英文:
Why can I only use 1 word in a string through input scanner?
问题
还相对新于Java,我在处理这个循环时遇到了问题。首先问题是,我只能输入一个单词作为newName,如果我尝试输入多个单词,它也会将输入用于newCode,然后跳过。我就是想不明白为什么我不能输入一个由多个单词组成的名字字符串。当我尝试添加一个包含3个单词的字符串时,它会跳过newCode,然后抛出一个错误。
int addAnother = 1;
while (addAnother == 1) {
System.out.print("输入新科目名称:");
String newName = input.next(); // 只接受一个单词...
System.out.print("输入新科目代码:");
String newCode = input.next(); // 必须使用大写输入
Subject newSubject = new Subject(newName, newCode); // 创建对象
if (newSubject.isValidCode(newCode) == true){
System.out.println("代码符合要求");
if (newSubject.codeExist(newCode, subjectList) == false){
subjectList.add(newSubject);
System.out.println("已添加您的科目");
}
else
System.out.println("您输入的代码已经存在");
}
else
System.out.println("您的科目代码不符合要求,例如 ITC206");
System.out.println("继续输入新科目吗? 1=是 2=否");
addAnother = input.nextInt();
}
我只是不确定我做错了什么...
英文:
Still fairly new to Java and I am having trouble with this loop. the first issue is that I can only enter a single word for newName, if I try and enter more then one word, it uses the input for the newCode as well and skips through. I just can't figure out why I cant enter a name that has more then 1 word in a string. when I try and add a string with 3 words in it it skips the newCode then throws an error.
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();
}
I am just not sure what I am doing wrong....
答案1
得分: 0
使用 nextLine() 方法替代 next() 方法。
private String read()
{
Scanner scanner = new Scanner(System.in);
return scanner.nextLine();
}
链接:https://www.geeksforgeeks.org/difference-between-next-and-nextline-methods-in-java/
英文:
Use nextLine() method instead of next().
private String read()
{
Scanner scanner = new Scanner(System.in);
return scanner.nextLine();
}
https://www.geeksforgeeks.org/difference-between-next-and-nextline-methods-in-java/
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论