【问题标题】:Having issues with the Scanner again再次遇到扫描仪问题
【发布时间】:2016-02-11 14:21:05
【问题描述】:

我很难在 Java 中使用 Scanner。

我尽力找出这段代码的错误,但我找不到。

我运行它然后程序允许我选择一个“代码”以及“单词”和“类别”(如果代码是 d)。当我尝试输入另一个代码时,程序进入一个无限循环。请大家指出我的错误可能在哪里?

import java.util.*;
public class GrammarChecker {       
  public static void main(String [ ] args) 
  {
   Dicionary dicionary = new Dicionary();
   Grammar grammar = new Grammar();
   Item a;
   String word, category, specification;
   int count = 0;
   char code;
   Scanner entry = new Scanner(System.in); 
   System.out.println("What is the code?");
   code = entry.nextLine().charAt(0);                 
   switch(code)
   {
      case 'd':
          System.out.println ("How many words your dicionary will have");
          count = entry.nextInt();
          entry.nextLine(); 
          for(int i = 0; i < count; count--) 
          {
            System.out.println ("What is the word?");
            word = entry.nextLine();
            System.out.println ("What is the category?");
            category = entry.nextLine(); 
            a = new Item (word, category);
            dicionary.listWords(a);

          }
      break;

      case 'g':   
         System.out.println ("How many lines are you going to use to specify your grammar?");
         count = entry.nextInt();
         entry.nextLine();

         for(int j = 0; j < count; count--) 
         {
          System.out.println ("What is the specification?");
          specification = entry.nextLine(); 
          grammar.listStructure(specification);

         } 

      break;

      case 'c':
          System.out.println ("I only accept d ou g");
      break;

      case 'f':
            System.out.println ("I only accept d ou g");
      break;
    }

    System.out.println("Would you like to enter another code?");
    code = entry.nextLine().charAt(0);
    entry.nextLine();

  }  
}

【问题讨论】:

  • 是字典吗?还是错字? :)
  • 这是一个巴西的课堂作业,所以它是葡萄牙语的。我只是从葡萄牙语中直接翻译了这些词。

标签: java class oop methods bluej


【解决方案1】:

您的代码中没有循环来读取多行。所以它似乎在最后停留在entry.nextLine();。此外,您正在为 code 分配一个从未使用过的新值。试试这样的:

loop: while (entry.hasNextLine()) {
    code = entry.nextLine().charAt(0);
    switch (code) {
        // handle each case except 'e'
    case 'e':
        break loop;
    }
    System.out.println("Would you like to enter another code?");
    System.out.println("Otherwise press e");
}

【讨论】:

  • 感谢您的快速回复!我以前从未在 Java 中使用过标签。
  • 它们对于打破嵌套循环或嵌套在循环中的开关很有用。您还可以在切换后添加 if 语句并打印例如消息
【解决方案2】:

当您执行entry.nextLine() 时,它会尝试读取另一个值。我必须输入两次字符才能使程序结束。

run:
What is the code?
e
Would you like to enter another code?
a
a
BUILD SUCCESSFUL (total time: 5 seconds)

(这是在 Netbeans 中测试的) 但正如@Manos 所说,如果您想继续询问,您需要围绕所有代码进行循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 2012-10-05
    • 2014-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多