【发布时间】:2020-10-11 05:03:17
【问题描述】:
对 Java 来说还是很新,我在处理这个循环时遇到了麻烦。第一个问题是我只能为 newName 输入一个单词,如果我尝试输入多个单词,它也会使用 newCode 的输入并跳过。我只是不明白为什么我不能输入一个字符串中包含超过 1 个单词的名称。当我尝试添加一个包含 3 个单词的字符串时,它会跳过 newCode 然后引发错误。
int addAnother = 1;
while (addAnother == 1) {
System.out.print("Enter a new Subject Name: ");
String newName = input.next(); //only accepting a single word...
System.out.print("Enter a new Subject Code: ");
String newCode = input.next(); // must be entered in CAPS
Subject newSubject = new Subject(newName, newCode);//create object
if (newSubject.isValidCode(newCode) == true){
System.out.println("The code meets the requirements");
if (newSubject.codeExist(newCode, subjectList) == false){
subjectList.add(newSubject);
System.out.println("Your Subject has been added");
}
else
System.out.println("The code you entered already exists");
}
else
System.out.println("Your subject code does not "
+ "meet the requirements i.e. ITC206");
System.out.println ("\nEnter a new subject? 1=Yes 2=No");
addAnother = input.nextInt();
}
我只是不确定我做错了什么......
【问题讨论】:
-
input.next()总是只返回一个下一个令牌。如果你想输入更多的单词,你应该使用input.nextLine()。