1

I am a beginner and i wrote a java program that allows you to enter n numbers and it displays the max, min and average only if the number -5 is entered, my program its not displaying correctly and i need some help. I want to use try/catch to catch errors when a string is entered instead integer.

        import java.util.Scanner;
public class Average{
public static void main(String[]args){

System.out.print("Enter any integer numbers or -5 to quit:");
        Scanner scan =new Scanner(System.in);
    double avg = 0.0;
    int number = -1;
    double avg = 0.0;
    double sum = 0;
    int count = 0; 
    int min = Integer.MAX_VALUE;
    int max = Integer.MIN_VALUE;

    try {
    while((scan.nextInt())!= -5)
       {
     if (count != 0) {
        avg = ((double) sum) / count;
    count++;
    }   
         if (number > max){
        max = number;
        }
        if(number < min){
       min = number;
        }
        catch (InputMismatchException e) {
      System.out.println("please enter only integer numbers");

    System.out.println("Average : " + avg); 
    System.out.println("maximum : " + max);
    System.out.println("minimum : " + min);
}
}
}
}
}
Sufyan
  • 21
  • 1
  • 7
  • Terrible choice for the question title. Recommend changing that to what your specific problem is. In addition to that, your question is actually missing the question part. – Takarii Aug 08 '16 at 13:24
  • My program its not displaying correctly the Average, maximum and minimum. And I also want to use try catch to cach errors. Eg: when the user inputs string instead of integer. please help me. – Sufyan Aug 08 '16 at 13:28
  • @Sufyan Please edit your question's title and description – C-Otto Aug 08 '16 at 13:39
  • @C-Otto ok, sorry for the inconvenience. – Sufyan Aug 08 '16 at 13:43
  • Possible duplicate of [How to handle infinite loop caused by invalid input using Scanner](https://stackoverflow.com/questions/3572160/how-to-handle-infinite-loop-caused-by-invalid-input-using-scanner) – Tom Sep 06 '17 at 21:40

5 Answers5

4

To get integer inputs in a loop, respond to an "exit" value, and guard against invalid inputs, I would use something like the template below.

Note that something critical that none of the answers so far has mentioned is that it is not good enough to simply catch InputMismatchException. You must also call your scanner object's nextLine() method to clear the bad input out of its buffer. Otherwise, the bad input will trigger the same exception repeatedly in an infinite loop. You might want to use next() instead depending on the circumstance, but know that input like this has spaces will generate multiple exceptions.

Code

package inputTest;

import java.util.Scanner;
import java.util.InputMismatchException;

public class InputTest {
    public static void main(String args[]) {
        Scanner reader = new Scanner(System.in);

        System.out.println("Enter integers or -5 to quit.");

        boolean done = false;
        while (!done) {
            System.out.print("Enter an integer: ");
            try {
                int n = reader.nextInt();
                if (n == -5) {
                    done = true;
                }
                else {
                    // The input was definitely an integer and was definitely 
                    // not the "quit" value.  Do what you need to do with it.
                    System.out.println("\tThe number entered was: " + n);
                }
            }
            catch (InputMismatchException e) {
                System.out.println("\tInvalid input type (must be an integer)");
                reader.nextLine();  // Clear invalid input from scanner buffer.
            }
        }
        System.out.println("Exiting...");
        reader.close();
    }
}

Example

Enter integers or -5 to quit.
Enter an integer: 12
    The number entered was: 12
Enter an integer: -56
    The number entered was: -56
Enter an integer: 4.2
    Invalid input type (must be an integer)
Enter an integer: but i hate integers
    Invalid input type (must be an integer)
Enter an integer: 3
    The number entered was: 3
Enter an integer: -5
Exiting...
MarredCheese
  • 9,495
  • 5
  • 59
  • 63
  • By bad input, I think you mean the '\n' present at the end of the line when n was tried to be read. Otherwise, that '\n' will be read in the next iteration of trying to read n. – deadLock Oct 04 '20 at 08:22
1

You would probably want

if(number > max) {
    max = number;
}
if(number < min) {
    min = number;
}

inside the while loop because right now you are only checking the last read value(also, there's no need to up the counter outisde the loop(after you have read -5, btw, why -5?o.O).

Also, you would probably want the min/max values initialised this way, because if your min value is bigger than 0, your code outputs 0. Same goes if your max value is below 0:

int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;

For the non-integer part: read up on exceptions and use a try-catch block to catch the InputMismatchException.

try {
    //while(scan.nextInt) here
} catch (InputMismatchException e) {
    //Do something here, like print something in the console
}

As someone else pointed out, if you want the average to not be truncated, cast sum to double: ((double) sum) / count.

Finally, but most important: try debugging it yourself before asking someone else.

taviss
  • 35
  • 8
  • thank you for your help.Please see the above code, I tried to edit, can you please tell me where I am doing it wrong? Best Regards @taviss – Sufyan Aug 08 '16 at 14:30
  • @Sufyan Please see this: https://docs.oracle.com/javase/tutorial/essential/exceptions/try.html – taviss Aug 08 '16 at 14:34
  • @Sufyan You need your entire code inside the try block. – taviss Aug 08 '16 at 14:36
1

Try this:

import java.util.Scanner;

public class Average {

static Scanner scan;

public static void main(String[] args) {
    System.out.println("Enter any integer numbers or -5 to quit:");
    scan = new Scanner(System.in);
    int number = -1, sum = 0, count = 0;
    int max = 0;
    int min = 0;
        while((number = scanNextInt()) != -5) {
            count++;
            sum = sum + number;

            if(number > max) {
                max = number;
            }

            if(number < min) {
                min = number;
            }
        }
            if(number == -5) {
                try {
                    System.out.println("Average : " + (sum / count));
                    System.out.println("Maximum : " + max);
                    System.out.println("Minimum : " + min);
                }catch(Exception e) {
                    //Error printing, so quit the program.  Look below.
                }
                //Quit
                System.exit(0);
            }
        scan.close();
    }
    static int scanNextInt() {
        try {
        return scan.nextInt();
        }catch(Exception e) {
            //Stop the program if the user inputs letters / symbols
            System.out.println("Invalid Number.");
            return -5;
        }
    }
}

Changes I've made:
1. I've created a method called scanNextInt() that returns scan.nextInt() if possible. If it will cause an error, it returns -5 to stop the program.
2. I've included the two if statements in the while loop so they actually work.
3. I've caught all of the possible errors, so you should not see any error messages

Note: This HAS been tested

coder98
  • 36
  • 1
  • 5
0

Firstly - you need to move the closing bracket of the while loop after the min number check to allow the checks to be performed for every number you read. And remove one count++ to avoid double counting.

To ignore illegal input you could use one of the other Scanner methods and read a String instead of int, then try to Integer.parseInt the String and wrap the parsing into a try catch.

FruBlom
  • 23
  • 1
  • 8
  • I moved the closing brackets and one count++ but still the code its not displaying correctly the average, maximum and the minimum. can you please edit my code and add the try catch for me? @FruBlom – Sufyan Aug 08 '16 at 13:46
  • See Joop Eggens answer. double has the required decimals for you, integers are only whole numbers. – FruBlom Aug 08 '16 at 13:53
0
    //count++;
    double avg = 0.0;
    if (count != 0) {
        avg = ((double) sum) / count;
    }
    System.out.println("Average : " + avg);

When both sides of the division are int then it is an integer division (result int, remainder of division thrown away).

Hence we cast one side, here sum to floating point:

(double) sum

And then it works.

Joop Eggen
  • 96,344
  • 7
  • 73
  • 121