Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Exception Handling/Logic Problems

  1. #1
    Member
    Join Date
    Aug 2020
    Posts
    42
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Exception Handling/Logic Problems

    Hello! So I'm working on a Java program that asks the user how many grades they would like to input, then asking them to enter those grades. From which it throws into an array, some math happens to get the average of those grades, the max grade given, etc. I am trying to do some exception handling so if the user tries to input an invalid value. Rather than throwing an 'InputMismatchException' it instead outputs, "Invalid Value/Amount" or the like. I've done something like this before, but can't quite remember how to do it. Any help is appreciated. I'll paste the code below:

    What I've tried:
    I've tried to use a boolean variable which should be in the code, to check if the given amount if an 'int' or not. If it is false, I was trying to have it in an if-statement to check and exit the program with the output before that. I've only tried that and moving it higher in my code thinking that perhaps I placed it in the wrong spot.

     
    import java.text.DecimalFormat;
    import java.util.Scanner;
     
    public class testingCode {
     
    	public static void main(String[] args) {
     
    		//creating the scanner object
    		Scanner  input = new Scanner(System.in);
    		//Creating our DecimalFormat
    		DecimalFormat df = new DecimalFormat("0.00");
     
    		//Ask User for scores
    		System.out.println("How many scores do you want to enter?");
    		//boolean variable to handle non-integer values
    		boolean hasInt = input.hasNextInt();
    		int size = input.nextInt();
     
     
    		//if-statement handling amount of size is less than 0 or a non-integer
    		if(size <= 0 || !hasInt) {
    			System.out.println("Invalid Amount.");
    			System.exit(0);
    		}//end if-statement
     
    		//Array
    		int[] score = new int[size];
     
    		int max = -1;
    		int sum = 0;
    		System.out.println("Please enter in " + size + " scores between 0-50");
    		for(int index = 0; index < score.length; index++) {
     
    			//take in the score and put it the array at the index
    			score[index] = input.nextInt();
     
    			//compare the value of the variable at that index to max
    			if(score[index] > max)
    				max = score[index];
     
    			sum += score[index];
     
    		}//end for
     
    		System.out.println("The max score is: " + max);
     
    		double average = (double)sum/score.length;
     
    		System.out.println("The average is: " + average);
     
    		//standard deviation
    		int total = 0;
    		for(int index = 0; index < score.length; index++) {
    			total += Math.pow(score[index] - average, 2);
    		}//end for
     
    		double standardDeviation = Math.sqrt(total * 1.0 / score.length);
     
    		System.out.println("Standard Deviation: " + df.format(standardDeviation));
     
    	}//end main
     
    }//end class
    Last edited by HyperRei; April 28th, 2021 at 07:54 PM.

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Exception Handling/Logic Problems

    What is it you want the program to do?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Aug 2020
    Posts
    42
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: Exception Handling/Logic Problems

    Hello, I would like the program to handle non-integer inputs essentially. Within Part 1, I would like it to ONLY take in values 1 and higher. Any value that is a non-int or 0 or <0 will lead to an if-statement checking for that, should any of those options be true. It will output, "Invalid Amount" and exit the program. For Part 2, if the value given is less than 0, higher than 50, or a non-integer, it is checked by an if-statement where should any of those be true, it will output, "Invalid Value." and once again, exit the program there. I hope this makes it more clear.

    Edit:
    I should state that the program works fine if you follow with what is saying, BUT by chance if the user inputs a character then a number. I would like the program to be able to handle those scenarios basically.

    Part 1:
    import java.text.DecimalFormat;
    import java.util.Scanner;
     
    public class testingCode {
     
    	public static void main(String[] args) {
     
    		//creating the scanner object
    		Scanner  input = new Scanner(System.in);
    		//Creating our DecimalFormat
    		DecimalFormat df = new DecimalFormat("0.00");
     
    		//Ask User for scores
    		System.out.println("How many scores do you want to enter?");
    		//boolean variable to handle non-integer values
    		boolean hasInt = input.hasNextInt();
    		int size = input.nextInt();
     
     
    		//if-statement handling amount of size is less than 0 or a non-integer
    		if(size <= 0 || !hasInt) {
    			System.out.println("Invalid Amount.");
    			System.exit(0);
    		}//end if-statement

    Part 2:
    //Array
    		int[] score = new int[size];
     
    		int max = -1;
    		int sum = 0;
    		System.out.println("Please enter in " + size + " scores between 0-50");
    		for(int index = 0; index < score.length; index++) {
     
    			//take in the score and put it the array at the index
    			score[index] = input.nextInt();
     
    			//compare the value of the variable at that index to max
    			if(score[index] > max)
    				max = score[index];
     
    			sum += score[index];
     
    		}//end for

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Exception Handling/Logic Problems

    Ok that sounds like the conditions can be tested for with if statements. What problems are you having trying to write if statements?
    Use the Scanner class's hasNextInt method to test if the user has entered an int value before calling nextInt.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member
    Join Date
    Aug 2020
    Posts
    42
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: Exception Handling/Logic Problems

    It was the order of that if-statement. I managed to get the program to work now finally how I wanted it. It handles those exceptions now. My only question now, if you don't mind answering, would be what could I do to make this more efficient/readable? If there are any improvements to be made. Anything is appreciated, and thank you for your time. The finished code is below:

     
    import java.text.DecimalFormat;
    import java.util.Scanner;
     
    public class testingCode {
     
    	public static void main(String[] args) {
     
    		//creating the scanner object
    		Scanner  input = new Scanner(System.in);
    		//Creating our DecimalFormat
    		DecimalFormat df = new DecimalFormat("0.00");
     
    		//variable for 'size' of array
    		int size = 0;
     
    		//Ask User for scores
    		System.out.println("How many scores do you want to enter?");
    		//boolean variable to handle non-integer values
    		boolean hasInt = input.hasNextInt();
    		if(hasInt) {
    			size = input.nextInt();
    			if(size <= 0) {
    				System.out.println("Invalid Amount.");
    				System.exit(0);
    			}//end if
    		} else {
    			System.out.println("Invalid Amount.");
    			System.exit(0);
    		}//end if-else
     
    		//Array
    		int[] score = new int[size];
     
    		int max = -1;
    		int sum = 0;
    		System.out.println("Please enter in " + size + " scores between 0-50");
    		//Exception Handling Below for Non-Integer values or values less than 0 or greater than 50
    		hasInt = input.hasNextInt();
    		if(hasInt) {
    			for(int index = 0; index < score.length; index++) {
     
    				//take in the score and put it the array at the index
    				score[index] = input.nextInt();
    				//Handling Integer Values outside of range
    				if(score[index] < 0 || score[index] > 50) {
    					System.out.println("Invalid Amount.");
    					System.exit(0);
    				}
     
    				//compare the value of the variable at that index to max
    				if(score[index] > max)
    					max = score[index];
     
    				sum += score[index];
    			}//end if
    		} else {
    			System.out.println("Invalid Value.");
    			System.exit(0);
    		}//end if-else
     
    		System.out.println("The max score is: " + max);
     
    		double average = (double)sum/score.length;
     
    		System.out.println("The average is: " + average);
     
    		//standard deviation
    		int total = 0;
    		for(int index = 0; index < score.length; index++) {
    			total += Math.pow(score[index] - average, 2);
    		}//end for
     
    		double standardDeviation = Math.sqrt(total * 1.0 / score.length);
     
    		System.out.println("Standard Deviation: " + df.format(standardDeviation));
     
    	}//end main
     
    }//end class

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Exception Handling/Logic Problems

    These comments are completely redundant. get rid of any similar ones that only repeat what the code is obviously doing
    //creating the scanner object
    Scanner input = new Scanner(System.in);
    //Creating our DecimalFormat

    No need for a variable, put the method in the if
    boolean hasInt = input.hasNextInt();
    if(hasInt) {

    if( input.hasNextInt()) {
    If you don't understand my answer, don't ignore it, ask a question.

  7. The Following User Says Thank You to Norm For This Useful Post:

    HyperRei (April 28th, 2021)

  8. #7
    Member
    Join Date
    Aug 2020
    Posts
    42
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Thumbs up Re: Exception Handling/Logic Problems

    Quote Originally Posted by Norm View Post
    These comments are completely redundant. get rid of any similar ones that only repeat what the code is obviously doing
    //creating the scanner object
    Scanner input = new Scanner(System.in);
    //Creating our DecimalFormat

    No need for a variable, put the method in the if
    boolean hasInt = input.hasNextInt();
    if(hasInt) {

    if( input.hasNextInt()) {
    Thank you Norm. I'll keep that in mind moving forward. Have a great day.

Similar Threads

  1. Exception Handling
    By LinuxPower in forum Java Theory & Questions
    Replies: 4
    Last Post: September 2nd, 2013, 10:10 PM
  2. [SOLVED] Exception Handling
    By Melawe in forum What's Wrong With My Code?
    Replies: 2
    Last Post: December 21st, 2011, 07:39 PM
  3. Exception handling
    By JavaGirl9001 in forum Object Oriented Programming
    Replies: 1
    Last Post: November 26th, 2011, 08:45 PM
  4. Exception Handling
    By hello_world in forum What's Wrong With My Code?
    Replies: 5
    Last Post: August 5th, 2011, 05:47 PM
  5. Exception handling
    By AnithaBabu1 in forum Exceptions
    Replies: 6
    Last Post: August 27th, 2008, 09:37 AM

Tags for this Thread