【问题标题】:Why can I only use 1 word in a string through input scanner? [duplicate]为什么我只能通过输入扫描器在字符串中使用 1 个单词? [复制]
【发布时间】: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()

标签: java string input


【解决方案1】:

使用 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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-04
    • 2014-05-06
    • 2021-09-06
    • 2014-11-04
    相关资源
    最近更新 更多