0

我尝试使用扫描仪获取用户输入,如果用户按 Enter 键,则继续执行下一个输入语句。但它一次打印所有。

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

输出 :

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) : 

所需输出:

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 
4

4 回答 4

1

知道了!

你需要使用:

path = in.nextLine();

否则,name = in.nextLine()捕获路径的“输入”键并且不会获得任何值。

于 2013-03-06T07:38:03.883 回答
1

你的代码很好。你只需要替换你的第一行

Scanner in = Scanner(System.in);

Scanner in =new Scanner(System.in);


我无法理解您是如何测试此代码的,因为由于Scanner in = Scanner(System.in);这一行,这不是一个正在运行的代码

于 2013-03-06T07:24:36.417 回答
0

改变

path = in.next();

path = in.nextLine();

测试了一下,一切都打印出来了,运行良好!

于 2013-03-06T07:26:30.303 回答
0

我刚刚测试了你的代码,它确实让用户按下“输入”键。你能更具体地解释一下你在寻找什么吗?正如其他人所说,只需更改您的扫描仪:

Scanner in = new Scanner(System.in);
于 2013-03-06T07:22:00.473 回答