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;
}
}
你每次成功执行返回的是0,然后你循环的条件是!=0,所以会退出。
楼上整理i了
我看着头大 帮忙整理一下 希望能够帮助解答者
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; } }