如何在Java中检查用户输入是String,double还是long [英] How to check if user input is String, double or long in Java
本文介绍了如何在Java中检查用户输入是String,double还是long的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是java的初学者。我想首先检查用户输入是String还是Double或int。如果是String,double或减号,则应提示用户再次输入有效的int号。只有当用户输入有效数字时,程序才会跳转尝试。我一直在想几个小时,我没有任何用处。请帮助,谢谢!
I'm a beginner in java. I want to check first if the user input is String or Double or int. If it's String, double or a minus number, the user should be prompted to enter a valid int number again. Only when the user entered a valid number should then the program jump to try. I've been thinking for hours and I come up with nothing useful.Please help, thank you!
import java.util.InputMismatchException;
import java.util.Scanner;
public class Fizz {
public static void main(String[] args) {
System.out.println("Please enter a number");
Scanner scan = new Scanner(System.in);
try {
Integer i = scan.nextInt();
if (i % 3 == 0 && (i % 5 == 0)) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i + "は3と5の倍数ではありません。");
}
} catch (InputMismatchException e) {
System.out.println("");
} finally {
scan.close();
}
}
推荐答案
一个简单的解决方法是将整行/用户输入读取为String。
像这样的东西应该有效。 (未经测试的代码):
One simple fix is to read the entire line / user input as a String. Something like this should work. (Untested code) :
String s=null;
boolean validInput=false;
do{
s= scannerInstance.nextLine();
if(s.matches("\\d+")){// checks if input only contains digits
validInput=true;
}
else{
// invalid input
}
}while(!validInput);
这篇关于如何在Java中检查用户输入是String,double还是long的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文