我有一個程式,其中有一個名稱串列,輸出說明名稱出現了多少次以及單詞出現在哪一行。現在,如果我有一個出現兩次的名字,它只輸出第一個出現的單詞的行號。我怎樣才能做到,如果它出現不止一次,它會說出名字在哪一行?
class Main {
public static void main(String[] args) {
String nameList="Joe\nBob\nSteve\nJasper\nZack\nInayah\nKevin\nSheila\nSophie\nAdi\nJasper";
String[] spl = nameList.split("\n");
System.out.println(nameList);
int position = java.util.Arrays.asList(spl).indexOf("Jasper") 1;
String amount = "Jasper";
int count = 0;
for(String word : spl) {
if(word.equals(amount)) {
count ;
}
}
System.out.println("The name " amount " Appears " count " Times");
System.out.print("The name appears on line " position );
if (count>1) {
System.out.print(" and line" /*the second line it appears on*/);
}
}
}
uj5u.com熱心網友回復:
這是一個簡單的解決方案,適用于每行一個名稱的給定輸入。
public class Main {
public static void main(String[] args) {
String nameList="Joe\nBob\nSteve\nJasper\nZack\nInayah\nKevin\nSheila\nSophie\nAdi\nJasper";
String[] spl = nameList.split("\n");
int lineArr[];
lineArr = new int[11];
int line = 0;
System.out.println(nameList);
int position = java.util.Arrays.asList(spl).indexOf("Jasper") 1;
String amount = "Jasper";
int count = 0;
for(String word : spl) {
line ;
if(word.equals(amount)) {
lineArr[count] = line;
count ;
}
}
System.out.println("The name " amount " Appears " count " Times");
System.out.print("The name appears on line " position );
while (count>1) {
count--;
System.out.print(" and line " lineArr[count]);
}
}
}
宣告該陣列lineArr以跟蹤關鍵字的存在Jasper。陣列需要具有最多行數的元素,以跟蹤關鍵字是否出現在所有行上。您可以通過添加未硬編碼的邏輯并檢測用于宣告陣列長度的行數來進一步改行程式。
在您的for(String word : sp1)回圈中,我們所要做的就是跟蹤我們所在的行,并在lineArr找到關鍵字時將其存盤在陣列中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/418889.html
標籤:
