I am writing a program that reverses 2 4 digit numbers, and I wrote a method that will do it. There are no errors in the project build, but I get "String index out of range: -3" when I try to run it. I am fairly new to programming and I have no idea what I did wrong.
Here's the code:
public static void main(String[] args)
{
int num1 = 1;
int num2 = 1;
Scanner console = new Scanner(System.in);
while (num1 <1000 || num1 > 9999)
{
System.out.println("Please enter a positive 4 digit number");
num1 = console.nextInt();
}
String numString1 = Integer.toString(num1);
while (num2 <1000 || num2 > 9999)
{
System.out.println("Please enter another positive 4 digit number");
num2 = console.nextInt();
}
String numString2 = Integer.toString(num2);
int numReverse1 = stringReverse(numString1);
int numReverse2 = stringReverse(numString2);
System.out.println(numReverse1 + numReverse2);
System.out.println("The product of your 2 reversed numbers is: " + (numReverse1 * numReverse2));
}
public static int stringReverse (String numString)
{
String c1c2c3 = numString.substring(4);
String c2c3c4 = numString.substring(1);
String c1c2 = c1c2c3.substring(3);
String c3c4 = c2c3c4.substring(1);
String c1 = c1c2.substring(2);
String c2 = c1c2.substring(1);
String c3 = c3c4.substring(2);
String c4 = c3c4.substring(1);
String numStringReverse = c4 + c3 + c2 + c1;
int reversedString = Integer.parseInt(numStringReverse);
return reversedString;
}
}