保持意想不到的类型

时间:2014-07-04 06:58:57

标签: java java.util.scanner

我正在为学校写一个程序。我已经完成了大部分工作,但我一直收到错误意外类型:在我的扫描仪对象之后找到所需的值类。它对我来说看起来不错,但我一直收到这个错误。任何帮助将不胜感激。

/**
 *
 * @author Randy
 */
import java.util.Scanner;//Import scanner

public class RandyGilmanhw2a {
    static int year_of_birth;
    static 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 = int year.nextInt();


        while( year_of_birth < 1900 || year_of_birth > 2014 ) {//begin while loop
            System.out.print("Please reenter the year you were born." );
            System.out.print("You must have an integer between 1900 and 2014:" );
            System.out.print("\n");
        }//end while 

        user1.getAge(year_of_birth);
        System.out.print("You are " + age + "years old." );

    }//end main

}//end class

具体来说,就是这个代码。

int year_of_birth = int year.nextInt();

由于

2 个答案:

答案 0 :(得分:1)

<强>问题:

 int year.nextInt();

它不是local field,它是object调用其方法(nextInt),它将返回一个整数,因此初始化为year_of_birth的正确方法是:

int year_of_birth = year.nextInt();//remove the int

答案 1 :(得分:0)

使用与该类字段同名的局部变量不是错误。

Eclipse之类的IDE通常会有一些选项,可以将这样的名称阴影标记为警告,这样您就会知道何时意外地执行此操作。

但请注意,您始终可以通过添加“this。”来访问该类的字段,例如“this.year_of_birth”。

对此进行更改,以证明我的意思:

   int year_of_birth_test = year.nextInt();//remove the int