问题
I was trying to do this:
import java.util.Scanner;
public class Prov{
public static void main(){
Scanner getInfo = new Scanner(System.in);
showInfo(getInfo.next());
}
public void showInfo(int numb){
System.out.println("You typed this integer: " + numb);
}
public void showInfo(double numb){
System.out.println("You typed this double: " + numb);
}
}
but it doesnt work no matter if I look for scanner.next or scanner.nextInt it wont just get a double when i write a double and an int when I type an int.
Thank You !
回答1:
next() method returns a String not a number, specifically not even an int or double, to fix this, you need to test if the next is a int or is a double. Ie:
if (getInfo.hasNextInt()) {
showInfo(getInfo.nextInt());
}else if(getInfo.hasNextDouble()) {
showInfo(getInfo.nextDouble());
}else{
//Neither int or double
}
Hope this helps!
回答2:
You can use
if (scanner.hasNextInt()) {
int i = scanner.nextInt();
} else if(scanner.hasNextDouble()) {
double d = scanner.nextDouble();
} else {
scanner.next(); // discard the word
I suggest you read the Javadoc for all the other options it has.
来源:https://stackoverflow.com/questions/19470591/detect-scanner-input-in-java-double-or-int