0

There are several questions I would like to ask, please refer the comment part I have added in the code, Thanks.

package test;

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

public class Test {
    /* Task:
     prompt user to read two integers and display the sum. prompt user to read the number again if the input is incorrect */

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

        boolean accept_a = false;
        boolean accept_b = false;
        int a;
        int b;

        while (accept_a == false) {
            try {
                System.out.print("Input A: ");
                a = input.nextInt();            /* 1. Let's enter "abc" to trigger the exception handling part first*/

                accept_a = true;
            } catch (InputMismatchException ex) {
                System.out.println("Input is Wrong");
                input.nextLine();                 /* 2. I am still not familiar with nextLine() parameter after reading the java manual, would you mind to explain more? All I want to do is "Clear Scanner Buffer" so it wont loop for the println and ask user to input A again, is it a correct way to do it? */

            }
        }

        while (accept_b == false) {
            try {
                System.out.print("Input B: ");
                b = input.nextInt();
                accept_b = true;
            } catch (InputMismatchException ex) {              /*3. Since this is similar to the above situation, is it possible to reuse the try-catch block to handling b (or even more input like c d e...) exception? */

                System.out.println("Input is Wrong");
                input.nextLine();
            }

        }
        System.out.println("The sum is " + (a + b)); /* 4. Why a & b is not found?*/

    }
}
MadProgrammer
  • 323,026
  • 21
  • 204
  • 329
Bilo
  • 125
  • 6

4 Answers4

1
  1. I am still not familiar with nextLine() parameter after reading the java manual, would you mind to explain more? All I want to do is "Clear Scanner Buffer" so it wont loop for the println and ask user to input A again, is it a correct way to do it?

The use of input.nextLine(); after input.nextInt(); is to clear the remaining content from the input stream, as (at least) the new line character is still in the buffer, leaving the contents in the buffer will cause input.nextInt(); to continue throwing an Exception if it's no cleared first

  1. Since this is similar to the above situation, is it possible to reuse the try-catch block to handling b (or even more input like c d e...) exception?

You could, but what happens if input b is wrong? Do you ask the user to re-enter input a? What happens if you have 100 inputs and they get the last one wrong?You'd actually be better off writing a method which did this for, that is, one which prompted the user for a value and returned that value

For example...

public int promptForIntValue(String prompt) {
    int value = -1;
    boolean accepted = false;
    do {
        try {
            System.out.print(prompt);
            value = input.nextInt();
            accepted = true;
        } catch (InputMismatchException ex) {
            System.out.println("Input is Wrong");
            input.nextLine();
        }
    } while (!accepted);
    return value;
}
  1. Why a & b is not found?

Because they've not been initialised and the compiler can not be sure that they have a valid value...

Try changing it something more like.

int a = 0;
int b = 0;
MadProgrammer
  • 323,026
  • 21
  • 204
  • 329
1
  1. Yes, it's okay. And will consume the non-integer input.
  2. Yes. If we extract it to a method.
  3. Because the compiler believes they might not be initialized.

Let's simplify and extract a method,

private static int readInt(String name, Scanner input) {
    while (true) {
        try {
            System.out.printf("Input %s: ", name);
            return input.nextInt();
        } catch (InputMismatchException ex) {
            System.out.printf("Input %s is Wrong%n", input.nextLine());
        }
    }
}

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

    int a = readInt("A", input);
    int b = readInt("B", input);
    System.out.println("The sum is " + (a + b));
}
Elliott Frisch
  • 183,598
  • 16
  • 131
  • 226
0

I have put comment to that question line.

package test;

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

public class Test {

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

    boolean accept_a = false;
    boolean accept_b = false;
    int a=0;
    int b=0;

    System.out.print("Input A: ");

    while (accept_a == false) {
        try {

            a = input.nextInt();  // it looks for integer token otherwise exception     

            accept_a = true;
        } catch (InputMismatchException ex) {
            System.out.println("Input is Wrong");
            input.next();    // Move to next other wise exception // you can use hasNextInt()         

        }
    }

    System.out.print("Input B: ");
    while (accept_b == false) {
        try {

            b = input.nextInt();
            accept_b = true;
        } catch (InputMismatchException ex) {     

            System.out.println("Input is Wrong");
            input.next();
        }

    }
    System.out.println("The sum is " + (a + b)); // complier doesn't know wheather they have initialised or not because of try-catch blocks. so explicitly initialised them.

}

}

-1

Check out this "nextLine() after nextInt()"

and initialize the variable a and b to zero

nextInt() method does not read the last newline character.

Community
  • 1
  • 1