【发布时间】:2016-07-09 07:18:05
【问题描述】:
所以我正在使用一个应该包含try-catch 块以进行异常处理的程序。我想不通的是如何编写一个简单的if statement 来检查用户通过Scanner 输入的内容,以确保它是双精度而不是字母或字符,这样如果是程序就会捕获它,显示错误消息,并告诉用户重新输入另一个值,直到输入合适的输入。我正在寻找的是一个简单的 if(_width 等于一个字母/字符) 然后返回 false 以及一条错误消息,以与我已经存在的 if 语句一起检查输入是否大于零。
我当前的代码如下:
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;
}
}
}
我的课程被另一个我正确编写的测试程序调用。任何帮助表示赞赏!谢谢。
【问题讨论】:
-
您希望错误消息显示为弹出窗口还是仅显示在控制台中?
-
只有控制台,谢谢
标签: java