gpt4 book ai didi

java - 扫描仪再次出现问题

转载 作者:太空宇宙 更新时间:2023-11-04 13:14:55 24 4
gpt4 key购买 nike

我在尝试使用 Java 中的扫描程序时遇到了困难。

我尽力查找这段代码的错误,但没找到。

我运行它,然后程序允许我选择一个“代码”以及“单词”和“类别”(如果代码是 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();

}
}

最佳答案

您的代码中没有循环来读取多行。所以它似乎在最后陷入了 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 - 扫描仪再次出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33634521/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com