如何验证一个接受整数或带有.5的双精度值(Java)

huangapple go评论94阅读模式
英文:

How to validate a double value which accepts either integers or values with .5 (Java)

问题

我正在为一个房屋类定义属性,并且需要在构造方法内对它们进行验证,以下是属性以及我需要进行的验证说明。

numberBathrooms – 一个双精度值,用于标识此房屋中浴室的数量。该值必须是大于零的数字,可带有0.5的可选小数部分。例如,1.5和0.5是有效值,而2.7和0.4则无效。

以下是继承自另一个建筑类的我的类的代码。

public class House extends Building {
    
    double numberBathrooms;
    int numberBedrooms;

    public void House(String name, String number, int buildYear, double bathrooms, int bedrooms) {
        if (name == null || number == null) {
            System.out.println("街道值不能为空");
        } 
        else if (buildYear < 1975 || buildYear > 2019) {
            System.out.println("年份不在有效范围内");
        }
        else if (bathrooms <= 0 || bathrooms % 1 != 0 && bathrooms % 1 != 0.5) {

        }
        else {
            streetName = name;
            streetNumber = number;
            yearBuilt = buildYear;
            numberBathrooms = bathrooms;
            numberBedrooms = bedrooms;
        }
    }
}

我可以使用类似其他参数中使用的逻辑(或者有没有更有效的方法呢)?

英文:

I'm defining attributes for a house class and need to validate them inside the constructor method, below is the attribute and the explanation of the validation I have to do.

numberBathrooms – a double value that identifies the number of bathrooms in this house. This value must a number greater than zero with an optional fraction value of 0.5. For example, 1.5 and 0.5 are valid values while 2.7 and 0.4 are not valid.

Below is my code for my class which is inheriting from my other building class.

public class house extends building {

double numberBathrooms;
int numberBedrooms;

public void house(String name, String number, int buildYear, double bathrooms, int bedrooms){
    if (name == null || number == null) {
        System.out.println(&quot;Street values cannot be empty&quot;);
    } 
    else if (buildYear &lt; 1975 || buildYear &gt; 2019) {
        System.out.println(&quot;Year is not in a valid range&quot;);
    }
    else if(bathrooms &lt;= 0 || bathrooms //Something here?){

    }
    else {
        streetName = name;
        streetNumber = number;
        yearBuilt = buildYear;
        bathrooms = numberBathrooms;
        bedrooms = numberBedrooms;
    }
}

Is there any logic I can use (as used in my other parameters)? or is there a more effective way maybe.

答案1

得分: 2

public class House extends Building {

    private double numberBathrooms;
    private int numberBedrooms;

    public void House(String name, String number, int buildYear, double bathrooms, int bedrooms){
        super(name, number, buildYear);
        if (name == null || number == null) {
            System.out.println("Street values cannot be empty");
        } 
        else if (buildYear < 1975 || buildYear > 2019) {
            System.out.println("Year is not in a valid range");
        }
        else if(bathrooms <= 0 || bathrooms % 0.5 != 0){
            System.out.println("Bathrooms is not in a valid range");
        }
        else {
            this.numberBathrooms = bathrooms;
            this.numberBedrooms = bedrooms;
        }
    }
}
英文:
public class House extends Building {

private double numberBathrooms;
private int numberBedrooms;

public void House(String name, String number, int buildYear, double bathrooms, int bedrooms){
    super(name, number, buildYear);
    if (name == null || number == null) {
        System.out.println(&quot;Street values cannot be empty&quot;);
    } 
    else if (buildYear &lt; 1975 || buildYear &gt; 2019) {
        System.out.println(&quot;Year is not in a valid range&quot;);
    }
    else if(bathrooms &lt;= 0 || bathrooms % 0.5 != 0){
        System.out.println(&quot;Bathrooms is not in a valid range&quot;);
    }
    else {
        this.numberBathrooms = bathrooms;
        this.numberBedrooms = bedrooms;
    }
}

Some suggestions:

  • Use capital letters as the first letter for Class names, no error will be thrown but still, it is the convention.

  • Use super() to instantiate the members of parent class.

  • Make data members private and write getters and setters for them.

答案2

得分: 1

    ...
    else if (bathrooms <= 0 || bathrooms % 0.5 != 0){

    }
    ...

这将对你的数字进行半数模运算,以查看是否有余数。

你可以在这里检查我的工作,并使用 jshell 进行快速原型设计。例如:

my prompt> jshell
| 欢迎使用 JShell -- 版本 11
| 要获取介绍,请键入:/help intro

jshell> 1.7 % .5
$1 ==> 0.19999999999999996

jshell> 1.5 % 0.5
$2 ==> 0.0

jshell> 1 % 0.5
$3 ==> 0.0

注意:这仅适用于浮点数能够准确表示 x = m/(2^n) 的情况,其中 x 是小数,m 和 n 是整数。

英文:

You could use:

    ...
    else if(bathrooms &lt;= 0 || bathrooms % 0.5 != 0){

    }
    ...

This will take your number modulo a half to see if there is any remainder.

You can check my work here and rapidly prototype using jshell. For example:

my prompt&gt;  jshell 
|  Welcome to JShell -- Version 11
|  For an introduction type: /help intro

jshell&gt; 1.7 % .5
$1 ==&gt; 0.19999999999999996

jshell&gt; 1.5%0.5
$2 ==&gt; 0.0

jshell&gt; 1%0.5
$3 ==&gt; 0.0

Note: this only works because floating point numbers will faithfully represent small numbers where x = m/(2^n)

答案3

得分: 1

使用 % 在这种情况下可以正常工作,但在更一般的情况下可能不起作用,例如 1 % 0.1 = 0.09999999999999995。在这里它碰巧可以正常工作,因为 0.5 可以精确表示。

一个更好的做法是将其表示为一个 long 型。

if ((long) (bathroom * 2) / 2 != bathroom)

或者如果你更喜欢更清晰的表达方式:

if (Math.round(bathroom * 2) / 2 != bathroom)
英文:

Using % will work in this case, it doesn't work for a more general case e.g. 1 % 0.1 = 0.09999999999999995 It happens to work here as 0.5 can be represented precisely.

A better pattern is to represent it as a long.

if ((long) (bathroom * 2) / 2 != bathroom)

or if you prefer for clarity

if (Math.round(bathroom * 2) / 2 != bathroom)

答案4

得分: 0

你可以使用模式匹配

Pattern numpat = Pattern.compile("\\d\\.((?<!0\\.)0|5)");
Matcher m = numpat.matcher("" + numberBathrooms);
if (!m.matches())
  System.err.println("无效");

有效: 0.5, 1, 1.5<br>
无效: 0, 0.4, 2.7
英文:

You could use pattern-matching

Pattern numpat = Pattern.compile( &quot;\\d\\.((?&lt;!0\\.)0|5)&quot; );
Matcher m = numpat.matcher( &quot;&quot; + numberBathrooms );
if( ! m.matches() )
  System.err.println( &quot;invalid&quot; );

valid:&nbsp; &nbsp; 0.5, 1, 1.5<br>
invalid: 0, 0.4, 2.7

huangapple
  • 本文由 发表于 2020年4月8日 14:29:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/61094550.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定