1

I'm writing a little sorting program in Java designed to grab a "student" object and determine what its name, career and classroom is dependent on parameters and attributes. A problem turns up, however, when I try to create the first object. Thus far, everything looks like this:

public class Student {
    private String name, classroom;
    /**
     * The career code is as follows, and I quote:
     * 0 - Computer Science
     * 1 - Mathematics
     * 2 - Physics
     * 3 - Biology
     */
    private short career, idNumber;

    public Student (String name, short career, short idNumber){
        this.name = name;
        this.classroom = "none";
        this.career = career;
        this.idNumber  = idNumber;
    }

    public static void main(String args[]){
        Student Andreiy = new Student("Andreiy",0,0);
    }
}

The error turns up on the object creation line, as for some reason it insist on interpreting 0,0 as integers when the constructor calls for shorts, leading to a mismatch problem.

Any ideas?

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
user1696111
  • 13
  • 1
  • 6

2 Answers2

2

One way is to tell the compiler that the value is a short using a cast:

Student Andreiy = new Student("Andreiy",(short)0,(short)0);

Alternatively, redefine the Student class to accept int instead of short. (For the career code, I'd suggest using an enum.)

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

You should convert Integer to short. Integer to short conversion requires narrowing so explicit cast is required. You should use integers in java as long as you have memory constraints.

public Student (String name, Career career, int idNumber)

//Enumeration for Career so no additional checks are required.
 enum Career
 {
     Computer_Science(0),Mathematics(1),Physics(2),Biology(3);
     private Career(int code)
     {
         this.code = code;
     }
     int code ;

     public int getCode()
     {
         return code;
     }

 }

And then you can do something like below

new Student("Andreiy", Career.Computer_Science, 0);
Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72