我在让这个程序正常运行时遇到了一个小问题。
/**
*
* @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 年之后的年份,我希望它要求用户重新输入他们的出生年份。我似乎找不到问题所在。任何帮助将不胜感激。
最佳答案
只需删除 int
声明。这样,您就可以重新定义变量。
所以,切换这个:
int year_of_birth = year.nextInt();
为此:
year_of_birth = year.nextInt();
关于java - 扫描仪对象在 While 循环中给我错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24589638/