在我的任務中,我應該創建一個程序,該程序使用開關盒訪問不同類的方法來執行某些操作。第一種情況需要用戶輸入,並且該輸入用於其他類的構造函數中。然而,如果我在第一種情況下初始化類對象,我從其他情況下得到錯誤,因爲對象可能尚未初始化。我如何爲擁有我的方法的類創建該對象,並仍然將開關案例中提示的用戶輸入獲取到構造函數中?我知道構造函數的參數之前如何初始化類對象?
public class NumberList{
int length; int offset;
public NumberList(int length, int offset){ //constructor
this.length = length; this.offset = offset;
}
public void shift(int a){ //shift method
temp = numbers[0];
for (int i = 0; i < length-1; i++) {
numbers[i] = numbers[i+1];
}
numbers[length - 1] = temp;
}
說這是我的班,有一個方法來移動數組元素。我的主要方法是
public class assignment7{
public static void main(String[] args){
int choice;
do{
System.out.println("input choice");
choice = scan.nextInt();
switch(choice){
case '1':
System.out.println("input the array size.");
size = scan.nextInt();
System.out.println("input the array offset.");
offset = scan.nextInt();
NumberList numbasbrah = new NumberList(size, offset);
numbasbrah.printInfo();
break;
case '2':
numbasbrah.shift();
numbasbrah.printInfo();
break;
case '3': //quit
break;
}while(choice!=3);
}} //end main method
所以如果我創建的開關情況下,我得到「變量可能尚未初始化」錯誤的NumberList對象,但它需要有這樣我就可以在添加用戶輸入構造函數。我如何初始化對象,同時仍然能夠在開關情況下添加構造函數的信息?
這是所有的代碼? NumberList如何在沒有任何數字聲明[]的情況下編譯? –
不,我試圖壓縮......它可能是總代碼的1/8,實際的NumberList總共有6種方法 –
所以如果用戶選擇案例2,那麼應該移動什麼?那裏會有默認值嗎? –