Help reading a file to decode or encode
Hello I've ran into hopefully a small problem. A few weeks ago we were given an assignment to decode or encode a phrase given by a user. This week we have to change our code so it users a file and not user input. This is the original working code. **this is not entire code just the part I need help with**
Code Java:
public static void main(String[] args) {
alpha = new char[26];
loadData();
input = new Scanner(System.in);
while (true) {
displayMenu();
int choice = input.nextInt();
input.nextLine();
if (choice == 1) {
String phrase = getPhrase("Please enter a phrase to decode");
decodeMessage(phrase);
} else if (choice == 2) {
String phrase = getPhrase("Please enter a phrase to encode");
encodeMessage(phrase);
} else if (choice == 3) {
displayAlphabet();
} else if (choice == 4) {
System.out.println("Goodbye!");
break;
}
}
}
private static String getPhrase(String message) {
System.out.println(message);
String phrase = input.nextLine();
return phrase;
}
I have spent hours trying different senerios without success. I'm not sure where I am making my mystake. This is my latest version.
Code Java:
private static String getPhrase() {
Scanner file = new Scanner(new File("C:\\Users\\me\\file.txt"));
String[] phrase=new String[5];
int i=0;
while (file.hasNext())
{
phrase[i]=file.nextLine();
i++;
}
return phrase;
}
public static void main(String[] args) {
alpha = new char[26];
loadData();
input = new Scanner(System.in);
while (true) {
displayMenu();
int choice = input.nextInt();
input.nextLine();
if (choice == 1) {
decodeMessage(phrase);
} else if (choice == 2) {
encodeMessage(phrase);
} else if (choice == 3) {
displayAlphabet();
} else if (choice == 4) {
System.out.println("Goodbye!");
break;
}
}
}
My newest error is on my return phrase; in getPhrase. It says incompatible types- found java.lang.String[] but expected java.lang.String. I know this is because I'm mixing an array with a String... I just know how to fix it...:-/
Re: Help reading a file to decode or encode
Just as a thought, maybe you can invoke the Array toString() method?
like:
String str= Arrays.toString(phrase)
and then instead of returning phrase, just return str
Re: Help reading a file to decode or encode
Re: Help reading a file to decode or encode