請問下我下面的代碼為什么會陷入死循環(huán)
?while(true){
? ? ? ? ?try{
? ? ? ? id1=input.nextInt();
? ? ? ? }catch(Exception e){
? ? ? ? System.out.println("請輸入整數(shù)型數(shù)字");
? ? ? ? continue;
? ? ? ? }
? ? ? ? ?break;
? ? ? ? ?}
?while(true){
? ? ? ? ?try{
? ? ? ? id1=input.nextInt();
? ? ? ? }catch(Exception e){
? ? ? ? System.out.println("請輸入整數(shù)型數(shù)字");
? ? ? ? continue;
? ? ? ? }
? ? ? ? ?break;
? ? ? ? ?}
2017-03-01
舉報
2017-03-18
這幾天沒看java啦,說實話,我對java也只是一個愛好者
給你看一個之前寫的
/**
* 判斷輸入玩家編號異常值
* @return
* @throws Exception
*/
public int scanInt() throws Exception
{
? ?try {
? ? ? ?int in = console.nextInt();
? ? ? ?return in;
? ?} catch (Exception e) {
? ? ? ?console = new Scanner(System.in,"UTF-8");
? ? ? ?throw new Exception("輸入異常,請輸入整數(shù)類型的ID");
? ?}
}
2017-05-04
樓上說的對,你只要改一行就好了
id1=Integer.parseInt(input.nextLine());
2017-04-18
你定義了一個Scanner對象 input吧 如果你已經(jīng)賦值給他并且非int變量
? 循環(huán)再運行input.nextInt()方法就不再接收鍵盤輸入 ? ?而是直接返回上一次有異常的值,然后繼續(xù)異常 ? 會無限循環(huán)catch塊的代碼的 ?
簡單說解決方案 可以try內(nèi)部再新new一個Scanner對象
或者使用樓上的throw?
2017-04-04
http://idcbgp.cn/qadetail/199049
2017-03-02
continue是用來繼續(xù)循環(huán)啊,break是跳出循環(huán),如果用return的話后面程序就都不用執(zhí)行了。
2017-03-01
這個問題你斷點調(diào)試一下就會發(fā)現(xiàn),當(dāng)輸入不是整形,觸發(fā)異常的時候,continue一直都在循環(huán)中,
改成throw new Exception("輸入異常,請輸入整數(shù)類型數(shù)字");就好啦