Read integers and strings from a single line of a console

一个人想着一个人 提交于 2019-12-13 15:12:21

问题


The problem is like this:

I have two programs which takes input from a console but in different manner: 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 1st case 1 take inputs in 2 different lines like

1
2

so it gives correct answer but in 2nd case I removed the input.nextLine() statement to take inputs in a single line like:

1 2

it gives me number format exception why?? and also suggest me how I can read integers and strings from a single line of a console.


回答1:


The problem is that str has the value " 2", and the leading space is not legal syntax for parseInt(). You need to either skip the white space between the two numbers in the input or trim the white space off of str before parsing as an int. To skip white space, do this:

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

To trim the space off of str before parsing, do this:

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

You can also get fancy and read the two pieces of the 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);
}



回答2:


Assuming the input is 1 2, after this line

String str = input.nextLine();

str is equal to " 2", so it can't be parsed as int.

You can do simply:

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



回答3:


in your next line there is no integer ... its trying to create and integer from null ... hence you get number formate exception. If you use split string on temp1 then you get 2 string with values 1 and 2.



来源:https://stackoverflow.com/questions/25646835/read-integers-and-strings-from-a-single-line-of-a-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!