【问题标题】:I have some problems with ArrayList (quiz of head first java)我对 ArrayList 有一些问题(head first java 的测验)
【发布时间】:2021-11-27 19:37:30
【问题描述】:

我从上周开始学习 java。我正在使用名为“head first java”的书,并且正在努力解决有关 ArrayList 的问题。错误提示“DotCom 类型中的方法 setLocationCells(ArrayList) 不适用于 参数(int [])”,我还没有找到解决方案:(帮助我..!

enter image description here

【问题讨论】:

  • 你好。请不要将文本/代码发布为图像/链接 (more info),而应以格式化文本的形式发布。使用edit 选项更正您的帖子。
  • "DotCom 类型中的方法 setLocationCells(ArrayList) 不适用于参数 (int[])" ArrayList 与 int[] 数组无关,Java 不会自动将 int[] 转换为ArrayList。如果你想传递int[] 作为参数创建方法,它将接受int[] 作为参数。

标签: java string oop arraylist integer


【解决方案1】:

这看起来像一个定位与征服类型的游戏类似类似于名为 Battleship 的游戏,不同的是这个游戏是一个单人游戏,只有一艘隐藏的船在单个水平行的柱状字符。相当简单,但我想玩起来很有趣。困难的部分是定位隐藏的船,但是一旦你找到它,征服(下沉)它就变得相对容易了。我确信这不是游戏的意图,因为它毕竟被命名为“The Dot Com Game”,但这个类比可能会有所帮助。

您的代码存在几个问题,但有两个主要问题无法让游戏正常运行:


问题 #1:对DotCom.setLocationCells() 方法的调用:

最初的问题位于代码 第 13 行 上的 DotComGame 类中(如异常所示),其中调用了DotCom.setLocationCells() 方法。正如在 cmets 中已经提到的,错误的参数类型被传递给了这个方法。当此方法包含规定它需要ArrayList 对象的参数签名时,您不能将int[] 数组传递给setLocationCell() 方法。我认为最好的解决方案是满足setLocationCells() 方法参数要求...为此方法提供ArrayList

我之所以这么说是因为 DotCom 类中的所有方法都使用已建立的 ArrayList 并且其中一种方法(checkYourself() 方法)的任务之一实际上从ArrayList 很容易从集合中完成,但从 Array 中执行同样的操作非常麻烦。

要解决此问题,您需要更改位于 DotComGame 类中的 locations 变量的数据类型。而不是使用:

int[] locations = {randomNum, randomNum + 1, randomNum + 2};

你应该有:

ArrayList<Integer> locations = new ArrayList<>(
     Arrays.asList(random, randomNum + 1, randomNum + 2));

或者你可以这样做:

ArrayList<Integer> locations = new ArrayList<>();
    locations.add(randomNum);
    locations.add(randomNum + 1);
    locations.add(randomNum + 2);

还有其他方法,但这些方法暂时可用。现在,当调用 setLocationCells() 方法时,您应该不会得到异常,这个问题现在应该得到解决。


问题 #2:DotCom.checkYourself() 方法的调用:

同样,此特定问题位于代码 第 18 行 上的 DotComGame 类中,其中调用了DotCom.checkYourself() 方法。又一个参数数据类型不匹配。您正在尝试将String(名为guess)类型的变量传递给此方法,而其签名规定它需要一个整数(int)值。这又是不行。

要解决此问题,您需要将guess 变量保存的字符串数值转换为整数(int) 值。所以不要这样:

while(isAlive) {
    String guess = helper.getUserInput("Enter a Number: ");
    String result = theDotCom.checkYourself(guess);
    // ... The rest of your while loop code ...
}

你应该有类似的东西:

while(isAlive) {
    String guess = helper.getUserInput("Enter a Number: ");
    /* Validate. Ensure guess holds a string representation
       of a Integer numerical value.           */
    if (!guess.matches("\\d+")) {
        System.err.println("Invalid Value (" + guess 
                         + ") Supplied! Try again...");
        continue;
    }
    int guessNum = Integer.parseInt(guess);
    String result = theDotCom.checkYourself(guessNum);
    numOfGuesses++;
    if (result.equals("kill")) {
        isAlive = false;
        System.out.println(numOfGuesses + " guesses!");
    }
    else if (result.equals("hit")) {
        // Do Something If You Like
        System.out.println("HIT!");
    }
    else {
        System.out.println("Missed!");
    }
}

下面是一个名为 Simple Battleship 的游戏,我基于您的代码图像(请不要再将图像用于代码 - 我讨厌使用在线 OCR;)

BattleshipGame.java - 应用程序启动类:

import java.awt.Toolkit;

public class BattleshipGame {

        public static int gameLineLength = 10;
        
    public static void main(String[] args) {
        GameHelper helper = new GameHelper();
        Battleship theDotCom = new Battleship();
        int score = 0;  // For keeping an overall score
        
        // Display About the game...
        System.out.println("Simple Battleship Game");
        System.out.println("======================");
        System.out.println("In  this  game  you will be  displayed a  line of  dashes.");
        System.out.println("Each  dash  has the  potential  to  hide a  section  of  a");
        System.out.println("hidden  Battleship.  The  size of this  ship  is  randomly");
        System.out.println("chosen by the  game engine and can be from 1 to 5 sections");
        System.out.println("(characters) in length. The score for each battle is based");
        System.out.println("on the length  of  the game line that will be displayed to");
        System.out.println("you  (default is a minimum of 10 charaters).  You now have");
        System.out.println("the option to supply the game line length you want to play");
        System.out.println("with.  If you want to use the default then just hit ENTER:");
        System.out.println();
        
        // Get the desire game line length
        String length = helper.getUserInput("Desired Game Line Length: --> ", "Integer", true, 10, 10000);
        if (!length.isEmpty()) {
            gameLineLength = Integer.parseInt(length);
        }
        System.out.println();

        // Loop to allow for continuous play...
        boolean alwaysReplay = true;
        while (alwaysReplay) {
            int numOfGuesses = 0;
            
            /* Create a random ship size to hide within the line.
               It could be a size from 1 to 5 characters in length.   */
            int shipSize = new java.util.Random().nextInt((5 - 1) + 1) + 1;
            int randomNum = (int) (Math.random() * (gameLineLength - (shipSize - 1)));
            int[] locations = new int[shipSize];
            for (int i = 0; i < locations.length; i++) {
                locations[i] = randomNum + i;
            }
            
            System.out.println("Destroy the " + shipSize + " character ship hidden in the");
            System.out.println("displayed line below:");
            System.out.println();
            String gameLine = String.join("", java.util.Collections.nCopies(gameLineLength, "-"));
            theDotCom.setLocationCells(locations);
            
            // Play current round...
            boolean isAlive = true;
            while (isAlive == true) {
                System.out.println(gameLine);
                String guess = helper.getUserInput("Enter a number from 1 to " + gameLineLength
                        + " (0 to quit): --> ", "Integer", 1, gameLineLength);
                int idx = Integer.parseInt(guess);
                if (idx == 0) {
                    System.out.println("Quiting with an overall score of: " + score + " ... Bye-Bye");
                    alwaysReplay = false;
                    break;
                }
                idx = idx - 1;
                String result = theDotCom.checkYourself(idx);
                numOfGuesses++;
                System.out.println(result);
                if (result.equalsIgnoreCase("kill")) {
                    Toolkit.getDefaultToolkit().beep();
                    isAlive = false;
                    /* Tally the score dependent upon the gameLineLength...  */
                    if (gameLineLength <= 10) { score += 5; }
                    else if (gameLineLength > 10 && gameLineLength <= 20) { score += 10; }
                    else if (gameLineLength > 20 && gameLineLength <= 30) { score += 15; }
                    else if (gameLineLength > 30 && gameLineLength <= 40) { score += 20; }
                    else { score += 25; }
                    gameLine = gameLine.substring(0, idx) + "x" + gameLine.substring(idx + 1);
                    System.out.println(gameLine);
                    System.out.println(numOfGuesses + " guesses were made to sink the hidden ship.");
                    System.out.println("Your overall score is: " + (score < 0 ? 0 : score));
                }
                else if (result.equalsIgnoreCase("hit")) {
                    gameLine = gameLine.substring(0, idx) + "x" + gameLine.substring(idx + 1);
                }
                if (result.equalsIgnoreCase("miss")) {
                    score -= 1;
                }
                System.out.println();
            }

            // Play Again? [but only if 'alwaysReplay' holds true]
            if (alwaysReplay) {
                String res = helper.getAnything("<< Press ENTER to play again >>\n"
                                          + "<<   or enter 'q' to quit    >>");
                if (res.equalsIgnoreCase("q")) {
                    System.out.println("Quiting with an overall score of: " + score + " ... Bye-Bye");
                    break;
                }
                System.out.println();
            }
        }
    }
}

GameHelper.java - GameHelper 类:

import java.util.Scanner;

public class GameHelper {
   
    private final Scanner in = new Scanner(System.in);
    
    public String getUserInput(String prompt, String responseType, int... minMAX) {
        int min = 0, max = 0;
        if (minMAX.length == 2) {
            min = minMAX[0];
            max = minMAX[1];
        }
        if (minMAX.length > 0 && min < 1 || max < 1) {
             throw new IllegalArgumentException("\n\ngetUserInput() Method Error! "
                     + "The optional parameters 'min' and or 'max' can not be 0!\n\n");
        }
        
        String response = "";
        while (response.isEmpty()) {
            if (prompt.trim().endsWith("-->")) {
                System.out.print(prompt);
            }
            else {
                System.out.println(prompt);
            }
            response = in.nextLine().trim();
            if (responseType.matches("(?i)\\b(int|integer|float|double)\\b")) {
                if (!response.matches("-?\\d+(\\.\\d+)?") || 
                        (responseType.toLowerCase().startsWith("int") && response.contains("."))) {
                    System.err.println("Invalid Entry (" + response + ")! Try again...");
                    response = "";
                    continue;
                }
            }
            // Check entry range value if the entry is to be an Integer
            if (responseType.toLowerCase().startsWith("int")) {
                int i = Integer.parseInt(response);
                if (i != 0 && (i < min || i > max)) {
                    System.err.println("Invalid Entry (" + response + ")! Try again...");
                    response = "";
                }
            }
        }
        return response;
    }
    
    public String getUserInput(String prompt, String responseType, boolean allowNothing, int... minMAX) {
        int min = 0, max = 0;
        if (minMAX.length == 2) {
            min = minMAX[0];
            max = minMAX[1];
        }
        if (minMAX.length > 0 && min < 1 || max < 1) {
             throw new IllegalArgumentException("\n\ngetUserInput() Method Error! "
                     + "The optional parameters 'min' and or 'max' can not be 0!\n\n");
        }
        
        String response = "";
        while (response.isEmpty()) {
            if (prompt.trim().endsWith("-->")) {
                System.out.print(prompt);
            }
            else {
                System.out.println(prompt);
            }
            response = in.nextLine().trim();
            if (response.isEmpty() && allowNothing) {
                return "";
            }
            if (responseType.matches("(?i)\\b(int|integer|float|double)\\b")) {
                if (!response.matches("-?\\d+(\\.\\d+)?") || 
                        (responseType.toLowerCase().startsWith("int") && response.contains("."))) {
                    System.err.println("Invalid Entry (" + response + ")! Try again...");
                    response = "";
                    continue;
                }
            }
            // Check entry range value if the entry is to be an Integer
            if (responseType.toLowerCase().startsWith("int")) {
                int i = Integer.parseInt(response);
                if (i != 0 && (i < min || i > max)) {
                    System.err.println("Invalid Entry (" + response + ")! Try again...");
                    response = "";
                }
            }
        }
        return response;
    }
    
    public String getAnything(String prompt) {
        if (prompt.trim().endsWith("-->")) {
            System.out.print(prompt);
        }
        else {
            System.out.println(prompt);
        }
        return in.nextLine().trim();
    }
}

Battleship.java - 战舰类:

import java.util.ArrayList;

public class Battleship {
    
    private ArrayList<Integer> locationCells;
    
    public void setLocationCells(java.util.ArrayList<Integer> loc) {
        locationCells = loc;
    }
    
    // Overload Method (Java8+)
    public void setLocationCells(int[] loc) {
        locationCells = java.util.stream.IntStream.of(loc)
                                   .boxed()
                                   .collect(java.util.stream.Collectors
                                           .toCollection(java.util.ArrayList::new));
    }
    
    /* 
    // Overload Method (Before Java8)
    public void setLocationCells(int[] loc) {
        // Clear the ArrayList in case it was previously loaded.
        locationCells.clear(); 
        // Fill the ArrayList with integer elements from the loc int[] Array
        for (int i = 0; i < loc.length; i++) {
            locationCells.add(loc[i]);
        }
    }
    */
    
    /**
     * Completely removes one supplied Integer value from all elements
     * within the supplied Integer Array if it exist.<br><br>
     * 
     * <b>Example Usage:</b><pre>
     *
     * {@code     int[] a = {103, 104, 100, 10023, 10, 140, 2065};
     *      a = removeFromArray(a, 104);
     *      System.out.println(Arrays.toString(a);
     *
     *      // Output will be:  [103, 100, 10023, 10, 140, 2065]}</pre>
     *
     * @param srcArray     (Integer Array) The Integer Array to remove elemental
     *                     Integers from.<br>
     *
     * @param intToDelete (int) The Integer to remove from elements within the 
     *                    supplied Integer Array.<br>
     *
     * @return A Integer Array with the desired elemental Integers removed.
     */
    public static int[] removeFromArray(int[] srcArray, int intToDelete) {
        int[] arr = {};
        int cnt = 0;
        boolean deleteIt = false;
        for (int i = 0; i < srcArray.length; i++) {
            if (srcArray[i] != intToDelete) {
                arr[cnt] = srcArray[i];
                cnt++;
            }
        }
        return arr;
    }
    
    public String checkYourself(int userInput) {
        String result = "MISS"; 
        int index = locationCells.indexOf(userInput); 
        if (index >= 0) { 
            locationCells.remove(index); 
            if (locationCells.isEmpty()) { 
                result = "KILL"; 
            } 
            else { 
                result = "HIT";
            }
        } 
        return result; 
    }
}

【讨论】:

    猜你喜欢
    • 2018-11-13
    • 1970-01-01
    • 2021-04-07
    • 2020-04-08
    • 2023-03-26
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多