Skip to content
Advertisement

In IntelliJ IDEA, while taking input in an array from console, character of enter key is accepted as an element

I was seeing an example of linear search in an array in Java, and I wrote this code:

import java.util.*;
public class LinearSearch
{
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter no. of members: ");
        int l=sc.nextInt();
        String[] list=new String[l];
        System.out.println("Enter the members: ");
        for(int i=0;i<l;i++)
            list[i]=sc.nextLine();
        System.out.print("nEnter the member you want to search for: ");
        String ts=sc.nextLine();
        for(int i=0;i<l;i++)
        {
            if(list[i].equalsIgnoreCase(ts))
            {
                System.out.println("The member is at index " + i);
                break;
            }
            if(i==l-1)
                System.out.println("There is no such member");
        }
    }
}

But while running this code, due to the System.out.println() at the 10th line, the carriage return (of the println() ) is taken as the element at index 0. Further, as I enter more elements, after each element I need to press Enter key to start the next iteration, but with that, the carriage return of the Enter key is taken as input too. This is the output:

Enter no. of members: 5
Enter the members: 
a
b
c

Enter the member you want to search for: e
There is no such member

I did the following to prevent it:

System.out.println("Enter the members: ");
int j=0;
String in="";
while(list[l-1]==null)
{
    in=sc.nextLine();
    if(in.equals(String.valueOf((char)10))) //10 being the ASCII code of carriage return
        continue;
    else
    {
        list[j] = in;
        j++;
    }
}

But this doesn’t work, it still takes carriage return as an element. Is there any way to fix this issue ?

Advertisement

Answer

You need to skip line after nextInt() call as in the answer mentioned by @user16320675 in the comment

But, there is another bug in Intellij IDEA console, refer answer which kind of skips alternative nextLine() input. Hence, your call ends even when you just enter 3 values in this case but your array size is 5.

Refer

IDEA output

Your program is still correct. Just test your code in other terminal instead of IDEA console

Terminal Output

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement