我不知道我在做什么错,分配是创建一个代码,将温度从C转换为F或从F转换为C,直到用户决定完成为止,我也是应该在出现无效字符时打印错误消息,并让用户在不再次询问数字部分的情况下更正错误消息。Java temp转换程序。正确的输出,但错误
该程序似乎运行良好,直到我输入'c''C''f'或'F'以外的值。在这一点上,我仍然得到所需的输出,但比我得到一个错误,这里是我的代码。
import java.util.Scanner;
public class ProjectThree
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a temperature to be converted followed"
+ "\nby a C or c for Celsius or an F or f for Fahrenheit. If "
+ "\nfinished converting temperatures enter done.");
String userInput, intString;
userInput = keyboard.nextLine();
while (!(userInput.equalsIgnoreCase("done")))
{
int length, temp, degreesC, degreesF;
length = userInput.length();
intString = userInput.substring(0,length - 1);
temp = Integer.parseInt(intString);
char scale = userInput.charAt(length - 1);
while (!((scale == 'c') || (scale == 'C') || (scale =='f') ||
(scale == 'F')))
{
System.out.println("Error: Invalid temperature unit. Enter a C or c"
+ " for Celsius or an F or f for Fahrenheit.");
String errorInput = keyboard.next();
scale = errorInput.charAt(0);
userInput = intString + errorInput;
}
switch (scale)
{
case 'C':
case 'c':
degreesF = (9 * (temp/5) + 32);
System.out.println(userInput + " is equal to " + degreesF
+ "F");
break;
case 'F':
case 'f':
degreesC = (5 * (temp - 32))/9;
System.out.println(userInput + " is equal to " + degreesC
+ "C");
break;
}
System.out.println("\nPlease enter a temperature to be converted followed"
+ "\nby a C or c for Celsius or an F or f for Fahrenheit. If "
+ "\nfinished converting temperatures enter done.");
userInput = keyboard.nextLine();
}
}
}
,误差
Please enter a temperture to be converted followed
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
by a C or c for Celsius or an F or f for Farenheit. If
finished converting tempertures enter done.
at java.lang.String.substring(String.java:1955)
at ChapterFour.ProjectThree.main(ProjectThree.java:33)
Java Result: 1
BUILD SUCCESSFUL (total time: 5 seconds)
您应该将代码放在try catch语句中 –
哪个是生成此异常的输入? –
使用调试器,你会发现为什么你会得到这个异常 – Jens