简体   繁体   English

带有扫描仪的 Java 应用程序出错。 Next() 与 NextLine() 以及为什么我收到错误?

[英]Error in Java app with scanner. Next() vs NextLine() and why Im getting an error?

Im having an issue with my Java application.我的 Java 应用程序有问题。 The application is required to do the following:该应用程序需要执行以下操作:


(1) Prompt the user for a string that contains two strings separated by a comma. (1) 提示用户输入包含两个以逗号分隔的字符串的字符串。 (1 pt) (1 分)

Examples of strings that can be accepted: Jill, Allen Jill , Allen Jill,Allen Ex:可以接受的字符串示例: Jill, Allen Jill , Allen Jill,Allen Ex:

Enter input string: Jill, Allen输入输入字符串:吉尔,艾伦

(2) Report an error if the input string does not contain a comma. (2) 如果输入字符串不包含逗号,则报错。 Continue to prompt until a valid string is entered.继续提示,直到输入有效字符串。 Note: If the input contains a comma, then assume that the input also contains two strings.注意:如果输入包含逗号,则假设输入还包含两个字符串。 (2 pts) (2 分)

Ex:前任:

Enter input string: Jill Allen Error: No comma in string Enter input string: Jill, Allen输入输入字符串:Jill Allen 错误:字符串中没有逗号 输入输入字符串:Jill, Allen

(3) Extract the two words from the input string and remove any spaces. (3) 从输入字符串中提取两个单词并去除所有空格。 Store the strings in two separate variables and output the strings.将字符串存储在两个单独的变量中并输出字符串。 (2 pts) (2 分)

Ex:前任:

Enter input string: Jill, Allen First word: Jill Second word: Allen输入输入字符串:Jill, Allen 第一个词:Jill 第二个词:Allen

(4) Using a loop, extend the program to handle multiple lines of input. (4) 使用循环,扩展程序以处理多行输入。 Continue until the user enters q to quit.继续直到用户输入 q 退出。 (2 pts) (2 分)

Ex:前任:

Enter input string: Jill, Allen First word: Jill Second word: Allen输入输入字符串:Jill, Allen 第一个词:Jill 第二个词:Allen

Enter input string: Golden , Monkey First word: Golden Second word: Monkey输入输入字符串: Golden , Monkey 第一个词:Golden 第二个词:Monkey

Enter input string: Washington,DC First word: Washington Second word: DC输入输入字符串:Washington,DC 第一个词:Washington 第二个词:DC

Enter input string: q输入输入字符串:q


My Code:我的代码:

package parsestrings;

import java.util.Scanner;

public class ParseStrings {

    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in); // Input stream for standard input
        Scanner inSS = null;                   // Input string stream
        String lineString = "";                // Holds line of text
        String firstWord = "";                 // First name
        String secondWord = "";                  // Last name
        boolean inputDone = false;             // Flag to indicate next iteration

        // Prompt user for input
        System.out.println("Enter input string: ");

        // Grab data as long as "Exit" is not entered
        while (!inputDone) {

            // Entire line into lineString
            lineString = scnr.next();

            // Create new input string stream
            inSS = new Scanner(lineString);

            // Now process the line
            firstWord = inSS.next();

            // Output parsed values
            if (firstWord.equals("q")) {
                System.out.println("Exiting.");

                inputDone = true;

                if (firstWord.matches("[a-zA-Z]+,[a-zA-Z]+")) {
                    System.out.print("Input not two comma separated words");
                }
            } else {
                secondWord = inSS.next();

                System.out.println("First word: " + firstWord);
                System.out.println("Second word: " + secondWord);

                System.out.println();
            }
        }
        return;
    }
}

The error Im getting returned:我返回的错误:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1371)
    at parsestrings.ParseStrings.main(ParseStrings.java:53)
Java Result: 1

Scanner.next doc says: Scanner.next文档说:

Throws: NoSuchElementException - if no more tokens are available抛出: NoSuchElementException - 如果没有更多可用的令牌

Reason for your exception:您的例外原因:

lineString = scnr.next(); // this is reading just one word (token)
//...
inSS = new Scanner(lineString); // this creates a new scanner with a string consisting in just one word
firstWord = inSS.next(); // this reads the word loaded in the inSS scanner
//...
secondWord = inSS.next(); // here is the problem. There are no more words left in this scanner (tokens) and throws the exception.

So It would work if you change this line:因此,如果您更改此行,它将起作用:

lineString = scnr.next();

with this:有了这个:

lineString = scnr.nextLine();

Scanner.nextLine will read the entire line as you are expecting. Scanner.nextLine将按照您的预期读取整行。 Anyway the user can input one word.无论如何用户可以输入一个词。 So it would be nice to validate the input before proceding.所以在继续之前验证输入会很好。 You can do it like this:你可以这样做:

lineString = scnr.nextLine();

if(lineString == null || lineString.length() == 0 || lineString.split("\\s+").length < 2){
    System.out.println("2 words required. Try again:");
    continue;
}

Here I'm using a regular expression to validate that there is more than one word in the input.在这里,我使用正则表达式来验证输入中是否有多个单词。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM