简体   繁体   English

Java:在链接列表上使用数组

[英]Java: Use an Array over a Linked list

I am relatively new to Java. 我对Java比较陌生。 And I am a Student in the second semester. 而且我是第二学期的学生。

The following has been my last task, and I have already presented it. 以下是我最后一次任务,我已经介绍了。 Everything was fine, and the task that was neccessary for me to accomplish has been completely fulfilled. 一切都很好,那就是neccessary为我完成任务已经完全履行。

The task over the semester was making a little game (My choice was guess a number game), and the tasks were simply build upon eachother. 这个学期的任务是做一个小游戏(我的选择是猜数字游戏),而这些任务只是彼此建立的。 (eg use at least 5 functions, at least 3 classes, show all four examples of OOP and make a Computer Player) So having that said I do not mean for people to solve these task because as you will see they have been completed. (例如,至少使用5个函数,至少3个类,显示OOP的所有四个示例并制作一个计算机播放器)。这么说并不是要人们解决这些任务,因为您将看到它们已经完成。

Just one additional thing gives me trouble. 仅有的另一件事给我带来麻烦。 I use a Linked list to store the guessed numbers and recall them when needed. 我用链表存储猜测号码并在需要时调出。 So finally my question is: How would I go about switching the Linked list with an Array? 所以最后我的问题是:我怎么会去使用数组转换链表?

Here the code: 这里的代码:

Here the Run Class: 在这里,运行类:

package fourfive;
public class Run {
/*
The Game Initializing class!
>>>> "game.getNumPlayers()" //can be uncommented if you want to play
if left commented, you can watch the bots fight to the death.
------------------------------------------------------
game.setBotPlayers //Same as getNumPlayers - defines how many (Bot) players you want to add
------------------------------------------------------
 game.setTopNum() // defines the maximum range of numbers
 which you want to guess. Starting from 0!
 -----------------------------------------------------
*/
public static void main(String[] args){
    Game game = new Game(0);
    //game.getNumPlayers();
    game.setBotPlayers(100);
    game.setTopNum(2000);
    game.start();
 }
}

Game Class: 游戏类别:

package fourfive;

import java.util.Random;
import java.util.Scanner;

public class Game {
/*
Some Variables being defined here.
 */
private static Scanner input = new Scanner(System.in);
private int MAX_Tries;
private int TOP_Num;
private int numPlayers;
private int numBots;
private boolean gameWinner = false;
private Random rand = new Random();
private int num;
private Participants[] players; //inheritance 1
private Participants currentPlayer; //polymorphism 1

public Game(int numPlayers) {
    this(numPlayers, 10);
}

public Game(int numPlayers, int maxTries) {
    this(numPlayers, maxTries, 1000);
}

public Game(int numPlayers, int maxTries, int topNum) {
    MAX_Tries = maxTries;
    TOP_Num = topNum;
    this.numPlayers = numPlayers;
    resetPlayers();
    resetTheNumber();
}

/*
Inheritance Example 1
The following is a piece of inheritance. Whereas an array of Players whenever of the type
"Participants". Which is then resolved into the type "Human" and that is being inherited from
"Participants". And whenever Bots or Human players are joined, they will be joined within
the same array
 */
public void resetPlayers() {
    players = new Human[numPlayers + numBots];
    for (int i = 0; i < numPlayers; i++) {
        players[i] = new Human(i + 1);
    }
    for (int i = numPlayers; i < (numBots + numPlayers); i++) {
        players[i] = new Computer(i + 1, TOP_Num);
    }
}

public void setNumPlayers(int numPlayers) {
    this.numPlayers = numBots;
    resetPlayers();
}

public void setBotPlayers(int numBots) {
    this.numBots = numBots;
    resetPlayers();
}

public int getMaxTries() {
    return MAX_Tries;
}

public void setMaxTries(int maxTries) {
    this.MAX_Tries = maxTries;
}

public int getTopNum() {
    return TOP_Num;
}

public void setTopNum(int topNum) {
    this.TOP_Num = topNum;
    resetTheNumber();
    resetPlayers();
}

private void resetTheNumber() {
    num = rand.nextInt(TOP_Num);
}

public void start() {
    resetPlayers();
    System.out.println("Welcome to the Guess a Number Game!\n");
    System.out.println("Guess a number between 0 and " + (TOP_Num - 1) + "!");
    currentPlayer = players[0];
    System.out.println("The num " + num);
    /*
    Polymorphism example.
    Any object that can pore than one IS-A test is considered to be Polymorphic.
    In this case we are setting up a condition in which any given player has
    the ability to win, which is depicted from the "isCorrect()" Method.
     */
    while (!gameWinner && currentPlayer.getNumTries() < MAX_Tries) {
        for (int i = 0; i < players.length; i++) {
            //currentPlayer = players[i];
            players[i].guess();
            if (isCorrect()) {
                gameWinner = true;
                printWinner();
                break;
            } else
                printWrong();
        }
        if (!gameWinner) {
            printTriesLeft();
        }
    }
    if (!gameWinner)
        printLoser();
}

public boolean isCorrect() {
    return currentPlayer.getLastGuess() == num;
}

public void printWinner() {
    if (currentPlayer instanceof Computer)
        System.out.println("Sorry! The Bot " + currentPlayer.getPlayerNum() + " got the better of you, and guessed the number: [" + num + "] and won! Perhaps try again!");
    else
        System.out.println("GG Player " + currentPlayer.getPlayerNum() + "you guessed the Number [" + num + "] right in just " + currentPlayer.getNumTries() + " tries!");
}

public void printLoser() {
    System.out.println("Too Sad! You didn't guess within " + MAX_Tries + " tries! Try again!");
}

public void printWrong() {
    String word = "too high";
    if ((Integer.compare(currentPlayer.getLastGuess(), num)) == -1)
        word = "too low";
    System.out.println("Nope! " + word + "!");
}

public void printTriesLeft() {
    System.out.println(MAX_Tries - currentPlayer.getLastGuess() + " tries left!");
}

public void getNumPlayers() {
    System.out.print("Enter number of Persons playing => ");
    while (!input.hasNextInt()) {
        input.nextLine();
        System.out.println("Invalid input! It must be a number!");
        System.out.print("Enter the number of Players => ");
    }
    numPlayers = input.nextInt();
    System.out.print("Enter number of Bots! =>");
    while (!input.hasNextInt()) {
        input.nextLine();
        System.out.println("Invalid input! It must be a number!");
        System.out.print("Enter number of Bots! =>");
    }
    numBots = input.nextInt();
    resetPlayers();
}
}

