2011-04-25 172 views
3

我试图选择阅读一个字符串与多个词,即。洛杉矶或纽约市。对于“出发”和“到达”,使用scanner.next()只会读取第一个,如果有两个单词并将它们在变量之间分开。 nextLine()也没有太多运气。这是我的代码:扫描仪 - Java的问题

  System.out.print("\nEnter flight number: "); 
      int flightNumber = Integer.valueOf(scanner.nextLine()); 
      System.out.print("\nEnter departing city: "); 
      String departingCity = scanner.nextLine(); 
      System.out.print("\nEnter arrival city: "); 
      String arrivalCity = scanner.nextLine(); 

我知道这是简单的东西,但我还没有弄明白。

这里的输入/输出瓦特/上面的代码:

输入航班号:29

输入出发城市:(立即它跳过到下一行)

输入到达城市:

----我真的会为----

输入航班号:29

回车出发城市:洛杉矶(能没有它跳过下输入到输入多个单词)

进不到货城市:堪萨斯城

+0

你希望你的输入看起来像什么?也就是说,您的输入将如何划分?列举所有可能性,然后可以确定如何使用扫描仪来做到这一点,或者即使扫描仪完全适合。 – BeeOnRope 2011-04-25 23:59:06

+0

请显示您当前的输入/输出是什么以及您的输入/输出应该是什么。这将是非常有用的。:) – Davidann 2011-04-25 23:59:48

+0

@skaffman,您对原始文章所作的编辑使得难以确定代码修复之前的问题。@tim调用'nextInt()',然后'nextLine()',这个组合导致了解析问题。 – hotshot309 2013-01-06 18:00:38

回答

6

你的问题是,下一个()不读取回车它会被你的下一个next()或nextLine()自动读取。使用nextLine()所有的时间和转换输入整数:

public static void main(String[] args) throws Exception { 
    Scanner scanner = new Scanner(System.in); 
    System.out.print("\nEnter flight number: "); 
    int flightNumber = Integer.valueOf(scanner.nextLine()); 
    System.out.print("\nEnter departing city: "); 
    String departingCity = scanner.nextLine(); 
    System.out.print("\nEnter arrival city: "); 
    String arrivalCity = scanner.nextLine(); 

} 
+0

+1更快(也是正确的:))。 – MByD 2011-04-26 00:15:34

+0

我把所有东西都切换到nextLine,并且像上面那样更改了int ...如果我首先得到一个NumberFormatException,并且如果我将它粘在不同的位置,它会跳过到达或离开输入。 – tim 2011-04-26 00:39:15

+0

更新后的代码高于 – tim 2011-04-26 00:40:07

0

Integer.parseInt(scanner.nextLine())也将工作 - 它返回一个int,而Integer.valueOf(scanner.nextLine())返回Integer

作为@Edwin Dalorzo建议的替代方法,您可以拨打nextInt()来获取输入流中的下一个标记,并从try to convert it to an int中获取下一个标记。如果转换为int不成功,则此方法将抛出InputMismatchException。否则,将只抓取的int值,输入。调用nextLine(),然后将获取int后面的行中输入的任何其他内容。此外,nextLine()消费换行符添加时,用户按下“输入”提交输入(它会超过它,并放弃它)。

如果你想确保用户没有按之前输入任何除了 int类型“输入”呼nextInt()第一,然后确保的nextLine()值为空。如果你不关心在int后面输入的任何内容,你可以忽略nextLine()返回的内容,但仍应该调用该方法来使用换行符。

为“java scanner next”或“java scanner nextLine”搜索StackOverflow以查找有关此主题的线程。