저는 사용자가 발과 인치 측정을 위해 두 개의 별도 double을 입력 할 수있는 간단한 프로그램을 작성하고 있습니다. 이 프로그램은이 값을 취하여 센티미터로 변환하여 출력합니다. 또한 두 가지 예외를 포함해야합니다. 하나는 숫자 값이 음수가 아닌지 확인하고 (이 중 하나는 완료했습니다) 다른 하나는 입력 된 값이 이중 값이고 문자열 값이 아닌지 확인하는 것입니다. 힘든 시간). 따라서 사용자가 숫자 대신에 'Bill'과 같은 입력을 입력하면 오류 메시지를 표시하고 입력 값을 다시 입력하도록 사용자에게 요청하는 것입니다.Java : 사용자 입력이 Double인지 확인하기 위해 Try/Catch Exception 사용
아마도 나는 사용자 입력을 문자열로 수집하는 것이 가장 좋을 것 같습니다 (현재 내가 두 배가되기보다는). 나는 두 배로 변환하여 해당 메소드에 대해 두 배로 반환합니다. getFootValue() 및 getInchValue() -하지만 나는 너무 확신하지 못합니다.
맞춤 예외로 어떻게 구현해야합니까? 나는 단순히 InputMismatchException을 활용할 수 없다. 나는 내 자신의 NonDigitNumberException()이라는 제목을 만들어야한다. 여기
... 나는 지금까지 무엇을
import java.util.Scanner;
public class Converter
{
private double feet;
private double inches;
public Converter(double feet, double inches)
{
this.feet = feet;
this.inches = inches;
}
public double getFootValue()
{
return feet;
}
public double getInchValue()
{
return inches;
}
public double convertToCentimeters()
{
double inchTotal;
inchTotal = (getFootValue() * 12) + getInchValue();
return inchTotal * 2.54;
}
public String toString()
{
return ("Your result is: " + convertToCentimeters());
}
}
import java.util.Scanner;
import java.util.InputMismatchException;
public class TestConverter
{
public static void main(String[] args)
{
/* Create new scanner for user input */
Scanner keyboard = new Scanner(System.in);
do
{
try
{
/* Get the feet value */
System.out.print("Enter the foot value: ");
double feet = keyboard.nextDouble();
if (feet < 0) throw new NegativeNumberException();
/* Get the inches value */
System.out.print("Enter the inch value: ");
double inches = keyboard.nextDouble();
if (inches < 0) throw new NegativeNumberException();
else
{
Converter conversion = new Converter(feet, inches);
/* Print the converted result */
System.out.println(conversion);
break;
}
} catch(InputMismatchException ignore){}
catch(NegativeNumberException error)
{
System.out.println("A negative-numeric value was entered, please enter only positive-numeric values...");
}
}while(true);
/* Close the keyboard */
keyboard.close();
}
}
class NegativeNumberException extends Exception
{
public NegativeNumberException()
{
super();
}
public NegativeNumberException(String errorMessage)
{
super(errorMessage);
}
}
어떤 도움 주셔서 감사합니다!
왜 당신은 모든 예외를 던지고있다? 대신 오류 메시지를 인쇄하고 대신 '계속'을 수행 할 수 있습니다. – azurefrog
Scanner.hasNextDouble()을 사용하여 다음 토큰을 이중으로 스캔 할 수 있는지 여부를 테스트 해 보셨습니까? –
아니면 단순히 입력을 double로 스캔 할 수없는 경우에 발생하는'InputMismatchException'을 처리하기 만하면됩니다. 예외를 포착하고 그것을 무시하는 것은 거의 결코 옳은 일이 아닙니다. –