我会尽力解释这个问题。在学校我们正在创建一个程序,允许您选择是否要创建数组或ArrayList,然后向它们添加数字。那部分工作正常。
问题在于你还将获得将数组转换为ArrayList的选项,反之亦然。当我尝试使用案例开关将数组或arraylist发送到类时,我得到了我没有初始化的错误。但是如果我将它设置为null以启动它,则只会在下次启动meny时重置用户输入。所以我想知道是否有办法初始化数组和arraylist一次,然后在下一次跳过它?我知道这是一个不好的解释,但如果你看一下代码,也许你明白我想问的是什么。
package labb;
import java.util.ArrayList;
import java.util.Scanner;
public class Meny {
@SuppressWarnings("resource")
public static boolean meny(Scanner input){
Scanner inputMeny = new Scanner(System.in);
ArrayList<Integer> arrayListNumbers = null;
System.out.println("\n What do you want to do? \n 1 : Arraylist? \n 2 : Array? \n 3 : Convert your Array to an Arraylist \n 4 : Convert your Arraylist to an Array \n 5 : Exit");
int answer = inputMeny.nextInt();
switch(answer){
case(1)://arrayList
arrayListNumbers = Array.readNumbersFromUser(input);
PrintNumbers.PrintOutNumbers(arrayListNumbers);
System.out.println("\n");
PrintNumbers.PrintOutNumbers2(arrayListNumbers);
return true;
case(2)://array
int[] arrayNumbers = Array.readNumbersFromUserArray(input);
PrintNumbers.printNumbersArray(arrayNumbers);
System.out.println();
PrintNumbers.printNumbers2Array(arrayNumbers);
return true;
case(3)://array to arrayList
case(4)://arrayList to array
int[] array = Convert.convertArrayListToArray(arrayListNumbers);
case(5):
System.out.println("Good bye");
inputMeny.close();
return false;
default:
System.out.println("Wrong input");
inputMeny.close();
return false;
}
}
}
答案 0 :(得分:0)
而不是调用public static boolean meny(Scanner input)调用public static boolean meny(Scanner input,ArrayList arrayListNumbers)。从您调用此方法(meny)的位置,获取arrayListNumbers
因此您的代码可能看起来像这样
您调用方法
ArrayList<Integer> arrayListNumbers = Array.readNumbersFromUser(input);
meny.meny(input, arrayListNumbers );
和班级
public class Meny {
@SuppressWarnings("resource")
public static boolean meny(Scanner input, ArrayList<Integer> arrayListNumbers){
Scanner inputMeny = new Scanner(System.in);
System.out.println("\n What do you want to do? \n 1 : Arraylist? \n 2 : Array? \n 3 : Convert your Array to an Arraylist \n 4 : Convert your Arraylist to an Array \n 5 : Exit");
int answer = inputMeny.nextInt();
.....