从控制台的一行中读取整数和字符串 [英] Read integers and strings from a single line of a console
问题描述
问题是这样的:
我有两个程序从控制台以不同方式获取输入:
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);
在第一种情况下,1在2条不同的行中输入
In 1st case 1 take inputs in 2 different lines like
1
2
so它给出了正确的答案,但是在第二种情况下,我删除了 input.nextLine()
语句以将输入内容放在一行中,例如:
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.
推荐答案
问题是 str
的值是 2
,并且前导空格不是 parseInt()的合法语法
。您需要跳过输入中两个数字之间的空格,或者将 str
的空格修剪掉,然后解析为 int
。要跳过空格,请执行以下操作:
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();
在之前缩小 str
的空间解析,执行以下操作:
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);
}
这篇关于从控制台的一行中读取整数和字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!