从控制台

从控制台

问题描述:

问题的单线读整数和字符串是这样的:从控制台

我有两个节目,其需要从控制台输入,但在不同的方式: 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之外的空格。要跳过空格,这样做:

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

是的,它的工作表示感谢。 – Spartan 2014-09-03 14:41:46

假设输入是1 2,这条线

String str = input.nextLine(); 

str等于" 2"之后,因此它不能被解析为INT。

你可以简单地做:

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

是的,但是这个问题的解决方案是什么? – Spartan 2014-09-03 14:31:49

+0

@pushpendra我提供了解决问题的代码。 – 2014-09-03 14:32:31

+0

解决方案是input.skip(“\\ s *”);因为在我们需要真正的字符串如“abc”的情况下,那么您的解决方案是不够的。 – Spartan 2014-09-03 15:07:03

在你的下一行有没有整...它试图创建和空整数...所以你会得到数甲例外。如果在temp1上使用分割字符串,则会得到2个值为1和2的字符串。