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

newplayer12132 picture newplayer12132 · Jul 26, 2015 · Viewed 27.6k times · Source

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.

Answer

Paul Sasik picture Paul Sasik · Jul 27, 2015

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.