0

Can someone explain me, why at line 19 the compiller throws me the excpetion? I just can't figure it out... I resolve some exercises on HackerRank and i know, there are the resolves, but my code works perfectly untill 1 test case throws the exception. And i simply can't figure it out, despite the fact that i read blog posts about that.

    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");
                }
            }


        }
    }
  • Change the line `scanner.next();` immediately following `int n = scanner.nextInt();` to`scanner.nextLine()`. [Here is why](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo?rq=1]) this should help. – Kevin Anderson Mar 30 '20 at 14:29
  • First of all, start with the [tour] and read [ask]. In particular, your question lacks the error message and the code as well could be reduced so it comes closer to a [mcve]. Also, first, you say it's the compiler, then you say it's a test case. What is actually happening? – Ulrich Eckhardt Mar 30 '20 at 19:24

2 Answers2

0

Change scanner.next(); to scanner.nextLine(); As explained in this link 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");
            }
        }

    }
}
Isuru Dilshan
  • 438
  • 5
  • 14
0

You should address the following things in your code:

  1. Use nextLine() instead of nextInt() and next(). Check Scanner is skipping nextLine() after using next() or nextFoo()? for more information.
  2. Although not a mandatory requirement, whenever you request an input from the user, you should always print a message describing the input.
  3. Probably your requirement is to store the contacts with name as a key, it's not a good design. If you try to put another contact with the same name, the old contact will be replaced with the new one as a map replaces the old entry with the new one having the same key. You should store data in a map with unique keys and in this situation, the unique key can be phone number and some other unique identifier you can think of.
  4. You should request input for searching a contact outside the while loop; otherwise, the user will be prompted n number of times to enter the name to be searched in the contact book.
  5. Once the name is found in the contact book, make sure to break the loop. If the loop doesn't get broken (i.e. the name is not found in the map), the value of n will become -1 eventually which you can use to print a message that the name could not be found.

Given below is the code incorporating the points mentioned above:

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");
        }
    }
}

A sample run:

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

Another sample run:

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

Another sample run:

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
Arvind Kumar Avinash
  • 50,121
  • 5
  • 26
  • 72