I am beginning to learn Java and am writing a Game of Pig for my introductory CS class. Knowing the details of this game is not necessary to respond to this question.
One of my methods has a loop that repeatedly prompts a user if they type a certain string. This string is "yes/n". For some reason, however, I can't get the loop to run past a single iteration. Sometimes, the program will proceed as a result, or the program will crash and throw a NoSuchElementException
.
turnInfo[0]
and turnInfo[1]
are other variables within this method and represent the values of the rolls. The rolls can be seen in the image showing output (below).
Any and all help would sincerely be appreciated!
Here is the relevant piece of code:
Scanner sc = new Scanner(System.in);
System.out.print("Roll again? Type 'yes' or 'no' and hit <enter>: ");
**String nextRoll = sc.next(); //THIS IS THE PROBLEM LINE: 72**
while ((nextRoll.equals("yes/n")) && (turnInfo[0] != 6) && (turnInfo[1] != 6)); {
turnInfo = diceInfo();
System.out.println("Player rolled " + turnInfo[0] + " and " + turnInfo[1] + ".");
int rollScore = rollScore(turnInfo[0], turnInfo[1]);
turnScore = turnScoreAccumulator(rollScore, turnScore);
//We create an exit out of the loop with the following conditionals.
//If at least one of the dice is six, then the turn score is set to zero.
if ((turnInfo[0] == 6) || (turnInfo[1] == 6)) {
turnScore = 0;
//If both dice turn out to be six, this situation is addressed in the main method.
}
else {
potentialGameScore = potentialGameScore + rollScore;
System.out.println("Player's turn sum is: " + turnScore + " and game sum would be: " + potentialGameScore + ".");
System.out.print("Roll again? Type 'yes' or 'no' and hit <enter>: ");
nextRoll = sc.next();
}
}
Here is the other set of code where the issue arises:
public static void main(String[] args) {
System.out.println("Hello, and welcome to the Game of Pig!\n\n");
int[] humanTurnInfo;
int [] computerTurnInfo;
int humanGameScore = 0;
int computerGameScore = 0;
boolean gameVictory = false;
int roundCounter = 0;
while (gameVictory == false) {
System.out.println("Player sum: " + humanGameScore + ", " + "Computer sum: " + computerGameScore + ".");
roundCounter += 1;
System.out.println("We now begin round " + roundCounter + ":");
**humanTurnInfo = userInteraction(humanGameScore); //THIS IS ALSO A PROBLEM LINE: 185**
humanGameScore = humanTurnInfo[2];
if ((humanTurnInfo[0] == 6) && (humanTurnInfo[1] == 6)) {
humanGameScore = 0;
}
if (humanGameScore >= 100) {
System.out.println("Congratulations, you have won the game!");
gameVictory = true;
}
else {
computerTurnInfo = computerPlay(computerGameScore);
if (computerTurnInfo[0] == 6 && computerTurnInfo[1] == 6) {
computerGameScore = 0;
}
if (computerGameScore >= 100) {
System.out.println("The computer has won the game. Better luck next time!");
gameVictory = true;
}
}
}