import java.io.*;

public class tempdetection {
public static int celciustofarenheit(int temp){
    int fTemp = ((9 * temp)/5) + 32;
    return fTemp;
}


public static void examineTemperature(int temp){
    System.out.println("\nTemperature is " + temp + " in celcius. Hmmm...");

    int fTemp = celciustofarenheit(temp);
    System.out.println("\nThats " + fTemp + " in Farenheit...");

    if(fTemp<20)
        System.out.println("\n***Burrrr. Its cold...***\n\n");
    else if(fTemp>20 || fTemp<50)
        System.out.println("\n***The weather is niether too hot nor too cold***\n\n");
    else if(fTemp>50)
        System.out.println("\n***Holy cow.. Its scorching.. Too hot***\n\n");
}


public static void main(String[] args) throws IOException {
    int temperature;
    char c;

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    do{
        System.out.println("Input:\n(Consider the input is from the sensor)\n");

        temperature = Integer.parseInt(br.readLine());

        examineTemperature(temperature);
        System.out.println("Does the sensor wanna continue giving input?:(y/n)\n");
        c = (char) br.read();
    }while(c!= 'N' && c!='n');          //if c==N that is no then stop



}

}

这是完整的代码专家。.我仍然能得到我的答案..我在网上进行了大量搜索,但无济于事。.也感谢那些已经提供帮助但那解决了我的问题的人..温度是整数。所以为什么我应该转换为字符串?
我也尝试尝试由成员之一指定的捕获,但然后inspectTemperature(temperature)抛出n错误,表示未初始化。
Input:
(Consider the input is from the sensor)

45

Temperature is 45 in celcius. Hmmm...

Thats 113 in Farenheit...

***The weather is niether too hot nor too cold***


Does the sensor wanna continue giving input?:(y/n)

N
Input:
(Consider the input is from the sensor)

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at tempdetection.main(tempdetection.java:33)

它也可以工作直到到达while循环。

最佳答案

行中的错误

temperature = Integer.parseInt(br.readLine());

这是在读取输入并尝试将其解析为整数。作为异常(exception)提示,输入不是数字,即NumberFormatException,因为Integer.parseInt()期望参数为数字。

有多种解决方法:

一种方法(我个人认为不是最好的方法)是捕获异常,什么也不做,然后继续
try
{
    temperature = Integer.parseInt(br.readLine());
    // and do any code that uses temperature
    //if you don't then temperature will not be assigned
}
catch (NumberFormatException nfex)
{}

更好的方法是在尝试解析之前检查输入字符串是否为数字
String input = br.readLine();
if(input.matches("\\d+"))  // Only ints so don't actually need to consider decimals
    //is a number... do relevant code
    temperature = Integer.parseInt(input);
else
    //not a number
    System.out.println("Not a number that was input");

关于java - Java : java.lang.NumberFormatException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19149784/

10-09 04:48