Participants class: 参加班:

package fourfive;
import java.util.LinkedList;

public abstract class Participants extends Run {
protected int numTries;
protected int playerNum;
protected LinkedList<Integer> guesses;
abstract void guess();
public int getLastGuess(){
    return guesses.peek();
}
public int getPlayerNum(){
    return playerNum;
}
public int getNumTries(){
    return guesses.size();
}
}

Now the Human class: (basically the human player) 现在是人类课:(基本上是人类玩家)

package fourfive;
import java.util.LinkedList;
import java.util.Scanner;
public class Human extends Participants {
protected static Scanner input = new Scanner(System.in);
public Human(int playerNum) {
    numTries = 0;
    this.playerNum = playerNum;
    guesses = new LinkedList<Integer>();
}
public void guess(){
    System.out.print("Player " + playerNum + "guess =>");
    while(!input.hasNextInt()){
        input.nextLine();
        System.out.println("Invalid input!");
        System.out.print("Player " + playerNum + "guess =>");
    }
    guesses.push(input.nextInt());
}
}

And Last the Computer class: 最后的计算机课:

package fourfive;
import java.util.Random;

public class Computer extends Human {
protected static Random rand = new Random();
protected int maxGuess;

Computer(int playerNum) {
    super(playerNum);
    maxGuess = 1000;
}
Computer(int playerNum, int topNum){
    super(playerNum);
    maxGuess = topNum;
}

@Override
public void guess() {
    int guess = rand.nextInt(maxGuess);
    System.out.println("Bot " + playerNum + " turn *" + guess + "*");
    guesses.push(guess);
}

public int getMaxGuess() {
    return maxGuess;
}

public void setMaxGuess(int num) {
    maxGuess = num;
}

}

You would initialize the Array with a fixed size, eg 4 and resize if needed. 您将使用固定大小(例如4初始化Array,并在需要时调整大小。 For this, you need an extra attribute to store the fill level of the array. 为此,您需要一个额外的属性来存储数组的填充水平。

int[] guesses = new int[4];
int guessFilling = 0;
[...]
@Override
public void guess() {
    int guess = rand.nextInt(maxGuess);
    System.out.println("Bot " + playerNum + " turn *" + guess + "*");
    if (guessFilling == guesses.length) {
        resizeGuesses();
    }
    guesses[guessFilling++] = guess;
}

private void resizeGuesses() {
    int[] newGuesses = new int[guesses.length > 0 ? 2 * guesses.length : 1];
    System.arraycopy(guesses, 0, newGuesses, 0, guesses.length);
    guesses = newGuesses;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM