-1

我正在尝试使用 ArrayLists 在 Java 中实现电话簿,但是每当我尝试使用 next() 或 nextLine() 获取用户信息时,都会出现错误。这是收集和保存用户输入的方法。

public void saveContact() {
        String[] userInput = new String[3];
        String[] input = {"name", "age", "phone number"};
        String[] pattern = {".", "\\d", ".+\\d+"};
        for(int i=0; i < 3; i++) {
            try (Scanner sc = new Scanner(System.in)) {
                String name = "";
                while(!verifyUserInput(name, pattern[i])) {
                    System.out.printf("Enter contact's %s\n", input[i]);
                    name = sc.nextLine();
                userInput[i] = name;
                }
            }
        }
        phoneArrayList.add(userInput);
    }

每当我使用 nextLine() 我得到

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
    at PhoneDirectory.saveContact(PhoneDirectory.java:42)
    at MainClass.main(MainClass.java:19)

当我使用 next() 我得到

Exception in thread "main" java.util.NoSuchElementException
    at java.base/java.util.Scanner.throwFor(Scanner.java:937)
    at java.base/java.util.Scanner.next(Scanner.java:1478)
    at PhoneDirectory.saveContact(PhoneDirectory.java:42)
    at MainClass.main(MainClass.java:19)

我试过像这样使用 hasNext() 和 hasNextLine() ,但它只会导致无限循环。我不知道应该使用什么来获取用户输入而不会出现错误。

if(sc.hasNext()) {
    name = sc.next();
}

这是 verifyUserInput 方法

public boolean verifyUserInput(String input, String patt) {
        Pattern pattern = Pattern.compile(patt);
        Matcher m = pattern.matcher(input);
        return m.find();
    }
4

1 回答 1

-2

public class Test {
    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        String[] userInput = new String[3];
        String[] input = {"name", "age", "phone number"};
        String[] pattern = {".", "\\d", ".+\\d+"};

        boolean isAllInputValid = true;
        for (int i = 0; i < 3; i++) {
            System.out.printf("Enter contact's %s\n", input[i]);
            if (scan.hasNextLine()) {
                String inputStr = scan.nextLine();
                if (!verifyUserInput(inputStr, pattern[i])) {
                    isAllInputValid = false;
                    break;
                }
                userInput[i] = inputStr;
                System.out.println("contact's  " + input[i] + " is " + inputStr);
            }
        }
        if (isAllInputValid) {
            System.out.println("userInput = " + Arrays.toString(userInput));
        }

    }

    public static boolean verifyUserInput(String input, String patt) {
        Pattern pattern = Pattern.compile(patt);
        Matcher m = pattern.matcher(input);
        return m.find();
    }
}

于 2020-07-24T11:11:13.643 回答