我遇到一个小问题,让这个程序正常运行。
/**
*
* @author Randy
*/
import java.util.Scanner;//Import scanner
public class RandyGilmanhw2a {
int year_of_birth;
int age;
public RandyGilmanhw2a (){//begin constructor
year_of_birth = 1900;
age = 0;
}//end constructor
public int getYear(){//get year method
return year_of_birth;
}//end method
public int getAge(int year_of_birth){//get year method
age = 2014 - year_of_birth;
return age;
}//end get year method
public void setYear (int year){//set year method
this.year_of_birth = year;
}//end method
public static void main(String[] args) {//begin main
RandyGilmanhw2a user1 = new RandyGilmanhw2a();
Scanner year = new Scanner(System.in);//create a scanner object
System.out.println("Please enter the year you were born: ");
int year_of_birth = year.nextInt();
while( year_of_birth < 1900 || year_of_birth > 2014 ) {//begin while loop
System.out.println("Please reenter the year you were born." );
System.out.println("You must have an integer between 1900 and 2014:" );
System.out.println("\n");
System.out.println("Please enter the year you were born: ");
int year_of_birth = year.nextInt();//ERROR OCCURS HERE SAYS VARIABLE
//year_of_birth ALREADY DEFINED IN METHOD MAIN
}//end while
user1.getAge(year_of_birth);
System.out.println("You are " + age + " years old." );//ERROR HERE SAYS NON-STATIC
// VARIABLE age CANNOT BE REFERENCED FROM A STAIC CONTEXT
}//end main
}//end class
我评论了显示错误的区域。我正在尝试制作一个程序,显示他们进入那个年龄的人的年龄。但是,如果他们在1900年之前或2014年之后进入一年,我希望它要求用户重新进入他们的出生年份。我似乎无法找到问题。任何帮助将不胜感激。
答案 0 :(得分:3)
只需删除int
声明即可。这样,您就可以重新定义变量。
所以,切换这个:
int year_of_birth = year.nextInt();
到此:
year_of_birth = year.nextInt();
答案 1 :(得分:2)
在int
移除int year_of_birth = year.nextInt();
并将年龄输出更改为:
System.out.println("You are " + user1.getAge(year_of_birth) + " years old." );
答案 2 :(得分:1)
从int
的第二次初始化中删除year_of_birth
,您的问题就会消失。
答案 3 :(得分:1)
不要在while循环中将year_of_birth
再次定义为int
,因为您已在循环中定义。
while( year_of_birth < 1900 || year_of_birth > 2014 ) {//begin while loop
...
year_of_birth = year.nextInt();//just assign next value
...
}