创建一个包含整数、getter和setter方法以及输入验证的类。

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

Creating a class that has integers, getter/setters, with input validation

问题

以下是您提供的内容的翻译部分:

我正在处理这个 Java 程序在这个程序中我应该编写一个名为 kumquat 的类其中有一个整型 age并带有 getter 和 setter 方法此外我需要进行输入验证我无法弄清楚我在做什么错误如果这非常简单我很抱歉因为我仍然是一个新手

public class Person
{
    private int age;
    
    public int getAge()
    {
        return age;
    }
    
    public void setAge(int newAge)
    {
        this.age = newAge;
    }
}

然后是我的主要部分

public class Kumquat
{

    public static void main(int[] args)
    {
        Person myObj = new Person();
        myObj.setAge("5");
        System.out.println(myObj.getAge());
    }

}
英文:

I am working on this Java program where I am supposed to write a class called kumquat that has an integer age with getter and setters. Additionally, I need to do input validation. I can't figure out what I'm doing wrong. I'm sorry if this is really simple I'm just still really new to this.

public class Person
{
    private int age;
    
    public int getAge()
    {
        return age;
    }
    
    public void setAge(int newAge)
    {
        this.age = newAge;
    }
}

and then my main

public class Kumquat
{

    public static void main(int[] args)
    {
        Person myObj = new Person();
        myObj.setAge("5");
        System.out.println(myObj.getAge());
    }
    
}

答案1

得分: 1

Person 类中一切正常。尽管在您的 main 函数中,方法 Person::setAge 接收一个 int 类型的参数,但是您在第 myObj.setAge("5"); 行尝试传递了一个 String 类型。请尝试传递一个 int,如 myObj.setAge(5);

英文:

Everything is ok in the Person class. Although in your main the method Person::setAge receives an int as parameter and you're trying to pass a String in line myObj.setAge("5");. Try passing an int like myObj.setAge(5); instead.

答案2

得分: 0

你应该使用 String 而不是 int,并且 setAge 不应该是 string。

public static void main(String[] args)
{
    Person myObj = new Person();
    myObj.setAge("5");
    System.out.println(myObj.getAge());
}
英文:

you should write String instead of int and setAge should not be string

public static void main(String[] args)
{
    Person myObj = new Person();
    myObj.setAge(5);
    System.out.println(myObj.getAge());
}

huangapple
  • 本文由 发表于 2020年10月17日 07:32:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/64397668.html
匿名

发表评论

匿名网友

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

确定