我正在用Java编写一个小的排序程序,旨在获取一个“学生”对象,并根据参数和属性确定它的名称、职业和课堂。然而,当我尝试创建第一个对象时,出现了一个问题。到目前为止,一切看起来都是这样的:
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);
}
}
错误出现在对象创建行,因为由于某些原因,当构造函数调用shorts时,它坚持将0,0解释为整数,从而导致不匹配问题。
有什么想法吗?
发布于 2012-09-25 12:21:35
一种方法是使用强制转换告诉编译器该值是一个short
:
Student Andreiy = new Student("Andreiy",(short)0,(short)0);
或者,重新定义Student
类以接受int
而不是short
。(对于职业代码,我建议使用enum
。)
发布于 2012-09-25 12:44:18
您应该将Integer转换为short。整数到短整型转换需要缩小范围,因此需要显式强制转换。只要你有内存限制,你就应该在java中使用整数。
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;
}
}
然后你可以像下面这样做
new Student("Andreiy", Career.Computer_Science, 0);
https://stackoverflow.com/questions/12575876
复制相似问题