Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I can't seem to work out these object arrays, I'm attempting to create a list of player names with values stored, each with an integer and some multiple strings for each.
This is what i'm working on so far, were object arrays the correct storage package for this? The error was in line 237 when I try to add a player in the class addPlayer: player[userCount].setName(name);
The error is:- Exception in thread "main" index out of bounds.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class PlayerKarma {
static Scanner input = new Scanner(System.in);
static private String[] username = {"name1","name2","test","moretesting","fervor","stackoverflow","imported","quaternion","jetstream"};
static private int[] karma = {1000,800,800,5,15,-4,-403,54,11,210};
static private boolean exit = false;
static private int maxKarmaChange = 10; //How much a players karma can change per day.
static Player[] userArray = new Player[10000];
//ArrayList<Player> userArray = new ArrayList<Player>();
static private int userCount = 0;
public static void main(String[] args)
{
while (!exit)
{
System.out.println("");
System.out.println("Select an option");
System.out.println("1: Display a player's karma");
System.out.println("3: Display all player names and karma");
System.out.println("5: Add player");
String command = input.nextLine();
switch(command)
{
//Display player's karma.
case "1": {
System.out.println("Enter a player's name: ");
String inputString = input.nextLine();
int playerindex = findPlayer(inputString);
if (playerindex == -1)
{
System.out.println("Player doesn't exist");
}
else //If the player exists.
{
System.out.println(userArray[playerindex].getName() + " has a karma of " + karma[userArray[playerindex].getKarma()]);
break;
}
break;}
//Display all player names and karma.
case "3": {getAllPlayerKarma(); sleep(1500); break;}
//Add player.
case "5": {
System.out.println("Enter a player's name:");
String inputString = input.nextLine();
if (userCount > 0) //If there is at least one user in the database.
{
int playerindex = findPlayer(inputString);
if (playerindex == -1)
{
addPlayer(inputString,0);
}
else //If the player exists.
{
break;
}
}
else //If there's no users.
{
addPlayer(inputString,0);
}
break;}
}
}
}
//Class creation for players.
public class Player
{
public String name;
public int karma;
//public String[] notes = new String[5];
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getKarma() {
return karma;
}
public void setKarma(int karma) {
this.karma = karma;
}
}
private static void getAllPlayerKarma() {
System.out.println("");
for (int k = 0; k < userCount; k++)
{
System.out.println(userArray[k].getName() + " has a karma of " + userArray[k].getKarma());
}
}
private static void setAllPlayerKarma(String karmaValue) {
System.out.println("");
for (int k = 0; k < username.length; k++)
{
int parseKarma = Integer.parseInt(karmaValue);
karma[k] = parseKarma;
}
System.out.println("All karma has been set to " + karmaValue);
}
private static void addPlayer(String name, int karma) {
//Adds a new user
Player[] player = new Player[userCount];
//Player[userCount] = new Player(userCount);
player[userCount].setName(name);
player[userCount].setKarma(karma);
//userArray[userCount].setName(name);
//userArray[userCount].setKarma(karma);
userCount++;
}
//Returns the index of the player in the database.
private static int findPlayer(String playerName) {
int playerIndex = -1;
for (int j = 0; j < userCount; j++)
{
System.out.println("Testing name: " + playerName + " against " + userArray[j].getName());
if (playerName.equals(userArray[j].getName())) {
playerIndex = j;
System.out.println("Match");
break;
}
else
{
//System.out.println("No match");
}
}
return playerIndex;
}
private static void sleep(int sleep) {
try {Thread.sleep(sleep);}
catch(InterruptedException ex) {
Thread.currentThread().interrupt();}
}
}
There are three problems with this code:
Player[] player = new Player[userCount];
player[userCount].setName(name);
Firstly, you're creating a new array each time - I suspect you want to populate userArray instead.
Secondly, you're creating an array of size userCount and then trying to use the element with index userCount - that's never going to work. Array indexes are 0-based, so an element with length 3 has valid indexes 0, 1 and 2 for example.
Thirdly, you're not creating a new Player object - so every element in the array is null. Even if you fixed the index, player[x].setKarma(karma) would throw a NullPointerException.
I suspect you want the method to look like this:
private static void addPlayer(String name, int karma) {
Player player = new Player();
player.setKarma(karma);
player.setName(name);
userArray[userCount] = player;
userCount++;
}
That's now fine, until the user count exceeds the length of your array. At that point, you should start looking at List<E> (and ArrayList<E> in particular).
You initialize usercount with the value of 0 and therefore create an array with the size of 0 Player[] player = new Player[userCount];, this leads to your error.
Related
I am new to Java and this is a very basic question.
However I struggle to find a solution, so hopefully someone could give me some pointers.
I am trying to fill values into an array "addedPlayer".
However, every time I run the AddPlayer() method it is initialiezed to zero again.
How can I structure this in a better way?
public class DemoApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
public void AddPlayer() {
int[] addedPlayer;
addedPlayer = new int[500];
System.out.println(" *** Add new player *** ");
System.out.println("Name:");
String name = System.console().readLine();
System.out.println("Age:");
int age = Integer.parseInt(System.console().readLine());
System.out.println("JNUM:");
int jnum = Integer.parseInt(System.console().readLine());
player p = new player();
p.SetAge(age);
p.SetName(name);
p.SetJnum(jnum);
System.out.println(addedPlayer[0]);
for (int j = 0; j < addedPlayer.length; j++) {
if (addedPlayer[j] != 0) {
} else {
addedPlayer[j] = p.GetAge();
System.out.println(addedPlayer[j]);
System.out.println(j);
break;
}
}
}
public void EditPlayer() {
//empty
}
public void ListPlayer() {
//empty
}
#Override
public void run(String... args) throws Exception {
while (true) {
System.out.println(" *** MENY *** ");
System.out.println(" 1. Add player ");
System.out.println(" 2. Edit player ");//ÖKurs
System.out.println(" 3. List player ");
System.out.println(" 100. Exit ");
System.out.println("Ange val");
int sel = Integer.parseInt(System.console().readLine());
if (sel == 100) break;
if (sel == 1) AddPlayer();
if (sel == 2) EditPlayer();
if (sel == 3) AddPlayer();
}
}
}
Each time you run AddPlayer(), it creates a new player from scratch. If you want to keep your modifications to a bare minimum, you must put it outside of the method and make it a property for your class like List<int[]> addedPlayers = new ArrayList<int[]>(); and you can add this line AddPlayer to add it in a list addedPlayers.add(addedPlayer). Otherwise, if you want a more cleaner code, you should add more classes than only one main class. To improve your code, you can see #g.momo's answer.
int[] addedPlayer; addedPlayer = new int[500];
It gets overridden because you are creating an new local var addedPlayer, and then setting all values to 0 (addedPlayer = new int[500];) I'm assuming you would want addedPlayer to be global, so don't define it locally and set it to 0.
Also, should addedPlayer be a player[] or just a player rather than an int[]? Plus, you didn't close the function in the code you gave us, so is there more missing or did you just not close it?
Your code and your expectations are completely differents.
Read this and tell us if you understand. It is the way I would have written if I were you . But it is NOT TESTED:
public class AddPlayer { // you create a class
player[] addedPlayer; // array of players
int index;
public AddPlayer() { // constructor of the class
addedPlayer = new player[500]; // max 500 players
index = 0;
}
public void addPlayer(player p) {
if(index < 500) {
addedPlayer[index] = p; // add at index,
index = index + 1; // then increment index for the next added player
}
}
public static void main(String... args) {
AddPlayer addPlayers = new AddPlayer();
int i = 0;
while(i < 5) { // will run 5 times, so only 5 players will be added. Change to stop when you will need
// here your read console inputs
System.out.println(" *** Add new player *** "+ (i+1));
System.out.println("Name:");
String name = System.console().readLine();
System.out.println("Age:");
int age = Integer.parseInt(System.console().readLine());
System.out.println("JNUM:");
int jnum = Integer.parseInt(System.console().readLine());
// initialize the player
player p = new player();
p.SetAge(age);
p.SetName(name);
p.SetJnum(jnum);
addPlayers.addPlayer(p); // add in the array
i++;
}
}
}
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I am building the object with the classical Nim game, and there are some methods dealing with the player data. I bumped into this problem when testing my code, and couldn't figure it out.
This problem appeared when I add a player in an array, removing it after. Then, adding a player again. It showed: Index 1 out of bounds for length 1. What I've tried is to filter the null position when I remove the player data.
Any help is highly appreciated. And thank you all for the patience and time solving it!
The code is a little bit longer, but related.
Here is the related code from class Nimsys, main method.
public static void addPlayer(String [] name) {
if (name != null && name.length == 3) {
for (int i = 0; i < NimPlayer.getCounter(); i++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName();
if (userCheck.contains(name[0])) {
System.out.println("The player already exists.\n");// Test if player has been created
return;
}
}
NimPlayer.createPlayer(name[0], name[1], name[2]);
System.out.println("The player has been created.");
return;
}
System.out.println("Not Valid! Please enter again!");
}
public static void searchAndRemovePlayer(String user) {
NimPlayer [] playerList = NimPlayer.getPlayer();
for (int i = 0; i < playerList.length; i++) {
String userName =playerList[i].getUserName().trim();
if (userName.equals(user)) {
playerList[i] = null;
System.out.println("Remove successfully!");
NimPlayer.setPlayerList(playerList);
return;
}
}
System.out.println("The player does not exist.\n");
}
public static void main(String[] args) {
System.out.println("Welcome to Nim\n");
//Scanner in = new Scanner(System.in);
while (true) {
System.out.print('$');
String commandin = in.next();
if (commandin.equals("addplayer")) {
String inputName = in.nextLine();
String[] name = splitName(inputName);
addPlayer(name);
}
if (commandin.equals("removeplayer")) {
String user = in.nextLine().trim();
if (user.equals("")) {
System.out.println("Are you sure you want to remove all players? (y/n)");
commandin = in.next();
if (commandin.equals("y")) {
NimPlayer [] playerList = NimPlayer.getPlayer();
for (int i = 0; i < playerList.length; i++) {
playerList[i] = null;
NimPlayer.setPlayerList(playerList);
}
System.out.println("Remove all the players\n");
Arrays.stream(NimPlayer.getPlayer()).filter(Objects::nonNull).toArray();
}
}
if (!user.equals("")) {
searchAndRemovePlayer(user);
Arrays.stream(NimPlayer.getPlayer()).filter(Objects::nonNull).toArray();
}
}
Here is part of my NimPlayer class:
public class NimPlayer {
private String userName;
private String familyName;
private String givenName;
private int score;
private int gamePlayed;
private static int counter;
private static final int SIZE = 10;
private static NimPlayer[] playerList = new NimPlayer[SIZE]; // set an array here
//define NimPlayer data type
public NimPlayer(String userName, String surName, String givenName) {
this.userName = userName;
this.familyName = surName;
this.givenName = givenName;
}
// create new data using NimPlayer data type
public static void createPlayer(String userName, String familyName, String givenName) {
if (counter < SIZE) {
playerList[counter++] = new NimPlayer(userName, familyName, givenName);
} else {
System.out.println("Cannot add more players.");
}
}
public static int getCounter() {
return counter;
}
public static NimPlayer [] getPlayer() {
NimPlayer[] nimPlayers = Arrays.stream(playerList).filter(Objects::nonNull).toArray(NimPlayer[]::new);
counter = nimPlayers.length; //update the counter
return nimPlayers;
}
public static void setPlayerList(NimPlayer [] newplayerList) {
NimPlayer.playerList = newplayerList;
1. Replace
if (commandin.equals("removeplayer")) {
String user = in.nextLine().trim();
if (user.equals("")) {
System.out.println("Are you sure you want to remove all players? (y/n)");
commandin = in.next();
if (commandin.equals("y")) {
NimPlayer [] playerList = NimPlayer.getPlayer();
for (int i = 0; i < playerList.length; i++) {
playerList[i] = null;
NimPlayer.setPlayerList(playerList);
}
System.out.println("Remove all the players\n");
Arrays.stream(NimPlayer.getPlayer()).filter(Objects::nonNull).toArray();
}
}
if (!user.equals("")) {
searchAndRemovePlayer(user);
Arrays.stream(NimPlayer.getPlayer()).filter(Objects::nonNull).toArray();
}
}
with
if (commandin.equals("removeplayer")) {
String user = in.nextLine().trim();
if (user.isEmpty()) {
System.out.println("Are you sure you want to remove all players? (y/n)");
commandin = in.nextLine();
if (commandin.equalsIgnoreCase("y")) {
NimPlayer [] playerList = NimPlayer.getPlayer();
for (int i = 0; i < playerList.length; i++) {
NimPlayer.removePlayer(playerList[i]);
}
System.out.println("Removed all the players\n");
}
} else {
searchAndRemovePlayer(user);
}
}
2. Change the following methods as given below:
public static void searchAndRemovePlayer(String user) {
NimPlayer[] playerList = NimPlayer.getPlayerList();
for (int i = 0; i < playerList.length; i++) {
String userName = playerList[i].getUserName().trim();
if (userName.equals(user)) {
NimPlayer.removePlayer(playerList[i]);
System.out.println("The player, " + user + " removed successfully!");
return;
}
}
System.out.println("The player, " + user + " does not exist.\n");
}
public static NimPlayer [] getPlayer() {
return Arrays.stream(playerList).filter(Objects::nonNull).toArray(NimPlayer[]::new);
}
2. Instead of exposing the playerList to be set from outside, you should remove its public setter and create public static void removePlayer similar to public static void createPlayer as follows:
public static void removePlayer(NimPlayer player) {
int i;
for (i = 0; i < playerList.length; i++) {
if (playerList[i] != null && playerList[i].getUserName().equals(player.getUserName())) {
break;
}
}
for (int j = i; j < playerList.length - 1; j++) {
playerList[j] = playerList[j + 1];
}
counter--;
}
Important note: Never put setting operation within getter, the way you have done in your method, getPlayer().
You need to use Iterator and call remove() on iterator instead of assigning to null.
Duplicate from: Removing items from a list
You shouldn't do a "playerList[i] = null;" for removing a player. Use an ArrayList instead and use the ArrayList's .remove method to remove a player. don't keep track of counter variables.
So I'm trying to create a small hangman mini-game. Unfortunately, I keep receiving the same error. I've attempted to re-do the game twice, but still can't seem to get it right. I'm sure it is simply some logic error or something.
I'm still relatively new to Java, so any help would be appreciated.
I've split the program into three classes. One for the Hangman object, one for the array containing said objects, and one for using the array of those objects. The three parts below are a snippet from the game.
Class 1: Hangman
package hangman2;
import java.util.*;
import java.io.*;
public class Hangman {
private ArrayList<String> words = new ArrayList<>();
private int diff;
public Hangman(String fileName, int difficulty) {
diff = difficulty;
//easy = 0; medium = 1; hard = 2
try {
Scanner scanFile = new Scanner(new File(fileName));
while(scanFile.hasNext()) {
String line = scanFile.nextLine();
Scanner scanLine = new Scanner(line);
String tempWord = scanLine.next();
words.add(tempWord);
}
}
catch (FileNotFoundException e) {
System.out.println("File not found\n" + e);
}
}
//Gets
public ArrayList<String> getWords() { return words; }
public int getDifficulty() { return diff; }
//Sets
public void addWord(String word) { words.add(word); }
}
Class 2: HangmanArray
package hangman2;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class HangmanArray {
private Hangman easyHangman;
private Hangman mediumHangman;
private Hangman hardHangman;
public HangmanArray() {
easyHangman = new Hangman("easy.txt", 0);
mediumHangman = new Hangman("medium.txt", 1);
hardHangman = new Hangman("hard.txt", 2);
}
public String getRandomWord() {
Hangman workingHangman = chooseDifficulty();
int max = workingHangman.getWords().size();
int randIndex = (int) (Math.random() * max);
return workingHangman.getWords().get(randIndex);
}
private Hangman chooseDifficulty() {
int chosenDifficulty = Integer.parseInt(JOptionPane.showInputDialog("Choose difficulty level\n"
+ "1: Novice\n2: Intermediate\n3: Expert"));
Hangman retHangman = null;
switch(chosenDifficulty) {
case 1: retHangman = easyHangman; break;
case 2: retHangman = mediumHangman; break;
case 3: retHangman = mediumHangman; break;
}
if (retHangman == null) {
System.out.println("Chosen difficulty not within range of [1;3]\nexiting");
System.exit(0);
}
return retHangman;
}
}
Class 3: HangmanUI
package hangman2;
public class HangmanUI {
public static void main(String[] args) {
HangmanArray hangmanArray = new HangmanArray();
System.out.println(hangmanArray.getRandomWord());
}
}
The error appears to be coming from line 25 of HangmanArray when difficulty 2 or 3 is selected:
return workingHangman.getWords().get(randIndex);
Any help is appreciated.
You should check whether max is 0 and, if so, return null or an empty string, then handle this special case.
I used Random.nextInt() instead of int randIndex = (int) (Math.random() * max);
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All bound possible int values are produced with (approximately) equal probability
Keep in mind that the index of last element is size()-1
public String getRandomWord() {
Hangman workingHangman = chooseDifficulty();
int max = workingHangman.getWords().size();
if (max == 0) {
return "";
}
int randIndex = new Random().nextInt(max); // returns an integer between 0 and max-1
return workingHangman.getWords().get(randIndex);
}
You should also use try-with-resources to ensure that resources you're using are closed once you finisched with them.
public Hangman(String fileName, int difficulty) {
diff = difficulty;
//easy = 0; medium = 1; hard = 2
try (Scanner scanFile = new Scanner(new File(fileName))) {
while(scanFile.hasNext()) {
String line = scanFile.nextLine();
Scanner scanLine = new Scanner(line);
String tempWord = scanLine.next();
words.add(tempWord);
}
}
catch (FileNotFoundException e) {
System.out.println("File not found\n" + e);
}
}
Lastly I suggest to use the debugger in order to know what you're putting into every Hangman.
My assignment is I have to manage a soccer league.There is a soccer league (text file) that I have to import into the program.Each line of the imported file displays the outcome of a single game:the name of two teams together with the scores like
Peter 4 Tiger 3
Sky 2 Peter 0
Tiger 1 Sky 2
I have to write the program to read this text file and displays the output of team records like
Team Wins Losses
Peter 1 1
Tiger 0 2
Sky 2 0
I don't understand how to read through the lines and calculate the wins and losses associated with each team/String.
import java.util.*;
import java.io.*;
public class SoccerLeagueStandings
{
public static void main(String[] args) throws IOException
{
File inFile = new File("LeagueScore.txt");
if(! inFile.exists())
{
System.out.println("Error could not open the file");
return;
}
String Panthers="Panthers";
String Tigers = "Tigers";
String Sky = "Sky";
Scanner input = new Scanner (inFile);
int PW=0;
int PL=0;
int TW =0;
int TL = 0;
int SW=0;
int SL=0;
while (input.hasNextLine())
{
String firstTeam=input.next();
input.nextInt();
int firstScore=input.nextInt();
String secondTeam=input.next();
input.nextInt();
int secondScore = input.nextInt();
if (firstScore>secondScore)
{
if (firstTeam.equals(Panthers))
{
PW+=1;
}
if (firstTeam.equals(Tigers))
{
TW+=1;
}
if (firstTeam.equals(Sky))
{
SW+=1;
}
}
}
}
}
The main challenge in this problem is to keep track of the wins and losses of each team.
So i suggest to create a class called Team which holds: name, winsCount, lossCount. This class represents a single team along with its wins and loss count.
Create an arrayList of Team and fill it using the file content.
So your algorithm would be as the following:
Parse the file line by line using Scanner.
Split each line by space in order to get the teams and their scores.
Compare the scores of the teams.
Add the winner team to the ArrayList OR increment its winsCount if already exist.
Do the same for the loser team.
Below is a non-tested sample code:
Following is the Team class:
public class Team {
private String name;
private int winsCount;
private int lossCount;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWinsCount() {
return winsCount;
}
public void setWinsCount(int winsCount) {
this.winsCount = winsCount;
}
public int getLossCount() {
return lossCount;
}
public void setLossCount(int lossCount) {
this.lossCount = lossCount;
}
}
Below is how to fill the arraylist from the input file:
private void generateWinsLossesFromInput(String filePath)
{
Scanner input = new Scanner(filePath);
List<Team> teams = new ArrayList<Team>();
while(input.hasNext())
{
String match = input.next();
// Split the line and get teams and their scores.
String[] splittedMatch = match.split("\\s+");
String firstTeam = splittedMatch[0];
int firstTeamScore = Integer.parseInt(splittedMatch[1]);
String secondTeam = splittedMatch[2];
int secondTeamScore = Integer.parseInt(splittedMatch[3]);
if(firstTeamScore > secondTeamScore)
{
addWinner(firstTeam, teams);
addLoser(secondTeam, teams);
}
else
{
if(secondTeamScore > firstTeamScore)
{
addWinner(secondTeam,teams);
addLoser(firstTeam, teams);
}
}
}
}
private void addWinner(String team, List<Team> teams)
{
int index = 0;
for(index = 0; index<teams.size(); index++)
{
Team t = teams.get(index);
if(t.getName().equalsIgnoreCase(team))
{
// Team already exists, so just increment its winsCount
t.setWinsCount(t.getWinsCount() + 1);
break;
}
}
if(index == teams.size())
{
// team not found, So add it as new team to the list.
Team t = new Team();
t.setName(team);
t.setWinsCount(1);
t.setLossCount(0);
teams.add(t);
}
}
private void addLoser(String team, List<Team> teams)
{
int index = 0;
for(index = 0; index<teams.size(); index++)
{
Team t = teams.get(index);
if(t.getName().equalsIgnoreCase(team))
{
// Team already exists, so just increment its loss count.
t.setLossCount(t.getLossCount() + 1);
break;
}
}
if(index == teams.size())
{
// team not found , then add new team to the list
Team t = new Team();
t.setName(team);
t.setWinsCount(0);
t.setLossCount(1);
teams.add(t);
}
}
At the end, you would be able to iterate over the array list and print out each team along with its Wins and loss counts.
I am having some trouble with this, and I would greatly appreciate some help. I am still a "noobie" when it comes to java so please understand that I probably will have stupid mistakes. Anyways, I am trying to make a two player java game and I keep getting errors that I do not understand. I have three separate classes. This is my main class
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Assignment3
{
public static void main(String args[]) throws IOException
{
// Constants
final int NUM_QUESTIONS = 10;
final int NUM_PLAYERS = 2;
// Variables
int playerTurn = 1; // The current player
int questionNum; // The current question number
int playerAnswer; // The player's chosen answer
int player1points = 0; // Player 1's points
int player2points = 0; // Player 2's points
// Create an array of Player objects for player #1 and player #2.
player[] players = new player[NUM_PLAYERS];
for (int i = 0; i < NUM_PLAYERS; i++)
{
players[i] = new player(i+1);
}
// Create an array to hold Question objects.
questions[] questions = new questions [NUM_QUESTIONS];
// Initialize the array with data.
intQuestion(questions);
// Play the game.
for (int i = 0; i < NUM_QUESTIONS; i++)
{
// Display the question.
Assignment3.displayQuestion(qArray[i], playerTurn);
// Get the player's answer.
players[playerTurn - 1].chooseAnswer();
// See if the correct answer was chosen.
if (qArray[i].getCorrectAnswerNumber() == players[playerTurn - 1].getCurrentAnswer())
{
players[playerTurn -1].incrementPoints();
}
// See if the the player chose the wrong answer.
// do nothing
// Switch players for the next iteration.
if (playerTurn == 1)
playerTurn = 2;
else
playerTurn = 1;
}
// Show the game results.
showGameResults(players);
}
/**
* The initQuestions method uses the contents of the trivia.txt file to
* populate the qArray parameter with Question objects.
*/
public static void initQuestions(questions qArray[]) throws IOException
{
// Open the trivia.txt file.
File file = new File("trivia.txt");
Scanner inputFile = new Scanner(file);
// Populate the qArray with data from the file.
for (int i = 0; i < qArray.length; i++)
{
// Create a Question object in the array.
qArray[i] = new questions();
// Get the question text from the file.
qArray[i].setQuestion(inputFile.nextLine());
// Get the possible answers.
for (int j = 1; j <= 4; j++)
{
qArray[i].setPossibleAnswer(inputFile.nextLine(), j);
}
// Get the correct answer.
qArray[i].setCorrectAnswerNumber(Integer.parseInt(inputFile.nextLine()));
}
}
public static void displayQuestion(questions q, int playerNum)
{
// Display the player number.
System.out.println("Question for player #" + playerNum);
System.out.println("------------------------");
// Display the question.
System.out.println(q.getQuestionText());
for (int i = 1; i <= 4; i++)
{
System.out.println(i + ". " + q.getPossibleAnswer(i));
}
}
public static void showGameResults(player[] players)
{
// Display the stats.
System.out.println("Game Over!");
System.out.println("---------------------");
System.out.println("Player 1's points: " + players[0].getPoints());
System.out.println("Player 2's points: " + players[1].getPoints());
// Declare the winner.
if (players[0].getPoints() > players[1].getPoints())
System.out.println("Player 1 wins!");
else if (players[1].getPoints() > players[0].getPoints())
System.out.println("Player 2 wins!");
else
System.out.println("It's a TIE!");
}
}
This is my player class
import java.util.Scanner;
public class player
{
private int playerNumber; // The player number
private int points; // Player's points
private int currentAnswer; // Current chosen answer
//Constructor
public player(int playerNum)
{
playerNumber = playerNum;
points = 0;
}
public void chooseAnswer()
{
// Create a Scanner object for keyboard input.
// Get the user's chosen answer.
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter your Answer"); //Asks user for a number
this.currentAnswer = keyboard.nextInt();
}
public int getCurrentAnswer()
{
return this.currentAnswer; //Returns Current Answer
}
public void incrementPoints()
{
this.points++; //Increments the points
}
public int getPoints()
{
return this.points; //Returns the points
}
}
This is my questions class
public class questions
{
// Constant for the number of answers
public final int NUM_ANSWERS = 10;
// The trivia question
private String questionText;
// An array to hold possible answers.
private String possibleAnswers[] = new String[NUM_ANSWERS];
// The number (1, 2, 3, or 4) of the correct answer.
private int correctAnswer;
//Constructor
public questions()
{
// Initialize all fields to "" or 0;
questionText = "";
correctAnswer = 0;
for (int i = 1; i < NUM_ANSWERS; i++)
setPossibleAnswer("", i);
}
public void setQuestion(String question)
{
//Sets the question
this.questionText = question;
}
public void setPossibleAnswer(String text, int num)
{
//Sets possible Answer
this.possibleAnswers[num] = text;
}
public void setCorrectAnswerNumber(int num)
{
//Sets correct Answer
this.correctAnswer = num;
}
public String getQuestionText()
{
//Returns Question Text
return this.questionText;
}
public String getPossibleAnswer(int num)
{
//Returns Possible Amswer
return this.possibleAnswers[num];
}
public int getCorrectAnswerNumber()
{
//Returns Correct Answer
return this.correctAnswer;
}
public String getCorrectAnswer()
{
//Returns Possible Answer
return this.possibleAnswers[this.correctAnswer];
}
}
If there is any help you guys can offer, I would greatly appreciate. I just can't seem to figure out why I keep getting these errors that are stopping it from running. Please and thank you.
these are the errors I get, I don't know if this is what you mean, I found out what I had earlier was from something else
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method intQuestion(questions[]) is undefined for the type Assignment3
qArray cannot be resolved to a variable
qArray cannot be resolved to a variable
at Assignment3.main(Assignment3.java:42)
Your method is named initQuestion, but you are calling intQuestion.
Oh, and you are using qArray outside of initQuestion, the only place where it seems to be defined.