gpt4 book ai didi

java - 如何分隔与字符串输入的 float ?

转载 作者:行者123 更新时间:2023-12-02 04:19:16 31 4
gpt4 key购买 nike

在我的程序中,用户输入带有 TEMP 的 float 数字(例如 TEMP 10.05)。该程序应该只采用 float 部分并将其转换为 fareheit。最后以浮点形式打印出结果。我怎样才能做到这一点?

    public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("The following program takes a float value with the word 'TEMP'in celcius, and converts into farenheit");
System.out.println("Enter the temperature with TEMP: ");

while (true) {
String input = s.next();
//converting into farenheit
if (input != null && input.startsWith("TEMP")) {
float celsius = Float.parseFloat(input.substring(input.indexOf(' ') + 1));
float tempFaren=celcius+32.8;
// float=result
System.out.println("Temperature in farehheit is : "+tempFaren+ " F.");

}
}

}

程序显示此错误:

enter image description here

最佳答案

您的代码的问题在于您使用了

String input = s.next();

这仅返回TEMP。您需要使用

String input = s.nextLine();

这应该返回完整的字符串。

与你的问题无关,你也是converting the temperatures错误的。应该是

float tempFaren = celcius*1.8f + 32.0f;

关于java - 如何分隔与字符串输入的 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32974299/

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