0

How do I print the selected name in the array? I want to print the names i entered in the array and print it alone but when I try to run the code it says:

Exception in thread "main" java.util.InputMismatchException
    at java.base/java.util.Scanner.throwFor(Scanner.java:939)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
    at Main.main(Main.java:17)

here is my code:

Scanner in = new Scanner(System.in);

  int numOfLoop = in.nextInt(); //number of loops I want.
  String[] name = new String[numOfLoop]; //size of the array is depend on how many loop I want.

  //Getting the names using for loop.
  for(int i = 0; i < numOfLoop; i++) {

   name[i] = in.nextLine();

}

  int num = in.nextInt(); //The name I want to print depend on what number I enter here.

  //Reading the array one by one to print the name I want.
  for(int i = 0; i <numOfLoop; i++) {

   if(name[i] == name[num]) {

   System.out.println(name[i]);

  }

}

Input:

6 //How many loop and size of array I want.
john
mark
kevin
tesia
arthur
cody
5 //what ever is in array[5] will be printed.

Expected output: cody

Johny
  • 43
  • 9
  • It is `name[i].equals(name[num])` for string equality. Furthermore you only need to do this `if(name.length > num) System.out.println(name[num]);` – muasif80 Nov 21 '20 at 12:16
  • That will match the reference not the content. But if its only the item at the index is needed then equality check is not needed at all. @Abra – muasif80 Nov 21 '20 at 13:32

4 Answers4

3

There are several typical flaws in the code snippet to be addressed:

  • InputMismatchException - because not all new lines are consumed properly after calling to nextInt
  • name[i] == name[num] -- invalid String comparison, should be name[i].equals(name[num])
  • Missing check num < numOfLoop -- without that, ArrayOutOfBoundsException is possible

The fixed code would look as follows:

Scanner in = new Scanner(System.in);

System.out.println("Input the number of names: ");
int numOfLoop = in.nextInt(); //number of loops I want.
in.nextLine();  // skip remaining line
String[] name = new String[numOfLoop]; //size of the array is depend on how many loop I want.

System.out.println("Input the names, one per line: ");
//Getting the names using for loop.
for (int i = 0; i < numOfLoop; i++) {
    name[i] = in.nextLine();
}

System.out.println("Input the index of the name to print: ");
int num = in.nextInt(); //The name I want to print depend on what number I enter here.

//Reading the array one by one to print the name I want.
if (num >= 0 && num < numOfLoop) {
    System.out.println("Looking for name: " + name[num]);
    for (int i = 0; i <numOfLoop; i++) {
        if(name[i].equals(name[num])) {
            System.out.println(name[i] + " at index=" + i);
        }
    }
} else {
    System.out.println("Invalid index, cannot be greater or equal to " + numOfLoop);
}

Sample output:

Input the number of names: 
5
Input the names, one per line: 
john
jeff
joan
john
jake
Input the index of the name to print: 
0
Looking for name: john
john at index=0
john at index=3
Alex Rudenko
  • 15,656
  • 9
  • 13
  • 33
3

I also encountered this problem before, it seems that when you change from nextInt() the scanner instance did not read the \n character before it goes forward to nextLine().

Just adding in.nextLine(); before the For-loop should fix the problem.

Your error comes from the fact that the first entry in the array gets set as an empty string and the last name you put in gets read where you normally would put the second number, thus the nextInt() throws an error since it gets a String and not an int.

1

You do not need the second loop.

All you need to do is to check if (num >= 0 && num < numOfLoop) and display the value of name[num] or an error message.

import java.util.Scanner;

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

        int numOfLoop = Integer.parseInt(in.nextLine()); // number of loops I want.
        String[] name = new String[numOfLoop]; // size of the array is depend on how many loop I want.

        // Getting the names using for loop.
        for (int i = 0; i < numOfLoop; i++) {
            name[i] = in.nextLine();
        }

        int num = Integer.parseInt(in.nextLine()); // The name I want to print depend on what number I enter here.
        if (num >= 0 && num < numOfLoop) {
            System.out.println(name[num]);
        } else {
            System.out.println("Invalid index.");
        }
    }
}

Also, use Integer.parseInt(in.nextLine()) instead of in.nextInt() for the reason mentioned at Scanner is skipping nextLine() after using next() or nextFoo()?

A sample run:

5
Johny
Arvind
Kumar
Avinash
Stackoverflow
3
Avinash
Arvind Kumar Avinash
  • 50,121
  • 5
  • 26
  • 72
  • I also thought initially that the second loop might be redundant, though it helps to detect and print any duplicates in the `name` array :) – Alex Rudenko Nov 21 '20 at 12:30
  • is it not necessary to have the second for loop? @Alex Rudenko – Johny Nov 21 '20 at 13:30
  • @Johny - As per your requirement, you do not need the second loop. It will be easier for you to understand this answer if you go through it carefully. It will be further helpful to you if you run it and see if it behaves as you expected. Feel free to comment in case of any further doubt/issue. – Arvind Kumar Avinash Nov 21 '20 at 13:34
  • @Johny, it's up to you. _The loop_ allows to detect duplicate names as shown in [my answer ](https://stackoverflow.com/a/64942776/13279831) _Without_ the loop, you'll simply print only one item at the specified index. – Alex Rudenko Nov 21 '20 at 13:40
0
  Scanner in = new Scanner(System.in);
    int numOfLoop = in.nextInt(); //number of loops I want.
    String[] name = new String[numOfLoop]; //size of the array is depend on how many loop I want.

    for (int i=0; i<name.length; i++){
        String names = in.next();
        name[i] = names;
    }
    System.out.println("The names array: " + Arrays.toString(name));

    for(int index=0;index<name.length;index++) {
        System.out.print("Enter an index you want to print: ");
        index = in.nextInt();
        System.out.println("index " + index + " is:  " + name[index-1]);
    }
HassanYu
  • 55
  • 3
  • 10