How do I separate a float number that was input with string?
在我的程序中,用户输入带有 TEMP 的
程序应该只取
我怎么能那样做?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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."); } } } |
程序显示此错误:
你的代码的问题在于你使用了
1 |
这只返回
1 |
这应该返回完整的字符串。
与您的问题无关,您还错误地转换了温度。应该是
1 | float tempFaren = celcius*1.8f + 32.0f; |
你可以使用 Float.parseFloat(yourString);
示例:
1 2 3 |
您可以使用以下方法:
1 2 3 4 5 6 |
像这样:
1 2 3 4 5 6 7 8 9 10 11 12 | while (true) { String input = s.next(); //converting into farenheit if (input != null && input.startsWith("TEMP")) { float celsius = extractFloatWithDefault(input, -999); if ( celsius > -999 ) { float tempFaren=celcius+32.8; System.out.println("Temperature in farehheit is :"+tempFaren+" F."); } else System.out.println("Please include a number"); } } |
此方法将提取它在字符串中找到的第一个数字并使用它,如果没有有效的浮点数或整数,则返回默认值。
试试这样的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | while (true) { String input = s.nextLine(); //converting into farenheit if (input != null && input.startsWith("TEMP")) { try{ double faren=Double.parseDouble(input.substring(input.lastIndexOf(' ')+1))+32.8; //float tempIntoFarenheit= input+32.8 System.out.println("Temperature in farenheit:"+faren); }catch(Exception e){ System.out.println("Something was wrong with the temperature, make sure the input has something like 'TEMP 50.0'"); System.out.println(e.toString()); } } else { System.out.println("Wrong input. Try again:"); } } |
可以使用indexOf查找第一个空格,substring获取空格位置后的字符串的test,parseFloat将字符串中的数字解析为浮点数:
1 |
同样的事情分解为步骤:
1 2 3 |
更新
您修改后的代码也无法编译(您在 "celcius" 中输入错误,以及其他问题)。
这会编译,并正确解析浮点部分:
1 2 3 4 |
最后,
另一种提取字符串末尾浮点值的方法是从开头去除非数字值,例如:
1 |
免责声明:我上面给出的示例都不适用于所有可能的输入,它们是针对您提供的示例输入量身定制的。如有必要,它们可以变得更加健壮。