我正在嘗試在以字母“a”結尾的陣列中查找單詞。我想用兩個 for 回圈來做,但我不斷得到整數越界錯誤。
誰能告訴我我做錯了什么?
代碼:
Scanner sc = new Scanner(System.in);
System.out.println("Enter text: ");
String text = sc.nextLine();
String[] words = text.split(" ");
for (int i = 0; i < words.length; i ) {
words[i] = words[i] " ";
}
for (int i = 0; i < words.length ; i ) {
for (int j = 0; j <= words[i].charAt(j); j ) {
if (words[i].charAt(j) == 'a' && words[i].charAt(j 1) == ' ') {
System.out.println(words[i]);
}
}
}
uj5u.com熱心網友回復:
你有太多的代碼來完成這個任務,這導致了一個錯誤。如果您使代碼盡可能簡單,那么您將獲得更少的錯誤。
洗掉這個,你不需要。
for (int i = 0; i < words.length; i ) {
words[i] = words[i] " ";
}
并洗掉所有這些:
for (int j = 0; j <= words[i].charAt(j); j ) {
if( words[i].charAt(j) == 'a' && words[i].charAt(j 1) == ' '){
System.out.println(words[i]);
}
}
而是將您的代碼基于endsWith("a"):
for (String word : words) {
if (word.endsWith("a")) {
System.out.println(word);
}
}
它易于閱讀和理解(因此更容易避免錯誤)。
更簡單,因為您實際上不需要參考陣列:
String text = sc.nextLine();
for (String word : text.split(" ")) {
if (word.endsWith("a")) {
System.out.println(word);
}
}
uj5u.com熱心網友回復:
在第二個 for 回圈中,您正在檢查當前位置的字符,而不是單詞的長度。將條件更改為words[i].length()以修復它。
uj5u.com熱心網友回復:
為了檢查某些單詞是否以 character 結尾a,我們可以執行以下操作:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Read the input
System.out.println("Enter text: ");
String text = sc.nextLine();
// Split the input by spaces
String[] words = text.split(" ");
// Iterate through the array of words and check if any of those ends with "a"
for (String word : words) {
if (word.endsWith("a")) {
System.out.println(word);
}
}
}
就這么簡單,我們真的不需要嵌入式回圈。
uj5u.com熱心網友回復:
試試這個
String[] words = {"apple", "ada", "cat", "material", "recursion", "stacksa"};
for (int i = 0; i < words.length; i ) {
// get each word first
String word = words[I];
int lenOfWord = word.length();
// check the last item in the word
if (word.charAt(lenOfWord - 1) == 'a') {
System.out.println("Last char is a" word);
}
}
uj5u.com熱心網友回復:
其他答案通過回圈解釋邏輯。做同樣的事情的另一種方法是通過 Java 流:
Scanner sc = new Scanner(System.in);
System.out.println("Enter text: ");
String text = sc.nextLine();
String[] words = text.split(" ");
Arrays.stream(words).filter(w -> w.endsWith("a")).forEach(System.out::println);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/407621.html
標籤:
上一篇:Python合并重疊路徑
下一篇:如果按順序重復多次,則洗掉子字串
