java 循环处理异常,使用Java中的do-while循环进行异常处理

The algorithm should take in 3 integers to an ArrayList. If the input is not an integer, then there should be a prompt. When I execute my code the catch clause is executed, but the program runs into a infinite loop. Could someone guide me into the right direction, I appreciate the help. :-D

package chapter_08;

import java.util.Scanner;

import java.util.List;

import java.util.ArrayList;

public class IntegerList {

static List numbers = new ArrayList();

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

int counter = 1;

int inputNum;

do {

System.out.print("Type " + counter + " integer: " );

try {

inputNum = input.nextInt();

numbers.add(inputNum);

counter += 1;

}

catch (Exception exc) {

System.out.println("invalid number");

}

} while (!(numbers.size() == 3));

}

}

解决方案

That is because when the next int is read using nextInt() and it fails, the Scanner still contains the typed contents. Then, when re-entering the do-while loop, input.nextInt() tries to parse it again with the same contents.

You need to 'flush' the Scanner contents with nextLine():

catch (Exception exc) {

input.nextLine();

System.out.println("invalid number");

}

Notes:

You can remove the counter variable, because you're not using it. Otherwise, you could replace counter += 1 by counter++.

You can replace while (!(numbers.size() == 3)) with while (numbers.size() != 3), or even better: while (numbers.size() < 3).

When catching exceptions, you should be as specific as possible, unless you have a very good reason to do otherwise. Exception should be replaced by InputMismatchException in your case.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值