[英]Command line arguments not read in intellij, java?
I am trying to to simply read the input of a user in my program. 我试图简单地读取程序中用户的输入。
import java.util.ArrayList;
import java.util.Scanner;
public class My_Counter {
public static void main (String[] args){
Scanner my_scan = new Scanner(System.in);
System.out.println("waiting for your number: \n");
int num2 = my_scan.nextInt();
System.out.println(num2);
}
}
Then I go to Run -» Edit Configurations -» and add in field "program arguments" one number. 然后我转到运行-»编辑配置-»并在字段“程序参数”中添加一个数字。 And then when I press run configuration, the program just returns:
然后,当我按运行配置时,该程序仅返回:
waiting for your numbers:
I have checked in the web already, but I cannot find anyone having the issue as me, it seemed that it has to work like this?? 我已经在网上签过帐,但是找不到像我这样的人,看来它必须像这样工作? Or am I missing something?
还是我错过了什么? I am using the IDE on the newest Ubuntu version.
我在最新的Ubuntu版本上使用IDE。
Command line arguments are stored as Strings in the String[] args
array of your main method. 命令行参数作为字符串存储在main方法的
String[] args
数组中。
You're not accessing the array but instead open up a Scanner which reads userinputs from the console during runtime . 您不是在访问数组,而是打开一个Scanner,该Scanner 在运行时从控制台读取用户输入。 Also
Scanner#nextInt
is a blocking operation. Scanner#nextInt
也是阻止操作。 Which means the program is 'suspended' until an input occurs from the underlying InputStream
( System.in
/ stdin in this case). 这意味着程序将被“挂起”,直到来自基础
InputStream
的输入(在这种情况下为System.in
/ stdin)。
In short: You've not accessed command line arguments but rather user input. 简而言之:您没有访问命令行参数,而是访问用户输入。
Try to input any number between Integer.MIN_VALUE
and Integer.MAX_VALUE
after the "waiting for your number" prompt and it will echo the entered value. 尝试在“等待您的号码”提示后输入
Integer.MIN_VALUE
和Integer.MAX_VALUE
之间的任何数字,它将回显输入的值。
To achiev your intended implementation you can go with something as follows: 为了实现预期的实现,可以采取以下措施:
public static void main( String[] args )
{
System.out.println( Integer.parseInt( args[0] ) );
}
If you want to read the number from the command line arguments, eg, when you run java -jar <my-class-compiled>.jar 15
or in your IDE (in order to pass the number 15
to your program) you will have to retrieve that number like this: 如果您想从命令行参数读取数字,例如,当您运行
java -jar <my-class-compiled>.jar 15
或在您的IDE中(为了将数字15
传递给程序)时,检索这样的数字:
public static void main(String[] args) {
String numberAsString = args[0]; // Will be "15"
try {
int number = Integer.parseInt(numberAsString);
} catch (Exception e) { // Manage a possible exception
System.out.println("The argument is not a valid Integer");
}
// Do your stuff...
}
In the other hand, if you want to pass a number on execution time, like a prompt, you will have to use Scanner.nextInt
, ie: https://www.tutorialspoint.com/java/util/scanner_nextint.htm 另一方面,如果要在执行时传递数字,如提示,则必须使用
Scanner.nextInt
,即: https : Scanner.nextInt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.