本質的に私はPig Latinコンバータを作成しようとしています。ただし、この割り当てでは、単語の入力をやめるためにユーザーが 'Q'を入力できるようにする必要があります。私は、コードをコンパイルするために取得することができますが、ユーザーがQに入った時はいつでも、それがクラッシュし、スロー:ユーザ入力= qのときにループを終了しようとしています
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:658)
at mission4aa.Mission4AA.main(Mission4AA.java:38)
私はちょうどcompletleyわからないどこでもこれを固定して行くことになっています。私は努力してきました。ない新しいもの -
import java.util.Scanner;
public class Mission4AA {
public static void main(String[] args) {
Scanner scanIn = new Scanner(System.in);
String userInput;
int firstVowel = 0;
System.out.println("Welcome to the pig latin translator!");
System.out.println("Please enter a word (Q to exit): ");
do {
userInput = scanIn.next();
userInput = userInput.trim();
userInput = userInput.toLowerCase();
int end = userInput.length();
char a = userInput.charAt(0);
if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u')
System.out.println(userInput + "way");
else { //Check for next vowel if the first letter is consonant
for (int i = 1; i < userInput.length(); i++) {
char b = userInput.toLowerCase().charAt(i);
if (b == 'a' || b == 'e' || b == 'i' || b == 'o' || b == 'u') {
firstVowel = i; //Stores the index of the first vowel
break;
}
}
if(userInput.charAt(1) != firstVowel) {
String startString = userInput.substring(firstVowel, end);
String endString = userInput.substring(0, firstVowel) + "ay";
String result = startString + endString;
System.out.println("Translation: " + result);
}
}
System.out.println("Enter another word(Q to exit): ");
} while (!userInput.equalsIgnoreCase("q"));
System.out.println("Thank you");
}
}
これは、単に「Q」または「q」と入力すると、if(userInput.charAt(1)!= firstVowel){'が爆発するからです。インデックス '1'に' char'はありません。 –
なぜ入力を小文字に2回変換していますか?入力が単一の子音であれば、何が起こると思いますか? –