0
創建例如地址簿時,我也想要一個搜索方法。 想象我去爲這樣的對象:在java中使用用戶輸入搜索對象
public class someone {
private static someone [] addressBook = new someone[150];
private String firstName;
private String lastName;
private String address;
//...
public someone(String firstName, String lastNameame, String adress/*,...*/){
this.Vorname=firstName;
//...
}
現在我打算在檢索利用用戶輸入和掃描儀的人。首先,用戶要什麼他(她)在gerneral搜索聲明:
public static void searchSomeone(){
System.out.println("What do you want to search for?: ");
Scanner sc1 = new Scanner(System.in);
String userInput1 = sc1.next(); // e.g. userInput1="firstName"
其次,詢問用戶的確切值(S),他正在尋找:
System.out.println("Enter a " + userInput1 + ": ");
Scanner sc2 = new Scanner(System.in);
String userInput2 = sc2.next(); // e.g. userInput2="Peter"
for (int i=1;i<150;++i){
if(getAddressBook[i].**"Value of userInput1"**.contains(userInput2)){ // here is my problem!*
System.out.println("Congrats, we've found someone! ");
}
}
}
- 有沒有辦法將輸入的值用作成員變量的調用?
在這種情況下,參數應該「成爲」
if(getAddressBook[i].firstName.contains(userInput2)){}
我試圖執行像getInputValue另一種方法,簡單地返回字符串,但它並沒有在這裏工作。 如果沒有這樣的解決方案,我將不得不包含每個成員變量的代碼,這是我真正不想要的!
希望你明白我的意思!請善待我對論壇很陌生。 :P
1st你應該反正測試那個用戶輸入1是你班級的一個屬性/字段,實際上它是很好的打印可能的選項。測試的字段數量有限,因此可以使用「for」循環內的switch語句來區分應使用哪個字段。 – JosefN
我同意你的意見。我將列出可能的輸入以確保用戶點擊我的變量。感謝那! – Avigrail
問題依然存在。我明白你的解決方案,但這正是我不想做的。我只想處理1或2行中的所有輸入。 – Avigrail