【问题标题】:Comparing element of an arraylist in method for an if statement在 if 语句的方法中比较数组列表的元素
【发布时间】:2016-05-03 19:51:21
【问题描述】:

我必须创建一个 peghole 游戏程序,它会显示数字 1 到 10,然后提示用户选择一个设置为 0 的数字。1-10 都存储在一个数组列表中,如果用户尝试制作一个已经被他们设置为 0 的元素,再次设置为 0 然后 if 语句将显示消息“Peghole 已填充!”。如何将用户选择的元素的值与 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);
    }
}
}

【问题讨论】:

  • 试试pegboard.get(holetofillInt);

标签: java if-statement arraylist methods compare


【解决方案1】:

对于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;
    }
}

【讨论】:

    【解决方案2】:

    对于您的if 条件,请执行pegboard.get(holetofillInt).equals(0)

    确实不需要整数checkInt

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多