gpt4 book ai didi

java - 在 if 语句的方法中比较数组列表的元素

转载 作者:行者123 更新时间:2023-11-29 04:52:12 24 4
gpt4 key购买 nike

我必须创建一个 peghole 游戏程序,它将显示数字 1 到 10,然后提示用户选择一个数字设置为 0。1-10 都存储在一个数组列表中,如果用户尝试创建一个已经被他们设置为 0 的元素,再次设置为 0,然后 if 语句将显示消息“Peghole is already filled!”。如何将用户选择的元素的值与 0 进行比较?我正在尝试在 peg_hole 方法中完成此操作。

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);
}
}
}

最佳答案

对于 ArrayList,您需要使用结构 list.get(index) 而不是 list[index]

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.get(holetofillInt);
if(checkInt == 0){
System.out.println("Peghole is already filled!");
}
else{
//set selected hole to 0
pegboard.set(holetofillInt,0);
return holetofillInt;
}
}

关于java - 在 if 语句的方法中比较数组列表的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35027583/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com