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 catch
ing 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
"Integer Number Too Large" Error Message for 600851475143
How to Compare Two Dates Without the Time Portion
Regex to Match Only Commas Not in Parentheses
Convert Integer into Byte Array (Java)
Java Generating Non-Repeating Random Numbers
How to Split a Comma-Separated String
How to Handle Iframe in Selenium Webdriver Using Java
Why Would One Mark Local Variables and Method Parameters as "Final" in Java
How to Use a Tablename Variable for a Java Prepared Statement Insert
Why Does the Jtable Header Not Appear in the Image
How to Restart a Java Application
Java Random Always Returns the Same Number When I Set the Seed
Modify Request Parameter with Servlet Filter
In Java, How to Write a String Literal Without Having to Escape Quotes
Java String Remove All Non Numeric Characters But Keep the Decimal Separator
How to Correctly Get Image from 'Resources' Folder in Netbeans