我必須創建一個包裝類來保存任何原始數據類型。我創建了這個類,它除了布爾類型以外都適用於所有其他類型。這是我的代碼:數據類型原始對象沒有正確初始化布爾值
byte a; // the byte in primitive
short b; // the short
int c, j; // int c is is int, j is the counter for Primitive to tell what dataType it is
long d; // the long
float e; //the float
double f; // the double
boolean g; // the boolean, with which I am having problems
char h; // the char
...;
public Primitive(boolean i) {
g = i;
j = 6;
}
頂端方法按預期工作,但是,當我嘗試我的複製方法,它使布爾值等於真,不管我是否是真還是假。
public Primitive(Primitive i){
switch (i.j){
case 0: a = i.a; break;
case 1: b = i.b; break;
case 2: c = i.c; break;
case 3: d = i.d; break;
case 4: e = i.e; break;
case 5: f = i.f; break;
case 6: g = i.g; break;
case 7: h = i.h; break;
}
}
任何幫助將不勝感激。
編輯**
測試拷貝構造函數的所有情況後,我發現,拷貝構造函數不會爲數據類型短,布爾和char工作。它適用於其他一切。這是我修改過的代碼:
public class Primitive {
private byte bytes;
private short shorts;
private int integer;
private final int DATATYPE;
private long longs;
private float floaters;
private double doubles;
private boolean bools;
private char character;
Compare compare = new Compare();
/**************************************************|
|* Constructors *|
|**************************************************/
public Primitive(byte i) {
bytes = i;
DATATYPE = 0;
}
public Primitive(short i) {
shorts = i;
DATATYPE = 1;
}
public Primitive(int i) {
integer = i;
DATATYPE = 2;
}
public Primitive(long i) {
longs = i;
DATATYPE = 3;
}
public Primitive(float i) {
floaters = i;
DATATYPE = 4;
}
public Primitive(double i) {
doubles = i;
DATATYPE = 5;
}
public Primitive(boolean i) {
bools = i;
DATATYPE = 6;
}
public Primitive(char i) {
character = i;
DATATYPE = 7;
}
public Primitive(Primitive i){
switch (i.DATATYPE){
case 0: bytes = i.bytes; break;
case 1: shorts = i.shorts; break;
case 2: integer = i.integer; break;
case 3: longs = i.longs; break;
case 4: floaters = i.floaters; break;
case 5: doubles = i.doubles; break;
case 6: bools = i.bools; break;
case 7: character = i.character; break;
}
DATATYPE = i.DATATYPE;
}
...;
}
我打算嘗試ENUM,但我忘記了如何使用它。那,我認爲一個整數比ENUM更容易操作。
你試過調試嗎? – Dagriel
我們能看到整個來源嗎?我絕對認爲這裏有一些缺失導致了問題。 – John
我將添加整個程序。 – oakTree