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

2024-02-28

问题是这样的:

我有两个程序从控制台获取输入,但以不同的方式: 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()。您需要跳过输入中两个数字之间的空格或修剪掉空格str在解析为之前int。要跳过空白,请执行以下操作:

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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从控制台的一行读取整数和字符串 的相关文章

随机推荐