我正在学习java作为初学者,我正在尝试创建一个计算未来年龄的程序。
我遇到以下问题:
错误:(14,64)java:找不到符号 符号:方法getYear() location:class ageProgram
我似乎无法获得我的getter方法eventho它们被宣布为公开。
ageProgram.java:
import java.util.Scanner;
public class ageProgram {
public static void main(String[]args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("enter your birth year");
int yearBirth = keyboard.nextInt();
System.out.println("enter a (future) year");
int yearTo = keyboard.nextInt();
ageCalculator agecalculator = new ageCalculator(yearBirth, yearTo);
if (yearBirth > yearTo) {
System.out.println("You will be born in %s years", getYear());
} else {
System.out.println("You are %s years old", getYear());
}
}
}
ageCalculator.java:
public class ageCalculator {
public ageCalculator(int yearBirth, int yearTo) {
if (yearBirth > yearTo) {
int year = (yearBirth - yearTo);
year = year.toString();
} else {
int year = (yearTo - yearBirth);
year = year.toString();
}
}
public String getYear() {
return year;
}
}
我不确定我做错了什么......我试图在stackoverflow上检查类似/其他问题的解决方案,但似乎没有任何效果。
感谢您的帮助!
答案 0 :(得分:1)
您必须告诉您所指的方法getYear
是哪个对象。在您的示例中,您必须将getYear
称为agecalculator.getYear()
,一切都应该没问题。
答案 1 :(得分:0)
试试这个
ageProgram.java
import java.util.Scanner;
public class ageProgram {
public static void main(String[]args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("enter your birth year");
int yearBirth = keyboard.nextInt();
System.out.println("enter a (future) year");
int yearTo = keyboard.nextInt();
ageCalculator agecalculator = new ageCalculator(yearBirth, yearTo);
if (yearBirth > yearTo) {
System.out.format("You will be born in %s years", agecalculator.getYear());
} else {
System.out.format("You are %s years old", agecalculator.getYear());
}
}
}
ageCalculator.java
public class ageCalculator {
String yearText;
public ageCalculator(int yearBirth, int yearTo) {
if (yearBirth > yearTo) {
int year = (yearBirth - yearTo);
yearText = String.valueOf(year);
} else {
int year = (yearTo - yearBirth);
yearText = String.valueOf(year);
}
}
public String getYear() {
return yearText;
}
}
如果你不理解,我可以解释
编辑:我最初没有得到它,但上面的答案也是正确的。你应该使用agecalculater.getYear()来调用方法 编辑:你应该用大写字母开始一个类名。你可以使用
yearText = String.valueOf(yearBirth - yearTo);
而不是
int year = (yearTo - yearBirth);
yearText = String.valueOf(year);