2014-07-05 44 views
1

我在使該程序正常運行時遇到小問題。掃描儀對象在While循環中給我錯誤

/** 
* 
* @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年之後進入,我希望它會要求用戶重新輸入其出生年份。我似乎無法找到問題。任何幫助,將不勝感激。

回答

3

只要刪除int聲明。這樣,你正在重新定義變量。 那麼,關掉這個:

int year_of_birth = year.nextInt(); 

這樣:

year_of_birth = year.nextInt(); 
+0

謝謝你,修好了。 –

1

year_of_birth第二初始化取出int和您的問題就會消失。

2

int year_of_birth = year.nextInt();刪除int和年齡輸出改成這樣:

System.out.println("You are " + user1.getAge(year_of_birth) + " years old."); 
+0

謝謝你的工作。 –

1

不要在while循環再次定義year_of_birthint當你在出循環的定義。

while(year_of_birth < 1900 || year_of_birth > 2014) {//begin while loop 
     ... 
     year_of_birth = year.nextInt();//just assign next value 
     ... 
    }