简体   繁体   English

从控制台的单行读取整数和字符串

[英]Read integers and strings from a single line of a console

The problem is like this: 问题是这样的:

I have two programs which takes input from a console but in different manner: 1) 我有两个程序从控制台输入但是以不同的方式: 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) 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个不同的行,如

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: 所以它给出了正确答案,但在input.nextLine()情况下,我删除了input.nextLine()语句,以便在一行中获取输入,如:

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. 并且还建议我如何从控制台的单行读取整数和字符串。

Assuming the input is 1 2 , after this line 假设输入为1 2 ,则在此行之后

String str = input.nextLine();

str is equal to " 2" , so it can't be parsed as int. str等于" 2" ,因此不能将其解析为int。

You can do simply: 你可以做到:

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

The problem is that str has the value " 2" , and the leading space is not legal syntax for parseInt() . 问题是str的值为" 2" ,而前导空格不是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 . 您需要跳过输入中两个数字之间的空白区域,或者在解析为int之前修剪str的空白区域。 To skip white space, do this: 要跳过空格,请执行以下操作:

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

To trim the space off of str before parsing, do this: 要在解析之前修剪str的空间,请执行以下操作:

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);
}

in your next line there is no integer ... its trying to create and integer from null ... hence you get number formate exception. 在你的下一行没有整数...它试图从null创建和整数...因此你得到数字格式异常。 If you use split string on temp1 then you get 2 string with values 1 and 2. 如果在temp1上使用split string,则会获得值为1和2的2个字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM