您能帮我在代码中找到问题吗?

时间:2019-11-05 14:16:58

标签: java json

我正在尝试为我的IT课做作业,我们只是开始进行一些编程。我们有2类,Main和Okej。这只是一个简单的代码,getter和setter必须检查用户是否输入了正确的数字。但是IF语句不起作用。你能帮忙吗?

package okej;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner program = new Scanner(System.in);

        System.out.println("Please, type your Name.");
        String name = program.nextLine();
        System.out.println("Please, type your age.");
        int age = program.nextInt();
        System.out.println("Please, type your weight.");
        double weight = program.nextDouble();


        Okej you = new Okej(name, age, weight);
        System.out.print(you);
    }

}

package okej;

import java.util.Scanner;

public class Okej {

    String name = "";
    int age = 0;
    double weight = 0.0;

    public Okej(String name, int age, double weight) {
        this.name = name;
        this.age = age;
        this.weight = weight;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        System.out.println("Okay, your name is " + name + ".");
        this.name = name;
    }

    public int getAge() {
        return age;
    }


    public void setAge(int age) {
        if (age > 18) {
            if (age < 99) {
        this.age = age;
        System.out.println("Okay, your age is " + age + "."); 
        }
    }
        else {
            System.out.println("You have put an invalid age for this program.");
            System.out.println("Setting the number to 20.");
            this.age = 20;
        }

    }

    public double getWeight() {
        return weight;
    }   

    public void setWeight(double weight) {
        if (weight > 30) {
            if (weight < 300) {
        this.weight = weight;
        System.out.println("Okay, your weight is " + weight + "."); 
            }
        }
        else {
            System.out.println("You have put an invalid weight for this program.");
            System.out.println("Setting the number to 50.");
            this.weight = 50;
        }
    }


    @Override
    public String toString() {
        return "Okay, your name is " + name + ", your age is " + age + ", and you weight "+ weight +".";
    }

}

1 个答案:

答案 0 :(得分:0)

它不起作用,因为验证您的输入的逻辑在setters内部,并且您没有调用它。您正在通过不执行任何验证的构造函数创建对象。您可以执行以下操作之一:

  • 将验证码移动到静态方法,并在构造函数中调用它以在分配值之前进行验证
  • 使用内部带有验证码的构建器
  • 创建一个空对象(使用默认构造函数)并使用设置器设置将触发您验证的值 ...