그래서 예외 처리를 위해 try-catch
블록을 통합해야하는 프로그램으로 작업하고 있습니다. 내가 이해할 수없는 것은 Scanner
을 통해 사용자가 입력 한 내용을 검사하기 위해 간단한 if statement
을 작성하는 방법이며, 프로그램이이를 잡으면 오류를 표시 할 수 있도록 문자 또는 문자가 아닌 이중이어야합니다. 적절한 입력이 입력 될 때까지 다른 값을 다시 입력하라고 사용자에게 알립니다. 내가 찾고있는 간단한 (_width 문자/문자 같음) 다음 입력 오류가 0보다 큰지 여부를 확인하는 내 현재있는 if 문 함께 갈 오류 메시지와 함께 false를 반환합니다.Java 입력 유효성 검사
내 현재 코드는 다음과 같습니다 :
public class Rectangle {
//two double data fields width and height, default values are 1 for both.
private double width = 1;
private double height = 1;
private String errorMessage = "";
//no-arg constructor creates default rectangle
public Rectangle() {
}
//fpzc, called by another program with a statement like Rectangle rec = new Rectangle(#, #);
public Rectangle (double _width, double _height) throws Exception {
setWidth(_width);
setHeight(_height);
}
//get functions
public double getArea(){
return (width * height);
}
public double getPerimeter() {
return (2*(width + height));
}
public String getErrorMessage() {
return errorMessage;
}
//set functions
public void setWidth(double _width) throws Exception {
if(!isValidWidth(_width)){
Exception e = new Exception(errorMessage);
throw e;
//System.out.println(errorMessage);
//return false;
}
width = _width;
}
public void setHeight(double _height) throws Exception {
if (!isValidHeight(_height)){
Exception e = new Exception(errorMessage);
throw e;
//System.out.println(errorMessage);
//return false;
}
height = _height;
}
//isValid methods
public boolean isValidWidth(double _width) {
if(_width > 0){
return true;
}
else {
errorMessage = "Invalid value for width, must be greater than zero";
return false;
}
if()
}
public boolean isValidHeight(double _height) {
if(_height > 0){
return true;
}
else {
errorMessage = "Invalid value for height, must be greater than zero";
return false;
}
}
}
내 클래스는 내가 제대로 쓴 다른 테스트 프로그램에 의해 호출되고있다. 어떤 도움을 주셔서 감사합니다! 고맙습니다.
[문자열에 포함 된 값이 double인지 알아내는 방법] (http://stackoverflow.com/questions/3133770/how-to-find-out-if-the-value - 포함 - 문자열 - 더블 또는 아닙니다). –
오류 메시지를 팝업 창이나 콘솔에 표시 하시겠습니까? –
콘솔 만 있습니다. –