[英]It is possible to use a Scanner in this manner?
我正在編寫一些東西,它創建了多個Teacher對象:
public class Teacher {
// 1) Define instance variables
String teacherName;
String catchPhrase;
public static int roomNum;
// 2) Write the constructor method
public Teacher() {
teacherName = "unknown";
catchPhrase = "unknown";
roomNum = 0;
}//end no-arg constructor
public Teacher(String newTeacher, String newCatch, int newRoom) {
teacherName = newTeacher;
catchPhrase = newCatch;
roomNum = newRoom;
}
// 3) Write the proccessing methods (getters and setters)
public void setName(String newName) {
teacherName = newName;
}
public String getName() {
return teacherName;
}
public static int getRoom() {
return roomNum;
}
// 4) Write the out method (eg toString() method)
public String toString() {
String str = "Name: " + teacherName + ". \nCatch phrase: " + catchPhrase + " \nRoom number: " + roomNum + ".";
return str;
}//end toString
public static void main(String args[]) {
}
}
它是這樣執行的:
Teacher teacherName("First Last", "Catch Phrase", 123);
我有多個教師對象。 我正在嘗試使掃描儀檢查用戶輸入,以查看輸入的數字是否是這些對象之一的房間號:
while (input != -1) {
Scanner scan = new Scanner(System.in);
input = scan.nextInt();
if(input == Teacher.getRoom()) {
System.out.println("Yes");
} else if(input != Teacher.getRoom()) {
System.out.println("Nope");
}
}
但是我不確定該怎么做。 或者,如果有可能。
任何幫助將不勝感激。
謝謝!
編輯:
我嘗試了另一種方式。 我試圖使用帶有房間號的數組,並將其與輸入進行比較,但是沒有用。
int[] rooms = {220, 226, 204, 234, 236, 242, 243, 129, 125, 136, 101, 104, 107, 113, 103, 105, 102, 108, 117, 111, 111, 313, 310, 132, 127, 129, 125,
+ 124, 122, 126, 130, 137, 114, 138, 136, 123, 135, 128, 139, 134, 220, 215, 211, 222, 253, 213, 252, 231, 255, 224, 254,
+ 218, 235, 233, 000, 212, 223, 257, 217, 259, 214, 240, 258, 221, 210, 219, 256, 216, 110, 133, 115, 423, 253, 230, 115, 106, 1062, 418, 415};
if (rooms.equals(input)) {
System.out.println("Yes");
} else {
System.out.println("Nope");
}
那沒用。 也沒有:
if (Arrays.asList(rooms).contains(input)) {
System.out.println("Yes");
} else {
System.out.println("Nope");
}
任何幫助使它與整數數組(或更好的方法)一起使用的方法,將不勝感激。
謝謝。
EDIT2:
我讓它像這樣工作:
if (rooms.contains(input)){
System.out.println("That teacher is in our database!");
//System.out.println(new int[(rooms).indexOf(1)]);
} else {
System.out.println("Sorry, that teachner was not found in our database!");
}
非常感謝你!
最簡單的方法是創建一個Teacher
數組,然后在while循環內,放置一個for循環,循環遍歷所有Teacher
對象並檢查房間號。 甚至更好的是,僅排列房間號的數組並循環遍歷。
另外,您可能想在while循環之外實例化掃描程序,然后執行while(scan.hasNextInt()){...
所以就像
Scanner scan = new Scanner(System.in);
Teacher[] teachears...
while (scan.hasNextInt()) {
input = scan.nextInt();
boolean isARoom = false;
for(Teacher teach : teachers){
if(input == teach.getRoom()) {
isARoom = true;
}
}
if(isARoom)
System,out.println("Yes");
else
System,out.println("No");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.