以下代码将为我提供所需的输入数据类型(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);
}
}
答案 0 :(得分:2)
我将使用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
答案 1 :(得分:0)
我认为您做错了。如果您想知道输入的数据类型,为什么要先读取它?您首先要读取并将其存储在input
变量中,然后确定下一个输入的输入的类型。因此,该消息也是错误的。我已经更改了您的代码以获得所需的输出
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.println ("You have entered an integer: "+ in.nextInt());
}
else if (in.hasNextDouble())
{
System.out.println ("You have entered a double: "+ in.nextDouble());
}
else if (in.hasNextLine())
{
System.out.println ("You have entered a string: "+ in.nextLine());
}
}