在我的程序中,用户用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.");
}
}
}
该方案显示此错误:
你是什么意思“只采取浮动部分”?你的意思是“一切都在”TEMP“之后?如果是这样,子串可能是你的朋友... –
这是一个字符串,找出数字开始的位置,提取那部分字符串,然后http://stackoverflow.com/questions/7552660/java-convert-float-to-string-and-string-to-float –
作为建议,您希望使用'Scanner#nextLine'而不是'Scanner#next',因为后者会读取'' TEMP“'而不是float部分 –