我正在尝试用 Java 编写一个程序,该程序将接受用户的输入并转换为摄氏度或华氏度。所以用户将输入一些数字,一个空格,然后是一个 C 或 F。你的程序编译得很好,但是当我尝试测试它时,我收到以下消息:
Exception in thread "main" java.lang.NumberFormatException: For input string: (whatever number, space, F/C I put in to test it0
at java.lang.Integer.parseInt<Integer.java:492>
at java.lang.Integer.parseInt<Integer.java:527>
at Temp.Conv.main<TempConv.java:14>
我猜 Java 不喜欢我尝试使用 Parse 在字符串中搜索整数。关于如何完成它的任何建议?
这里是代码:(你知道,我知道括号和空格是关闭的,但这个网站不允许我修复它)
public class TempConv
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String reply = "y";
while( reply.equalsIgnoreCase("y") )
{
System.out.println("Enter temp (ex. 70 F or 23 C): ");
String CF = input.nextLine(); // inputs string
int temp = Integer.parseInt(CF); // to get integers from string
for (int i = 0; i < CF.length(); ++i)
{
char aChar = CF.charAt(i);
if (aChar == 'F') // looking in string for F
// go to f2c()
{
f2c(temp);
}
else if (aChar == 'C') // looking for C
// go to c2f()
{
c2f(temp);
}
}
System.out.println("Would you like to covert another temp? <y/n> ");
reply = input.next();
}
}
static void f2c(int j)
{
int c = (j - 32)*(5/9);
System.out.println(j + "F = " + c + "C");
}
static void c2f(int k)
{
int f = (k*(5/9))+32;
System.out.println(k + "C = " + f + "F");
}
}