gpt4 book ai didi

java - 停止读取 Java 中的标准输入

转载 作者:行者123 更新时间:2023-11-30 02:00:50 24 4
gpt4 key购买 nike

下面的代码将为我提供我想要的输入数据类型(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);
}



}

最佳答案

我会使用 trycatch 来找到正确的数据类型。不要使用多个输入,否则您将收到错误,只需使用 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

关于java - 停止读取 Java 中的标准输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52902041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com