In this code, I ask the user to input their name. For example, "John Smith". I would first reverse their name as "Smith John" That part works. Now, to make this "program" better, I added a couple of lines:
String newFirst2= ""; for (int i = newFirst.length()-1; i >=0; i--) { newFirst2 = newFirst2+newFirst.charAt(i); }
and
String newLast2= ""; for (int i = newLast.length()-1; i>=0; i--) { newLast2=newLast2+newLast.charAt(i); }
If everything works, the output should be htimS nhoJ, but I am getting an error. I can compile, but cannot run (Error after imputing name) Also, I know that I could have done the 2 flips in one method, but I wanted more practice with Methods.
import java.util.Scanner; public class Application { public static void main(String[] args) { Scanner scanner2 = new Scanner(System.in); System.out.print("Enter your name here: "); String a = scanner2.next(); Flip(a); } public static void Flip(String name) { int a = name.indexOf(' '); String newFirst = (name.substring (a+1, name.length())); String newFirst2= ""; for (int i = newFirst.length()-1; i >=0; i--) { newFirst2 = newFirst2+newFirst.charAt(i); } Flip2(newFirst, name, newFirst2); } public static void Flip2(String newFirst, String name, String newFirst2) { int a = name.indexOf(' '); String newLast = (name.substring (0, a)); String newLast2= ""; for (int i = newLast.length()-1; i>=0; i--) { newLast2=newLast2+newLast.charAt(i); } System.out.println ("Your name is: " + newFirst + " " + newLast); System.out.println ("Your second name is: " + newFirst2 + " " + newLast2); } }
Error:
Best Output (Intended Output):Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1911)
at Application.Flip2(Application.java:25)
at Application.Flip(Application.java:20)
at Application.main(Application.java:9)
Your name is Smith John
Your second name is htimS nhoJ
Thanks for the help!