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