Ahmar
Ahmar

Reputation: 3877

Detecting enter key in java

I have tried to get user input with scanner and if user press enter then proceed to next input statement. but it print all at once.

public class MainRDS 
{
    public static void main(String[] args) 
    {
        Scanner in = new Scanner(System.in);
        String path;
        String name;
        String ext;
        String date;

        System.out.println("Directory search by path, name, extension, content and date.");
        System.out.print("\nEnter Starting directory for the search (link c:"+"\\"+"temp) : ");
        path = in.next();

        System.out.print("\nEnter the file name (like myFile or enter for all) : ");

        if((name = in.nextLine()).length() > 0)
        System.out.print("\nEnter the file extenstion (like txt or enter for all) : ");

        if((ext = in.nextLine()).length() > 0)
        System.out.print("\nEnter last modified date (like 11/21/2012 or enter for any) : ");

        date = in.nextLine();
    }
}

output :

Directory search by path, name, extension, content and date.

Enter Starting directory for the search (link c:\temp) : c:

Enter the file name (like myFile or enter for all) : myfile

Enter last modified date (like 11/21/2012 or enter for any) : 

required output:

Directory search by path, name, extension, content and date.  
Enter starting directory for the search (like c:\temp): c:\temp 
Enter the file name (like myFile or enter for all):  
Enter the file extension (like txt or enter for all): txt 
Enter content to search for (like comp121 or enter for any):  
Enter last modified date (like 11/21/2013 or enter for any): 11/1/2011 

Upvotes: -1

Views: 5383

Answers (4)

BobTheBuilder
BobTheBuilder

Reputation: 19304

Got It!

you need to use:

path = in.nextLine();

Otherwise, name = in.nextLine() catches the path's "enter" key and doesn't get any value.

Upvotes: 1

goravine
goravine

Reputation: 266

Change

path = in.next();

To

path = in.nextLine();

Tested it, all is printed out and worked fine!

Upvotes: 0

DBroncos1558
DBroncos1558

Reputation: 141

I just tested your code and it does make the user press the "enter" key.. can you explain what you are looking for more specifically? As others have stated just change your Scanner:

Scanner in = new Scanner(System.in);

Upvotes: 0

Freak
Freak

Reputation: 6883

Your code is perfectly fine.You just need to replace your first line

Scanner in = Scanner(System.in);

with

Scanner in =new Scanner(System.in);


I am unable to understand that how you tested this code, because this is not a running code due to Scanner in = Scanner(System.in); this line

Upvotes: 1

Related Questions