再次遇到扫描仪问题

时间:2015-11-10 16:13:57

标签: java class oop methods bluej

我很难在Java中使用Scanner。

我尽力找到此代码的错误,但我无法找到它。

我运行它然后程序允许我选择一个"代码"和#34;字"和"类别" (如果代码是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();

  }  
}

2 个答案:

答案 0 :(得分:0)

您的代码中没有循环来读取多行。所以它似乎最终陷入了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");
}

答案 1 :(得分:0)

执行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所说,如果你想继续问你需要围绕你的所有代码循环。