【问题标题】:NoSuchElementException using ScannerNoSuchElementException 使用扫描仪
【发布时间】:2020-03-30 14:13:23
【问题描述】:

有人可以解释一下,为什么编译器在第 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");
                }
            }


        }
    }

【问题讨论】:

  • 将紧跟在int n = scanner.nextInt(); 之后的行scanner.next(); 更改为scanner.nextLine()Here is why 这应该会有所帮助。
  • 首先,从tour 开始阅读How to Ask。特别是,您的问题缺少错误消息,并且代码也可以减少,因此它更接近minimal reproducible example。另外,首先,你说它是编译器,然后你说它是一个测试用例。实际发生了什么?

标签: java exception java.util.scanner nosuchelementexception


【解决方案1】:

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

  1. 使用nextLine() 代替nextInt()next()。更多信息请查看Scanner is skipping nextLine() after using next() or nextFoo()?
  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

【讨论】:

  • 感谢您为解释我所做的努力。我得到了所有的分数。也感谢您重写代码!帮助很大!为你竖起大拇指:D
  • @HegyiLevente - 不客气。祝你成功!
【解决方案2】:

改变scanner.next();到scanner.nextLine();如此链接中所述https://stackoverflow.com/a/24773533/7877099

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

public 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.nextLine();
        for (int i = 0; i < n; i++) {
            String name = scanner.nextLine();

            String phoneNumber = scanner.nextLine();

            contactBook.put(name, phoneNumber);
            System.out.println(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");
            }
        }

    }
}

【讨论】:

    猜你喜欢
    • 2013-03-04
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多