困擾了一晚上的Scanner,還是不知道在哪里close?
package com.imooc;
import java.util.Scanner;
public class LibraryTest {
private static String[] books = new String[] {"語文", "數學", "英文", "政治", "歷史", "物理", "化學"};
public static void main(String[] args) {
LibraryTest lt = new LibraryTest();
while(lt.searchBook() != 0)? // 進入查找圖書系統
System.out.println("圖書不存在!");
}
public int searchBook() {
int ret = -1;
System.out.println("輸入命令:1-按照名稱查找圖書;2-按照序號查找圖書");
try {
Scanner input = new Scanner(System.in);
int cmd = input.nextInt();
switch (cmd) {
case 1:
ret = searchBookByName();
break;
case 2:
ret = searchBookByIndex();
break;
default:
System.out.println("命令輸入錯誤!請根據提示輸入數據命令");
break;
}
} catch(Exception e) {
System.out.println("命令輸入錯誤!請根據提示輸入數據命令");
}
return ret;
}
private int searchBookByName() {
System.out.println("輸入圖書名稱:");
Scanner input = new Scanner(System.in);
String name = input.nextLine();
for (String book : books) {
if (book.equals(name)) {
System.out.println("book: " + name);
return 0;
}
}
return -1;
}
private int searchBookByIndex() {
System.out.println("輸入圖書序號:");
Scanner input = new Scanner(System.in);
int index = input.nextInt();
if (index >= 0 && index < books.length) {
System.out.println("book: " + books[index]);
return 0;
}
return -1;
}
}
2020-10-08
你每次成功執行返回的是0,然后你循環的條件是!=0,所以會退出。
樓上整理i了
2020-07-23
我看著頭大 幫忙整理一下 希望能夠幫助解答者