Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 989
newplayer12132 Avatar asked Jul 26 '15 21:07

newplayer12132


People also ask

How do you read a double scanner?

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.

How do you read a double in Java?

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.

How do you check if an input is a double Java?

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.


1 Answers

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.

like image 112
Paul Sasik Avatar answered Sep 20 '22 06:09

Paul Sasik