使用不带参数的for循环时,此方法将使用数字1到10填充ArrayList
。我尝试执行此操作的方法是靠近顶部的create_pegboard
。我应该为for循环填写什么来完成这个?
import java.util.*;
import java.util.Scanner;
public class PegBoardGame {
public static ArrayList create_pegboard(){
//for loop and add method to holes 1-10
for(){
}
}
public static void print_pegboard(ArrayList pegboard) {
//print results from array 1-10 or final result
System.out.println("-----------------------------------------");
System.out.println(pegboard);
System.out.println("-----------------------------------------");
}
public static Integer peg_hole(ArrayList pegboard){
Scanner in = new Scanner(System.in);
//variable for user input
int holetofillInt;
int checkInt;
//prompt for input
System.out.println("Select a peghole 1-10 to fill");
holetofillInt = in.nextInt();
//if peg chosen by user is already 0 then print error message
checkInt = pegboard[holetofillInt];
if( ){
System.out.println("Peghole is already filled!");
}
else{
//set selected hole to 0
pegboard.set(holetofillInt,0);
return holetofillInt;
}
}
public static void main(String[] args) {
//create array list with peghole numbers
ArrayList<Integer> pegboard = create_pegboard();
//print the pegboard unchanged
print_pegboard(pegboard);
//construct array list up to 10
for (int i = 0; i < 10; i++) {
//see if they want to change and change what hole is peggged
peg_hole(pegboard);
//print changed peghole board
print_pegboard(pegboard);
}
}
}
答案 0 :(得分:1)
您的方法应该创建一个新的整数ArrayList,然后使用for循环填充数字1-10,然后返回您已创建的新填充列表。
这就是您正在寻找的。 p>
public static ArrayList create_pegboard(){
//for loop and add method to holes 1-10
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i = 1; i<=10; i++){
list.add(i);
}
return list;
}
答案 1 :(得分:0)
如果没有传递参数,请确保数组在整个类中具有范围,然后以与方法之外相同的方式执行。
我的建议是将数组传入。