JUST_4_IT
2016-12-15 16:14:32浏览 2462
import java.util.*;
class Index {
static int flag = 0;
//定义一个字符串数组存放书籍
String[] books = new String[]
{"java编程思想","高等数学","Java疯狂讲义",
"从你的全世界路过","幻城","大学英语","努力","加油","做自己"};
//浏览方式选择方法
public void showEnter() {
System.out.println("请选择浏览图书的方式:");
System.out.println("1:按照名称查找"+"\t"+"2:按照序号查找");
Scanner sc = new Scanner(System.in);
int choose = sc.nextInt();
if (choose==1) {
flag = 1;
System.out.println("请输入名称");
dispByName();
}else if (choose==2) {
flag = 1;
System.out.println("请输入序号");
dispByNum();
}else {
System.out.println("输入无效,请按照要求输入!");
showEnter();
}
}
//主方法
public static void main(String[] args)
{
Index ix = new Index();
while(flag==0) {
ix.chooseStyle();
}
}
//判断选择方式的方法
public void chooseStyle() {
try {
showEnter();
}
catch (InputMismatchException e) {
System.out.println("输入无效,请重新选择浏览方式:");
chooseStyle();
}
}
//定义一个按照序号显示图书的方法
public void dispByNum() {
Scanner sc = new Scanner(System.in);
try{
int index = sc.nextInt();
if (index<=0||index>books.length) {
throw new Exception();
}
System.out.println(books[index-1]);
}catch(Exception e) {
System.out.println("请输入合适的序号1-"+books.length);
dispByNum();
}
}
//定义一个按照名称显示图书的方法
public void dispByName() {
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
int flag = 0;
int j = 0;
try {
for (int i=0;i<books.length ;i++ ) {
if (books[i].equals(name)) {
j = i;
System.out.println("你好,你查找的图书是第"+(j+1)+"个");
flag=1;
}
}
if (flag==0) {
throw new Exception();
}
}catch (Exception e) {
System.out.println("输入的名字有误,重新输入:");
dispByName();
}
}
}