Reading integers and strings from one console line

The problem is this:

I have two programs that take input from the console, but in different ways: 1)

Scanner input = new Scanner(System.in);
    int temp1 = input.nextInt();
    input.nextLine();
    String str = input.nextLine();
    int temp2 = Integer.parseInt(str);
    int total = temp1+temp2;

    System.out.println(total);

      

2)

 Scanner input = new Scanner(System.in);
    int temp1 = input.nextInt();
 // input.nextLine();
    String str = input.nextLine();
    int temp2 = Integer.parseInt(str);
    int total = temp1+temp2;

    System.out.println(total);

      

In the first case, 1 take input in 2 different lines like

1
2

      

so it gives the correct answer, but in the second case, I removed the operator input.nextLine()

to type the inputs on one line, like:

1 2

      

it gives me numerical formatted exception, why ?? and also suggest me how can I read integers and strings from one console line.

+3


source to share


3 answers


The problem is what str

matters " 2"

, and leading space is not legal syntax for parseInt()

. You need to either skip the space between the two numbers in the input, or trim the space in str

before parsing like int

. To skip a space, do the following:

input.skip("\\s*");
String str = input.nextLine();

      

To strip the space str

before parsing, do the following:



int temp2 = Integer.parseInt(str.trim());

      

You can also get fancy and read two parts of a line in one go:

if (input.findInLine("(\\d+)\\s+(\\d+)") == null) {
    // expected pattern was not found
    System.out.println("Incorrect input!");
} else {
    // expected pattern was found - retrieve and parse the pieces
    MatchResult result = input.match();
    int temp1 = Integer.parseInt(result.group(1));
    int temp2 = Integer.parseInt(result.group(2));
    int total = temp1+temp2;

    System.out.println(total);
}

      

+1


source


Assuming the input 1 2

, after this line

String str = input.nextLine();

      

str

is equal " 2"

, so it cannot be parsed as an int.



You can do simply:

int temp1 = input.nextInt();
int temp2 = input.nextInt();
int total = temp1+temp2;
System.out.println(total);

      

+1


source


your next line doesn't have an integer ... its trying to create and an integer from null ... hence you get a form formate exception. If you use a separator string in temp1, you get 2 lines with values ​​1 and 2.

0


source







All Articles