2017-06-13 55 views
-4

我得到的问题是与getter和setter。不相容的类型:从短到短可能有损转换

我为变量数据类型short创建了setter和getters。

public String getName() { 
    return name; 
} 

public void setName(String name) { 
    this.name = name; 
} 

public int getAge() { 
    return age; 
} 

public void setAge(int age) { 
    this.age = age; 
} 

public String getFavoriteColor() { 
    return favoriteColor; 
} 

public void setFavoriteColor(String favoriteColor) { 
    this.favoriteColor = favoriteColor; 
} 

public long getFavoriteNumber() { 
    return favoriteNumber; 
} 

public void setFavoriteNumber(long favoriteNumber) { 
    this.favoriteNumber = favoriteNumber; 
} 

public short getHeightInCent() { 
    return heightInCent; 
} 


public void setHeightInCent(short heightInCent) { 
    this.heightInCent = heightInCent; 
} 


public short getWeight() { 
    return weight; 
} 


public void setWeight(short weight) { 
    this.weight = weight; 
} 

private String name; 
private int age; 
private String favoriteColor; 
private long favoriteNumber; 
private short heightInCent; 
private short weight; 

上面是存储此数据的Object类。在我的主类中,我将这些数据从中调用。除了heightInCent和weight之外,一切都被称为很好。我没有做任何不同的事情,并想知道为什么我得到这个错误?我查看了整个网络和这里的类似问题,但我发现的一切都是将一种数据类型转换为另一种。或者沿着这条线。 以下是我的主要课程。

public static void main(String args[]){ 

     PeopleObjects person1 = new PeopleObjects(); 


     person1.setAge(21); 
     person1.setName("James Bloggs"); 
     person1.setFavoriteColor("Green"); 
     person1.setFavoriteNumber(3248505); 
     person1.setWeight(144); 
     person1.setHeightInCent(159); 

     System.out.println(person1.getName() + ", " + person1.getAge() + ", " + person1.getHeightInCent() + "cm, " + person1.getWeight() + "lb"); 
     System.out.println("Favorite Color: " + person1.getFavoriteColor()); 
     System.out.println("Favorite number: " + person1.getFavoriteColor()); 

     person1.speak(); 

     int death = person1.yearsUntilDeath(); 
     System.out.println(death); 

     int age = person1.getAge(); 

     System.out.println(age); 

     String name = person1.getName(); 

     System.out.println(name); 

解决这个问题的答案会很棒!更好的是(如果你知道的话)解释为什么会发生这种情况。谢谢你们!

+4

你是否_sure_这是错误信息? –

+5

你可以发布[mcve]吗?如果(1)我们给出了完整程序的代码,我们可以运行这个代码来看看自己的问题,并且(2)程序中没有任何不必要的代码,那么我们更容易回答这个问题。 – Dukeling

+0

试着将person1.setWeight(144);改成person1.setWeight((简称)144);'和person1.setHeightInCent(159) – Eran

回答

0

一般:不要使用短裤或甚至字节。 Java使用整数并且不关心,例如,意思是短。如果你真的必须退换短片,你必须先投下它。 只是考虑这个(并没有其他方式):

byte[] someByteArray = { 
    (byte) 0x01, 
    (byte) 0x63 
} 
+0

谢谢atmin!这很有帮助!你和Eran帮助我理解我做错了什么,为什么错了! – soulparagon

相关问题