我不知道我在做什麼錯,分配是創建一個代碼,將溫度從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