Scanner為什么前面要加private static
package?com.imooc.proj_1; import?java.util.Scanner; public?class?BookManagerEasy?{ private?static?Scanner?console?=?new?Scanner(System.in); public?static?void?main(String[]?args)?{ //定義”圖書“數(shù)組 String[]?books?=?{?"C語言",?"數(shù)據(jù)結(jié)構(gòu)",?"匯編語言",?"高數(shù)",?"大學(xué)語文",?"毛概"?}; while?(true)?{ System.out.println("輸入命令:1-按照名稱查找圖書;2-按照序號查找圖書"); String?book; try?{ //取得整型命令 int?command?=?inputCommand(); //根據(jù)不同命令值,進(jìn)行不同操作 switch?(command)?{ case?1://按照圖書名稱選擇圖書 book?=?getBookByName(books); System.out.println("book:"?+?book); break; case?2://按照圖書序號(數(shù)組下標(biāo))選擇圖書 book?=?getBookByNumber(books); System.out.println("book:"?+?book); break; case?-1://返回值為-1,說明輸入有誤 System.out.println("命令輸入錯(cuò)誤!請根據(jù)提示輸入數(shù)字命令!"); continue; default://其他值的命令均認(rèn)為是錯(cuò)誤命令 System.out.println("命令輸入錯(cuò)誤!"); continue; } break;//退出程序 }?catch?(Exception?bne)?{ //捕獲”圖書不存在異常“時(shí),要求重新輸入命令 System.out.println(bne.getMessage()); continue; }? } } //按照圖書名稱查詢圖書 private?static?String?getBookByName(String[]?books) throws?Exception?{ System.out.println("輸入圖書名稱:"); //獲取輸入的圖書名稱 String?name?=?console.next(); for?(int?i?=?0;?i?<?books.length;?i++)?{ if?(name.equals(books[i])) //輸入的名稱與某一圖書名稱匹配,返回該圖書 return?books[i]; } //若無匹配,拋出”圖書不存在異?!? throw?new?Exception("圖書不存在!"); } //根據(jù)圖書序號(數(shù)組下標(biāo))查詢圖書 private?static?String?getBookByNumber(String[]?books) throws?Exception?{ while?(true)?{ System.out.println("輸入圖書序號:"); try?{ //獲取輸入的圖書序號(數(shù)組下標(biāo)) int?index?=?inputCommand(); //若返回值為-1 if(index?==?-1){ System.out.println("命令輸入錯(cuò)誤!請根據(jù)提示輸入數(shù)字命令!"); continue; } //若不出現(xiàn)”數(shù)組下標(biāo)越界異?!?,則返回相應(yīng)位置的圖書 String?book?=?books[index]; return?book; }?catch?(ArrayIndexOutOfBoundsException?e)?{ //輸入的序號不存在(引發(fā)”數(shù)組下標(biāo)越界異?!埃?,則拋出”圖書不存在異?!? Exception?bookNotExists?=?new?Exception("圖書不存在!"); bookNotExists.initCause(e); throw?bookNotExists; } } } //從控制臺輸入命令,用于輸入命令和輸入圖書序號 private?static?int?inputCommand(){ int?command; try?{ command?=?console.nextInt(); return?command; }?catch?(Exception?e)?{ //若輸入字符型或者字符串,則拋出異常,捕獲該異常,拋出”錯(cuò)誤命令異?!? console?=?new?Scanner(System.in); //返回-1 return?-1; } } }
在代碼中對Scanner進(jìn)行了private static的聲明,這個(gè)是什么原因呢,用public??static可以嗎?小白求教,謝謝
2016-08-03
private?static?int?inputCommand()方法中引用了private?static?Scanner?console?=?new?Scanner(System.in);中的console對象。inputCommand()方法是private?static修飾的故Scanner前面也要加!
2019-07-16
inputCommand()方法用static修飾 即此方法為靜態(tài)方法 而Java中靜態(tài)方法中不能調(diào)用非靜態(tài)變量或方法 所以要使用Scanner的引用對象時(shí) 應(yīng)將其申明為靜態(tài) 而private確定此變量在此類可見 而不能用于其他類 而public不僅僅在此類中可見 在其他地方也可見 在此處用public也可以
2016-11-30
請問為什么inputCommand()方法中,在捕獲異常時(shí),要再寫一個(gè)console = new Scanner(System.in);
我發(fā)現(xiàn)如果不寫的話將會陷入死循環(huán),但是想不通為什么不寫,請賜教。
2016-08-03
可以,public是一個(gè)全局的,他可以在其它類里面去調(diào)用你這個(gè)類里定義的東西,private是一個(gè)表示私有的表示符,只允許你在這個(gè)類里面去調(diào)用
2016-08-03
應(yīng)該是可以的? 對內(nèi)都是可見的? 所以用public 和private區(qū)別不大