如代碼所示,for循環(huán)那步怎么修改?
package test3;
import java.util.*;
public class Mooc4 {
Scanner sc=new Scanner(System.in);
String[] bookName={"高數(shù)","數(shù)據(jù)結(jié)構(gòu)","haha"};
int l=bookName.length;
//通過(guò)實(shí)例化來(lái)實(shí)現(xiàn)test2()
public static void main(String[] args) {
Mooc4 m=new Mooc4();
m.test2();
}
//定義一個(gè)test1方法用來(lái)輸入管理系統(tǒng)
public void test1(){
//通過(guò)while來(lái)實(shí)現(xiàn)無(wú)限循環(huán)
while(true){
System.out.println("輸入命令:1-按照名稱(chēng)查找圖書(shū);2-按照序號(hào)查找圖書(shū)");
//定義bookNum來(lái)選擇不同的方式查找圖書(shū)
int bookNum=sc.nextInt();
//按照名稱(chēng)查找圖書(shū)
if(bookNum==1){
System.out.println("輸入圖書(shū)名稱(chēng):");
String n1=sc.next();
//通過(guò)for循環(huán)來(lái)控制數(shù)組的輸出
/*
* 這一步因?yàn)橐闅v數(shù)組,所以每次都要打印"圖書(shū)不存在",應(yīng)該怎么修改
*/
for(int i=0;i<l;i++){
String book=bookName[i];
//比較輸入字符串和圖書(shū)名字
if(n1.equals(book)){
book=bookName[i];
System.out.println("book:"+book);
}else{
System.out.println("圖書(shū)不存在!");
}
}
??
}
//按照序列查找圖書(shū)
if(bookNum==2){
System.out.println("輸入圖書(shū)序號(hào):");
int n2=sc.nextInt();
if(n2>=l){
System.out.println("圖書(shū)不存在!");
}else{
System.out.println("book:"+bookName[n2]);
break;
}
}
}
}
//通過(guò)test2()調(diào)用test1()來(lái)獲取異常
public void test2(){
try{
test1();
}catch(InputMismatchException e){
System.out.println("命令輸入有誤!請(qǐng)根據(jù)提示輸入數(shù)字命令!");
}catch(Exception e){
e.printStackTrace();
}
}
}
2018-05-06
for(i=0;i<l;i++){
String book=bookName[i];
//比較輸入字符串和圖書(shū)名字
if(n1.equals(book)){
book=bookName[i];
System.out.println("book:"+book);break;
}}
if(!n1.equals(bookName[i])){
System.out.println("圖書(shū)不存在!");
}
}?
2018-02-26
加一個(gè)標(biāo)志變量boolean flag=flase,遍歷時(shí)候,如果存在所選圖書(shū),置為true.根據(jù)最終的flag 判斷輸出