I'm writing a program in which I need to take input from the keyboard. I need to take a number in, yet I'm not sure if it's an int
or a double
. Here's the code that I have (for that specific part):
import java.io.*;
import java.util.*;
//...
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
I know I can get a String
and do parseInt()
or parseDouble()
, but I don't know which one it'll be.
The nextDouble() method of java. util. Scanner class scans the next token of the input as a Double. If the translation is successful, the scanner advances past the input that matched.
The readDouble() method of DataInputStream class in Java is used to read eight input bytes and returns a double value. This method reads the next eight bytes from the input stream and interprets it into double type and returns. Specified By: This method is specified by readDouble() method of DataInput interface.
parseDouble(stringInput); when you scan the input as a String you can then parse it to see if it is a double. But, if you wrap this static method call in a try-catch statement, then you can handle the situation where a double value is not parsed.
Well, ints are also doubles so if you assume that everything is a double you will be OK with your logic. Like this:
import java.io.*;
import java.util.*;
Scanner input = new Scanner(System.in);
double choice = input.nextDouble();
It only get complex if you needed the input to be an integer for whatever reason. And then, parseInt() to test for int would be just fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With