除打印提示和扫描仪以外的用户输入

时间:2012-11-05 16:53:04

标签: java user-input

我写了一个程序,询问用户输入如下:

System.out.println("Where would you like the output file to end up? (full path and desired file name): ");
Scanner out_loc = new Scanner(System.in);
output_loc = out_loc.nextLine();

...

System.out.println("Hey, please write the full path of input file number " + i + "! ");
System.out.println("For example: /home/Stephanie/filein.txt");
Scanner fIn = new Scanner(System.in);

我多次问这样的输入,但如果你错误输入会很痛苦,因为那时你必须杀死程序并重新运行。在运行程序时,有一种简单的方法可以一次性输入所有内容吗?如何在运行时在命令行中声明它?

java -jar /home/Stephanie/NetBeansProjects/cBelow/dist/cBelow.jar -userinputhere?

2 个答案:

答案 0 :(得分:2)

您可以使用文件重定向。

program < file

将文件发送到程序的标准输入。在你的情况下,

java -jar /home/Stephanie/NetBeansProjects/cBelow/dist/cBelow.jar -userinputhere&lt;文件

或者您可以从程序中的文件中读取。您可以将此选项设为

InputStream in = args.length < 1 ? System.in : new FileInputStream(args[0]);
Scanner scan = new Scanner(in); // create the scanner just once!

答案 1 :(得分:0)

以命令运行命令:

  

java -jar /home/Stephanie/NetBeansProjects/cBelow/dist/cBelow.jar -userinputhere?

它运行您的主要类的public static void main(String[] args)方法,您可以直接将userinputhere作为:

  public static void main(String[] args)
     String userinputhere = args[0];
     ..... rest of your code
   }

如果有多个用户输入,您可以将它们全部显示为:

  public static void main(String[] args)
      String userinput1 = args[0];
      String userinput2 = args[1];
      String userinput3 = args[2];
      //and so on..
      ..... rest of your code
  }
相关问题