下面的代码将为我提供输入的数据类型(int,double或string),但是,当我运行代码时,就好像在执行之前需要其他输入一样。我希望我走在正确的道路上。
要么
Enter some stuff: 43
3
You have entered an integer: 43
在我输入其他字符(在本例中为43以下的3)之前,它不会运行。
感谢您的光临。
public static void main(String[] args)
{
// variables
Scanner in = new Scanner(System.in);
String input;
// Prompt user for stuff
System.out.print ("Enter some stuff: ");
// input stuff
input = in.next();
//determine and read type echo to use
if (in.hasNextInt())
{
System.out.print ("You have entered an integer: "+ input);
}
else if (in.hasNextDouble())
{
System.out.print ("You have entered a double: "+ input);
}
else if (in.hasNextLine())
{
System.out.print ("You have entered a string: "+ input);
}
}
我将使用try
和catch
以找到正确的数据类型。不要使用多个输入,否则您将得到所得到的错误,只需使用in.next()
一次,然后按如下所示处理值:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input;
// Prompt user for stuff
System.out.print ("Enter some stuff: ");
// input stuff
input = in.next();
//determine and read type echo to use
try {
int v = Integer.parseInt(input);
System.out.print ("You have entered an integer: " + input);
} catch (NumberFormatException nfe1) {
try {
double v = Double.parseDouble(input);
System.out.print ("You have entered a double: " + input);
} catch (NumberFormatException nfe2) {
System.out.print ("You have entered a string: " + input);
}
}
}
输出1:
Enter some stuff: 7
You have entered an integer: 7
输出2:
Enter some stuff: 3.0
You have entered a double: 3.0
输出3:
Enter some stuff: sfsdfasd
You have entered a string: sfsdfasd
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句