Program overview: Ask user for phrase, ask user for an index in which a scramble will rotate the phrase until that letter at index is the first index (0) of the string. Ask for an Integer until an integer is given. After phrase is scrambled ask to scramble again. if yes, scramble to inputted index, if no, print final result end program.
import java.util.Scanner;
public class PJ {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String phrase;
String phraseMut;
int index;
System.out.println("Enter your word or phrase: ");
phrase = scan.nextLine();
phraseMut = phrase;
System.out.println();
while (true) {
System.out.println("Enter the index of a character in your phrase: ");
if (scan.hasNextInt()) {
index = scan.nextInt();
scan.nextLine();
break;
} else if (index >= phraseMut.length()) {
System.out.println("Error: Index is Double not Integer.");
} else {
System.out.println("Error: Index is not Integer.");
}
}
System.out.println();
System.out.println("Rotating phrase to bring index " + index + " to the front. . .");
int count = 0;
for (int i = 0; i < index; i++) {
phraseMut = phraseMut.substring(1, phrase.length()) + "" + phraseMut.substring(0, 1);
count++;
System.out.println(phraseMut);
}
}
}
First for loop, I cannot access "index" as the compiler is stating it may not have been initialized. Any solution to access this?
while-loop,indexmust be set in order to exit the loop. Therefore, we have to initializeindex. Easiest way is to initialize it at declaration:int index = 0;indexis declared earlier in the method:int index;.