[英]Java Input Validation
所以我正在使用一個程序,該程序應該包含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;
}
}
}
我正確編寫的另一個測試程序正在調用我的班級。 任何幫助表示贊賞! 謝謝。
也許像這樣:
String errorMessage = "error";
Scanner in = new Scanner(System.in);
String str = in.nextLine();
try {
Double.parseDouble(str);
}
catch( Exception e ){
System.out.println(errorMessage);
}
或遍歷輸入並檢查每個字符是否為數字:
String errorMessage = "error";
Scanner in = new Scanner(System.in);
String str = in.nextLine();
for(int i=0;i<str.length();i++){
char token = str.charAt(i);
if(!Character.isDigit(token) && token!='.' ) {
System.out.println(token + " doesnt work");
break;
}
}
在聲明掃描儀時,您還可以:
double num;
String errorMessage = "error";
while(true) {
Scanner in = new Scanner(System.in);
if (in.hasNextDouble()) {
num = in.nextDouble();
System.out.println(num);
break;
}
else System.out.println(errorMessage);
}
也許這段代碼可以幫助您:
double Input=0;
while(!(Input > 0)){{
System.out.println("Enter Valid Number");
Input = new Scanner(System.in).nextDouble();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.