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.
Command line arguments are stored as Strings in the String[] args
array of your main method.
You're not accessing the array but instead open up a Scanner which reads userinputs from the console during runtime . Also Scanner#nextInt
is a blocking operation. Which means the program is 'suspended' until an input occurs from the underlying InputStream
( System.in
/ stdin in this case).
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.
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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.