gpt4 book ai didi

java - 从控制台的一行读取整数和字符串

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:23:24 24 4
gpt4 key购买 nike

问题是这样的:

我有两个程序以不同的方式从控制台获取输入: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 条不同的行中输入

1
2

所以它给出了正确的答案,但在第二种情况下,我删除了 input.nextLine() 语句以在一行中获取输入,例如:

1 2

为什么给我数字格式异常??并建议我如何从控制台的一行中读取整数和字符串。

最佳答案

问题在于 str 的值为 "2",并且前导空格不是 parseInt() 的合法语法。在解析为 int 之前,您需要跳过输入中两个数字之间的空白或修剪 str 中的空白。要跳过空格,请执行以下操作:

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

要在解析之前去除 str 的空间,请执行以下操作:

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

你也可以想象一下,一次性读完这行的两部分:

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

关于java - 从控制台的一行读取整数和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25646835/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com