繁体   English   中英

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

[英]User input other than print prompt and scanner

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

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?

您可以使用文件重定向。

program < file

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

java -jar /home/Stephanie/NetBeansProjects/cBelow/dist/cBelow.jar -userinputhere <file

或者您可以从程序中的文件中读取。 你可以选择这个

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

当您运行命令时:

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
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM