【问题标题】:Scanner interfering with another扫描仪干扰另一个
【发布时间】:2017-03-23 20:03:33
【问题描述】:

所以我正在尝试编写一个代码,提示用户使用基本计算器,或显示用户输入的给定句子中有多少单词的单词计数器,这是使用方法完成的。我已经弄清楚如何正确设置计算器,但是单词计数器给我带来了一些问题:

    public static int wordCounter(String str){

      String words[]=str.split(" ");
       int count=words.length;
        return count;
  }



public static void main(String[] args) {

   Scanner input = new Scanner(System.in);
   System.out.print("What do you want to do( calculator(0)/word counter(1) )? ");  
   //This runs and I select '1' for word counter
   int choice = input.nextInt();    //Input the choice here

   if (choice == 0) {     
   // It runs this selection statment, and since zero is not selected, 
   //it runs the word Counter branch
      calculator();
  }else{
     System.out.println("Please enter a sentence:");     // Tells me to enter a sentence
     String sentence=input.nextLine();  
    //^ This input is completely skipped and goes 
    //right to the 'System.out.print(); Statement.

    System.out.print("There are "+ wordCounter(sentence) + " words in the sentence.");     
    //^ This prints a 1 immediately after the branch is selected with '1'
}

}

我不确定哪里出了问题,因为这只发生在 if/else 语句中。做一些测试还告诉我,第一个扫描仪“int choice=input.nextInt()”似乎在某种程度上干扰了第二个扫描仪的字符串。任何保持类似格式的想法将不胜感激。

请原谅我的格式,它可能看起来不太好。

【问题讨论】:

  • 计算器方法在哪里???
  • 我没有包含它,因为该特定部分有效并且不是问题。如果你愿意,我可以包括它。

标签: java


【解决方案1】:

nextLine() 只会返回当前正在扫描的行的剩余部分。由于您在选择数字后会按回车键,因此它将捕获的只是一个空字符串。

要修复它,只需在获得整数后直接添加nextLine()

public String nextLine()

将此扫描器前进到当前行并返回被跳过的输入。此方法返回当前行的其余部分,不包括末尾的任何行分隔符。位置设置为下一行的开头。 由于此方法继续搜索输入以查找行分隔符,因此如果不存在行分隔符,它可能会缓冲所有搜索要跳过的行的输入。

https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()

【讨论】:

    【解决方案2】:

    问题是当您输入数字int choice = input.nextInt() 时,它只扫描整数,而不是换行符。因此,当您调用 input.nextLine() 时,它会立即返回一个空字符串。解决此问题的一种方法是将该行替换为

    int choice = Integer.parseInt(input.nextLine());
    

    【讨论】:

    • 这成功了!非常感谢你!一旦允许我将其标记为已解决!
    猜你喜欢
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-23
    相关资源
    最近更新 更多