2015-12-01 2 views
-4

У меня проблемы с этим, и я был бы очень признателен за помощь. Я все еще «noobie», когда речь заходит о java, поэтому, пожалуйста, поймите, что я, вероятно, буду иметь глупые ошибки. В любом случае, я пытаюсь создать двухпользовательскую Java-игру, и я продолжаю получать ошибки, которые я не понимаю. У меня есть три отдельных класса. Это мой основной классJava 2 игровой пустяк

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

Это мой игрок класс

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 

} 
} 

Это мои вопросы класса

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]; 

} 

} 

Если есть любая помощь вы, ребята, может предложить, я бы очень признателен , Я просто не могу понять, почему я продолжаю получать эти ошибки, которые мешают ему работать. Пожалуйста и спасибо.

эти ошибки, которые я получаю, я не знаю, если это то, что вы имеете в виду, я узнал, что у меня было раньше было от чего-то еще

Exception в потоке «главный» java.lang.Error: Нерешенные проблемы компиляции: метод intQuestion (вопросы []) не определено для типа Assignment3 qArray не может быть решена с переменной qArray не может быть решена с переменной

at Assignment3.main(Assignment3.java:42) 
+0

Какая ошибка вы получаете? Можете ли вы опубликовать трассировку стека? – ryekayo

+1

Можете ли вы правильно откомментировать свой код? – khelwood

+0

Где ошибка? – hbelmiro

ответ

0

Ваш метод назван initQuestion, но вы вызывают intQuestion.

О, и вы используете qArray за пределами initQuestion, это единственное место, где оно определено.

+0

Я просто любопытный о нисходящем - есть ли что-то, что я мог бы улучшить в своем ответе? – stuXnet

+0

Я не сделал это, idk, почему другие сделали это, это немного помогло, спасибо, я все еще работаю над попыткой заставить его работать – user211212

Смежные вопросы