[英]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.