首页 > 解决方案 > NoSuchElementException 使用扫描仪

问题描述

有人可以解释一下,为什么编译器在第 19 行向我抛出异常?我只是想不通...我在 HackerRank 上解决了一些练习,我知道,有解决方法,但是我的代码可以完美运行,直到 1 个测试用例引发异常。尽管我阅读了有关此的博客文章,但我根本无法弄清楚。

    import java.util.*;
    import java.io.*;
    import java.util.Scanner;

    class Solution{

        public static void main(String []args) {
            Scanner scanner = new Scanner(System.in);

            Map<String, String> contactBook = new HashMap<>();

            int n = scanner.nextInt();
            scanner.next();

            for(int i = 0; i < n; i++) {
                String name = scanner.nextLine();

                String phoneNumber = scanner.nextLine();

                contactBook.put(name, phoneNumber);
            }

            while(n-- > 0) {
                String search = scanner.nextLine();
                if(contactBook.containsKey(search)) {
                    System.out.println(search + "=" + contactBook.get(search));
                } else {
                    System.out.println("Not found");
                }
            }


        }
    }

标签: javaexceptionjava.util.scannernosuchelementexception

解决方案


您应该在代码中解决以下问题:

  1. 使用和nextLine()代替。使用 next() 或 nextFoo() 后检查Scanner 是否跳过 nextLine()?了解更多信息。nextInt()next()
  2. 尽管不是强制性要求,但无论何时您向用户请求输入,您都应该始终打印一条描述该输入的消息。
  3. 可能您的要求是将带有名称的联系人存储为键,这不是一个好的设计。如果您尝试放置另一个具有相同名称的联系人,则旧联系人将被新联系人替换,因为地图会将旧条目替换为具有相同键的新条目。您应该使用唯一键将数据存储在地图中,在这种情况下,唯一键可以是电话号码和您可以想到的其他一些唯一标识符。
  4. while您应该请求输入以在循环外搜索联系人;否则,将n多次提示用户在通讯录中输入要搜索的姓名。
  5. 在通讯录中找到姓名后,请确保break循环。如果循环没有被破坏(即在地图中找不到名称),最终的值n将变为-1您可以使用它来打印找不到名称的消息。

下面给出的是包含上述几点的代码:

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = 0;
        boolean valid;
        Map<String, String> contactBook = new HashMap<>();
        do {
            valid = true;
            System.out.print("Enter the number of contacts to be saved: ");
            try {
                n = Integer.parseInt(scanner.nextLine());
                for (int i = 0; i < n; i++) {
                    System.out.println("---Contact#" + (i + 1) + "---");
                    System.out.print("Enter the name: ");
                    String name = scanner.nextLine();
                    System.out.print("Enter the phone number: ");
                    String phoneNumber = scanner.nextLine();
                    contactBook.put(name, phoneNumber);
                }
            } catch (NumberFormatException e) {
                System.out.println("This is an invalid entry. Please try again.");
                valid = false;
            }
        } while (!valid);

        System.out.print("Enter the name to serach in the contact book: ");
        String search = scanner.nextLine();
        while (n-- > 0) {
            if (contactBook.containsKey(search)) {
                System.out.println(search + "=" + contactBook.get(search));
                break;
            }
        }
        if (n < 0) {
            System.out.println("Not found");
        }
    }
}

示例运行:

Enter the number of contacts to be saved: 3
---Contact#1---
Enter the name: Arvind
Enter the phone number: 1234567890
---Contact#2---
Enter the name: Kumar
Enter the phone number: 1023456789
---Contact#3---
Enter the name: Avinash
Enter the phone number: 2013456789
Enter the name to serach in the contact book: Kumar
Kumar=1023456789

另一个示例运行:

Enter the number of contacts to be saved: 2
---Contact#1---
Enter the name: Hegyi
Enter the phone number: 1234567890
---Contact#2---
Enter the name: Levente
Enter the phone number: 1023456789
Enter the name to serach in the contact book: Hello
Not found

另一个示例运行:

Enter the number of contacts to be saved: abc
This is an invalid entry. Please try again.
Enter the number of contacts to be saved: 10.5
This is an invalid entry. Please try again.
Enter the number of contacts to be saved: 2
---Contact#1---
Enter the name: Test1
Enter the phone number: 123
---Contact#2---
Enter the name: Test2
Enter the phone number: 234
Enter the name to serach in the contact book: Test2
Test2=234

推荐阅读