I'm not sure what I'm doing wrong, the assignment is to create a code that converts a temperature from C to F or from F to C until the user decides they are finished, I'm also supposed to print an error message if an invalid character appears and have the user correct it without asking for the numeric portion again.
The program seems to run fine until I enter a value other than 'c' 'C' 'f' or 'F'. At which point I still get the desired output but than I get an error here is my code.
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();
}
}
}
and the error is
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)