bigDecimal을 스캔하고 싶지만 스캔 된 입력이 bigdecimal이 아닌 경우 사용자 지정 예외를 throw하고 다시 스캔해야합니까?
아래 코드를 시도하고 있지만 결론에 도달 할 수 없습니다.
암호:
import java.util.*;
import java.io.*;
class WrongInputException extends Exception{
WrongInputException(String s){
super(s);
}
}
public class Main
{
public static void main(String[] args) throws WrongInputException
{
try
{
int number;
Scanner sc = new Scanner(System.in);
while (!sc.hasNextBigDecimal())
{
throw new WrongInputException("Wrong data type of input.....");
}
number = sc.nextInt();
System.out.println(number);
} catch(NumberFormatException e) {
System.out.println(e.getMessage());
}
}
}
문제는 던지는 예외를 처리하지 않는다는 것입니다.
sc.next();
끝없는 루프를 피하기 위해 try catch 블록을 추가하여 thw 내부에서 처리해야 합니다.
while (!sc.hasNextBigDecimal())
{
try {
throw new WrongInputException("Wrong data type of input.....");
}catch (WrongInputException e) {
e.printStackTrace();
}finally {
sc.next();
}
}
throw 할 예외가 있으므로 try catch에는 아무런 의미가 없습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다