How to Read Integer Value from the Standard Input in Java

how to read a long value from standard input in java?

use the nextLong method :

long l=scr.nextLong();

How to accept arguments in java from the user

just use the args in main

public static void main(String [] args) {
for (int i = 0; i < args.length; i += 2)
System.out.println("distance(" + args[i] + ", " + args[i+1] + ") = " + distance(args[i], args[i+1]));
}

and run it with java -jar app.jar kitten mitten

How do I read input that could be an int or a double?

Just use a double no matter what it is. There is no noticeable loss on using a double for integral values.

Scanner input = new Scanner(System.in); 
double choice = input.nextDouble();

Then, if you need to know whether you've gotten a double or not, you can check it using Math.floor:

if (choice == Math.floor(choice)) {
int choiceInt = (int) choice);
// treat it as an int
}

Don't mess with catching NumberFormatException, don't search the string for a period (which might not even be correct, for example if the input is 1e-3 it's a double (0.001) but doesn't have a period. Just parse it as a double and move on.

Also, don't forget that both nextInt() and nextDouble() do not capture the newline, so you need to capture it with a nextLine() after using them.



Related Topics



Leave a reply



Submit