英文:
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());
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论