I am designing a program for my class that is supposed to simulate a lottery game. I am supposed to design a method that generates random lottery numbers, a method that asks and stores the user for their number choices, a method that compares the arrays to find how many numbers are the same, and then I am supposed to call them all back up to the main method, and create my output statement that contains some if statements that determine which prize is awarded for the particular amount of matches.
Here is what I have thus far
import java.util.*;
public class LotteryGame {
/**
The main method is the program's starting point
*/
public static void main(String[] args){
int NUM_DIGITS = 5;
int[] userDigits = new int[5];
int[] lotteryNumbers = new int[5];
int sameNum;
generateNumbers(lotteryNumbers);
getUserData(userDigits);
compareArrays();
System.out.println("Lottery numbers: " + lotteryNumbers[0] + " " +
lotteryNumbers[1] + " " + lotteryNumbers[2] + " " + lotteryNumbers[3] +
" " + lotteryNumbers[4] + " ");
System.out.println("Player numbers: " + userDigits[0] + " " + userDigits[1] + " " + userDigits[2] + " " + userDigits[3] + " " + userDigits[4] + " ");
System.out.println("Number of matching digits: " + sameNum);
if (sameNum == 5){
System.out.println("GRAND PRIZE WINNER - $5 MILLION!!");
}
if (sameNum == 4){
System.out.println("SUPER PRIZE WINNER - $500,000!!");
}
if (sameNum == 3){
System.out.println("GOOD PRIZE WINNER - $5,000!!");
}
if (sameNum == 2){
System.out.println("NICE PRIZE WINNER - $500!!");
}
if (sameNum == 1){
System.out.println("WINNER - $5!!");
}
if (sameNum ==0){
System.out.println("No matching numbers - better luck next time");
}
}
public static int generateNumbers(int [] lotteryNumbers){
Random randNum = new Random();
lotteryNumbers[0] = randNum.nextInt(10);
lotteryNumbers[1] = randNum.nextInt(10);
lotteryNumbers[2] = randNum.nextInt(10);
lotteryNumbers[3] = randNum.nextInt(10);
lotteryNumbers[4] = randNum.nextInt(10);
return lotteryNumbers[4];
}
public static int getUserData (int [] userDigits){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter digit 1: ");
userDigits[0] = keyboard.nextInt();
System.out.print("Enter digit 2: ");
userDigits[1] = keyboard.nextInt();
System.out.print("Enter digit 3: ");
userDigits[2] = keyboard.nextInt();
System.out.print("Enter digit 4: ");
userDigits[3] = keyboard.nextInt();
System.out.print("Enter digit 5: ");
userDigits[4] = keyboard.nextInt();
return userDigits[4];
}
public static int compareArrays (int [] userDigits,
int [] lotteryNumbers){
int sameNum = 0;
for (int i = 0; i < 5; i++){
for (int x = 0; x < 5; x++){
if (lotteryNumbers[i] == userDigits[x]){
sameNum++;
}
return sameNum;
}
return sameNum;
}
return sameNum;
}
}
I am very new to arrays (and Java at that) so my problems are in my return/call statements. Please excuse my spacey coding style and any blatant mistakes that I have made. Any tips,advice, solutions, or if you notice anything wrong with what I have please let me know. Thanks!
Keep in mind that randNum.nextInt(10) will give you lottery numbers that range from 0 to 9. You can use a for loop to assign the random numbers to the lotteryNumbers array easier. Also, you should make sure that the random lottery numbers don't repeat.
In your compareArrays function, just put one return sameNum call after the outermost for loop, otherwise it won't update with the correct number of matching numbers. You need to give compareArrays() the correct parameters (userDigits and lotteryNumbers) and set sameNum equal to this result.
Several points you might find useful:
You might want to use NUM_DIGITS for the initiation of the arrays since that's the whole point of having named constant:
int[] userDigits = new int[NUM_DIGITS];
int[] lotteryNumbers = new int[NUM_DIGITS];
You can use Arrays.toString() to output arrays, e.g.:
System.out.println(Arrays.toString(lotteryNumbers));
Instead of multiple ifs use switch, plus do not repeat the whole print statement, only assign the part that differs:
String prize = "";
switch (sameNum) {
case 5: prize = "GRAND PRIZE WINNER - $5 MILLION!!";
break;
case 4: prize = "SUPER PRIZE WINNER - $500,000!!";
break;
case 3: prize = "GOOD PRIZE WINNER - $5,000!!";
break;
case 2: prize = "NICE PRIZE WINNER - $500!!";
break;
case 1: prize = "WINNER - $5!!";
break;
case 0: prize = "No matching numbers - better luck next time";
break;
default: prize = "Something weird happened";
}
System.out.println(prize);
I've updated your code with the changes you'll need.
Added NUM_DIGITS to your initializer
Closed your Scanner
Removed the early returns in your comparison method
Assigned the return value of the comparison method to sameNum
Set the return value of the generation and get methods to void
The other suggestions might be something you want to incorporate (such as the switch/case).
import java.util.Random;
import java.util.Scanner;
public class App {
public static void main(String[] args) {
int NUM_DIGITS = 5;
int[] userDigits = new int[NUM_DIGITS];
int[] lotteryNumbers = new int[NUM_DIGITS];
int sameNum;
generateNumbers(lotteryNumbers);
getUserData(userDigits);
sameNum = compareArrays(lotteryNumbers, userDigits);
System.out.println("Lottery numbers: " + lotteryNumbers[0] + " "
+ lotteryNumbers[1] + " " + lotteryNumbers[2] + " "
+ lotteryNumbers[3] + " " + lotteryNumbers[4] + " ");
System.out.println("Player numbers: " + userDigits[0] + " "
+ userDigits[1] + " " + userDigits[2] + " " + userDigits[3]
+ " " + userDigits[4] + " ");
System.out.println("Number of matching digits: " + sameNum);
if (sameNum == 5) {
System.out.println("GRAND PRIZE WINNER - $5 MILLION!!");
}
if (sameNum == 4) {
System.out.println("SUPER PRIZE WINNER - $500,000!!");
}
if (sameNum == 3) {
System.out.println("GOOD PRIZE WINNER - $5,000!!");
}
if (sameNum == 2) {
System.out.println("NICE PRIZE WINNER - $500!!");
}
if (sameNum == 1) {
System.out.println("WINNER - $5!!");
}
if (sameNum == 0) {
System.out.println("No matching numbers - better luck next time");
}
}
public static void generateNumbers(int[] lotteryNumbers) {
Random randNum = new Random();
lotteryNumbers[0] = randNum.nextInt(10);
lotteryNumbers[1] = randNum.nextInt(10);
lotteryNumbers[2] = randNum.nextInt(10);
lotteryNumbers[3] = randNum.nextInt(10);
lotteryNumbers[4] = randNum.nextInt(10);
return lotteryNumbers[4];
}
public static void getUserData(int[] userDigits) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter digit 1: ");
userDigits[0] = keyboard.nextInt();
System.out.print("Enter digit 2: ");
userDigits[1] = keyboard.nextInt();
System.out.print("Enter digit 3: ");
userDigits[2] = keyboard.nextInt();
System.out.print("Enter digit 4: ");
userDigits[3] = keyboard.nextInt();
System.out.print("Enter digit 5: ");
userDigits[4] = keyboard.nextInt();
keyboard.close();
return userDigits[4];
}
public static int compareArrays(int[] userDigits, int[] lotteryNumbers) {
int sameNum = 0;
for (int i = 0; i < 5; i++) {
for (int x = 0; x < 5; x++) {
if (lotteryNumbers[i] == userDigits[x]) {
sameNum++;
}
}
}
return sameNum;
}
}
Related
I have a math quiz game I am making and I am not sure how to loop it, let's say 50 times. It ends after answering only 2 questions. I also want to add lives so after you get three questions wrong it ends the program. How am I able to do this?
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int Number1 = (int)(20 * Math.random()) + 1;
int Number2 = (int)(20 * Math.random()) + 1;
int correct = 0;
System.out.print(Number1 + " + " + Number2 + " = ");
int GuessRandomNumberAdd = keyboard.nextInt();
if (GuessRandomNumberAdd == Number1 + Number2) {
System.out.println("Correct!");
correct++;
}else {
System.out.println("Wrong!");
}
System.out.print(Number1 + " * " + Number2 + " = ");
int GuessRandomNumberMul = keyboard.nextInt();
if (GuessRandomNumberMul == Number1 * Number2) {
System.out.println("Correct!");
correct++;
}else{
System.out.println("Wrong!");
System.out.println("You got " + correct + " correct answers.");
After the int correct = 0;
add a lives counter.
eg:
int lives =3;
then start a while loop
while(lives > 0){
reduce the lives if a question is incorrect (where you put "wrong!" message)
lives--;
at the end of the while loop (before no of correct answers is printed out)
remember to put the last }
This will keep looping till you lose your lives
A couple things:
-There are multiple java structures which allow you to loop. The main loops out there in any kind of programming language are for loop, while loop, and do-while loop (uncommon)
-You can create lives by defining a variable and checking it in every iteration (an iteration is each "run" through the code of a loop).
Your code after implementing this 2 things would look like this:
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int Number1 = (int)(20 * Math.random()) + 1;
int Number2 = (int)(20 * Math.random()) + 1;
int correct = 0;
int lives = 3;
//The for loop is read as: having i equal 25 and the variable lives, iterate if i is lower than 25 AND lives is higher than 0. After an iteration, add 1 to i;
for (int i=25, lives; i<25 && lives > 0; i++) {
System.out.print(Number1 + " + " + Number2 + " = ");
int GuessRandomNumberAdd = keyboard.nextInt();
if (GuessRandomNumberAdd == Number1 + Number2) {
System.out.println("Correct!");
correct++;
} else {
System.out.println("Wrong!");
lives--;
}
System.out.print(Number1 + " * " + Number2 + " = ");
int GuessRandomNumberMul = keyboard.nextInt();
if (GuessRandomNumberMul == Number1 * Number2) {
System.out.println("Correct!");
correct++;
}else{
System.out.println("Wrong!");
lives--;
} //Forgot this bracket
} //Closes the for loop
System.out.println("You got " + correct + " correct answers.");
See if below example works as you intend. Here I have given the loop count as 5. So there will be 5 "addition" questions and 5 "multiplication" questions.
I'm printing the question number also. So, now the output is more clear.
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int correct = 0;
for (int i = 0; i < 5; i++) {
int Number1 = (int) (20 * Math.random()) + 1;
int Number2 = (int) (20 * Math.random()) + 1;
System.out.println("Question " + (i*2+1));
System.out.print(Number1 + " + " + Number2 + " = ");
int GuessRandomNumberAdd = keyboard.nextInt();
if (GuessRandomNumberAdd == Number1 + Number2) {
System.out.println("Correct!");
correct++;
}
else {
System.out.println("Wrong!");
}
System.out.println();
System.out.println("Question " + (i*2+2));
System.out.print(Number1 + " * " + Number2 + " = ");
int GuessRandomNumberMul = keyboard.nextInt();
if (GuessRandomNumberMul == Number1 * Number2) {
System.out.println("Correct!");
correct++;
}
else {
System.out.println("Wrong!");
}
System.out.println();
}
System.out.println("You got " + correct + " correct answers.");
}
}
This is my code:
import java.util.*;
import java.util.Scanner;
public class Assignment2 {
public static void main(String args[]){
Scanner stdin = new Scanner(System.in);
Random random = new Random();
int ran2 = (random.nextInt(10));
int ran1 = (random.nextInt(10));
int total = ran1 + ran2;
char exit = 'y';
System.out.println("First cards: " + ran1 + ", " + ran2);
System.out.println("Total: " + total);
while(exit != 'n' && total < 21){
System.out.println("Do you want another card? (y/n): ");
exit = stdin.next().charAt(0);
System.out.println("Card: "+ (random.nextInt(10)));
total = total + (random.nextInt(10));
System.out.println("Total: "+ total);
}
}
}
When I enter n, how can I make it so the program exit, instead of printing out the total again?
Check this out:
public class Assignment2 {
public static void main(String args[]){
int next = 0;
Scanner stdin = new Scanner(System.in);
Random random = new Random();
int ran2 = (random.nextInt(10));
int ran1 = (random.nextInt(10));
int total = ran1 + ran2;
char exit = 'y';
System.out.println("First cards: " + ran1 + ", " + ran2);
System.out.println("Total: " + total);
while(exit != 'n' && total < 21){
System.out.println("Do you want another card? (y/n): ");
exit = stdin.next().charAt(0);
next = random.nextInt(10);
System.out.println("Card: "+ next);
total = total + next;
System.out.println("Total: "+ total);
}
if (exit.equals('n'))
system.exit(0);
}
}
Now the program exists after you enter n by calling system.exit(0).
You need to call nextInt just once, so you won't create 2 different random numbers. So I put the first call into a variable next so you could use it as many times as you please without having to call nextInt again.
If you want the program to exit immediately after the user enters n, you will want to put the if statement right after the exit = stdin.next().charAt(0);
If you want to exit the loop, you can break from it. Basically you have to do this(I have written comments to highlight the alterations)-
import java.util.*;
import java.util.Scanner;
public class Assignment2 {
public static void main(String args[]){
Scanner stdin = new Scanner(System.in);
Random random = new Random();
int ran2 = (random.nextInt(10));
int ran1 = (random.nextInt(10));
int total = ran1 + ran2;
char exit = 'y';
System.out.println("First cards: " + ran1 + ", " + ran2);
System.out.println("Total: " + total);
while(exit != 'n' && total < 21){
System.out.println("Do you want another card? (y/n): ");
exit = stdin.next().charAt(0);
//you need to check here if the user entered 'n'. I have used a break opertion
//to break from the loop and print the total outside the loop. But if you want
//to exit the program altogether, just replace break with exit(0) :)
if(total >= 21 or exit == 'y') {
break;
}
//As Idos correctly pointed out that by calling random.nextInt(10) two
//times you have a very big chance of creating two different random numbers.
//So it makes sense to put the first call into a variable nextNumber.
int nextNumber = random.nextInt(10);
total = total + (nextNumber);
//Now we should again check for total. If it is greater than or equal to 21
//I am again breaking from the loop. Feel free to replace break with exit(0).
if(total >= 21) {
break;
}
System.out.println("Total: "+ total);
}
System.out.println("Your total- "+ total);
}
}
I am working on my final project for my intro to java class and i am having a hard time understanding the errors in my project and why it will not run if you could tell me why i would greatly appreciate it
public static void main(String[] args) {
Scanner scanner1;
int dice, dice2;
int pScore, cScore = 0;
int pTotalScore = 0;
int cTotalScore = 0;
final int maxScore = 750;
String input = "R";
String input2 = "R";
char repeat;
Random randomNumbers = new Random();
System.out.println("Welcome to Our version of the dice game Pig");
System.out.println("Here are the instructions");
System.out.println("On a turn, the player or computer rolls the die repeatedly");
System.out.println("Until either a 1,7,12, or 17 is rolled");
System.out.println("or the player or computer holds");
System.out.println("If a 1,7,12, or 17 is rolled, that player's turn ends");
System.out.println("and no points are earned");
System.out.println("If the player chooses to hold, all of the points rolled during");
System.out.println("that turn are added to his or her score.");
System.out.println("First player to 750 points or more WINS!");
System.out.print("\nPlease enter your name: ");
scanner1 = new Scanner(System.in);
String pName = scanner1.nextLine();
System.out.print("\nI Hope You have fun," + pName);
do { // run at least once. Start of loop
dice = randomNumbers.nextInt(6) + 1;
System.out.println();
System.out.printf("%s you rolled a %d %n", pName, dice);
if (dice == 1 || dice == 7 || dice == 12 || dice == 17) // if these numbers, end
{
pScore = 0;
System.out.println("Turn over.");
System.out.println(" " + pName + " total is " + pScore + " ");
break;
} else { // else ask for re-roll
pScore = dice;
pTotalScore += pScore;
System.out.print(+pScore + " Your turn total is " + pTotalScore + " ");
System.out.print("Enter (R) to roll or (H)to hold: ");
input = scanner1.nextLine();
repeat = input.charAt(0);
}
if (repeat != 'R') { // if something other than R, end
break;
}
} while (pTotalScore < 750 || cTotalScore < 750); // allow repeat so long as scores are less than 750
if (repeat == 'H') {
System.out.println("Turn over.");
System.out.print("Current score: " + pname + " has " + pTotalScore);
System.out.println("The Computer has " + cTotalScore);
break;
}
while (input.equalsIgnoreCase("R"));
if (pTotalScore >= maxScore) {
System.out.println("Your total Score is " + totalScore);
System.out.println(+pname + "WINS!");
break;
}
System.out.println();
System.out.println("It is the Computer's turn.");
do {
dice2 = randomNumbers.nextInt(6) + 1;
System.out.println("The Computer rolled: " + dice2);
if (dice2 == 1 || dice2 == 7 || dice2 == 12 || dice2 == 17) {
cScore = 0;
System.out.print("Turn over");
System.out.println("The Computer total is " + cTotalScore);
break;
} else {
cScore = dice2;
cTotalScore += cScore;
System.out.print("The Computer's total is " + cTotalScore + " ");
System.out.print("Enter (r) to Roll or (H)to Hold: ");
input = keyboard.nextLine();
repeat = input.charAt(0);
}
if (repeat == 'H') {
System.out.println("Turn over");
System.out.print("Current score:" + pName + " has " + pTotalScore);
System.out.println(", The Computer has " + cTotalScore);
break;
}
} while (input2.equalsIgnoreCase("R"));
if (cTotalScore >= maxScore) {
System.out.println("The Computer's score is " + cTotalScore + "\n");
System.out.println("The Computer wins!!!!");
System.out.printl("Run The uprisng has begun!!!!!!");
break;
}
Final3.java:112: error: reached end of file while parsing } ^ 1 error
now the problem is i get the error basically means im missing a } but i cant see where it would be nd no matter where i put it it still says
Final3.java:112: error: reached end of file while parsing } ^ 1 error
You have one while loop that does nothing - while (input.equalsIgnoreCase("R")); - and you didn't close your main method. Add } at the end.
Add a closing brace "}" in the end.I hope this will solve your purpose.
Hey guys so I made a Pig Game in Java for my CS project. I didn't have too much trouble with it because I only used one class. However, my professor now is making us implement OOP, and I'm having a lot of trouble. Here is my working Pig Game:
package edu.bsu.cs121.zmbarnes;
import java.util.Random;
import java.util.Scanner;
public class PigGame {
public static void main(String[] args) {
int player1TurnScore = 0;
int player1TotalScore = 0;
int player2TurnScore = 0;
int player2TotalScore = 0;
int dice;
int dice2;
String input = "r";
char repeat;
Scanner keyboard = new Scanner(System.in);
Random diceRoll = new Random();
System.out.println("Welcome to the game of Pig!\n");
while(player1TotalScore < 100 || player2TotalScore < 100){
// human's turn
System.out.println();
System.out.println("It is Player 1's turn.");
do{
dice = diceRoll.nextInt(6) + 1;
System.out.println("You rolled a " + dice);
if(dice == 1){
player1TurnScore = 0;
System.out.println("You lose your turn!");
System.out.println("Your total score is " + player1TotalScore);
break;
}else{
player1TurnScore += dice;
System.out.println("Your turn score is " + player1TurnScore);
System.out.println("And your total score is " + player1TotalScore);
System.out.println("If you hold, " + player1TurnScore + " points will be added to your total score.");
System.out.println("Enter 'r' to roll again, or 'h' to hold.");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 'h'){
break;
}
}
}while(input.equalsIgnoreCase("r") || dice != 1);
player1TotalScore += player1TurnScore;
System.out.println("Your score is " + player1TotalScore);
player1TurnScore = 0;
if(player1TotalScore >= 100){
System.out.println("Your total score is " + player1TotalScore);
System.out.println("PLAYER 1 WINS!");
break;
}
// Player 2's turn
System.out.println();
System.out.println("It is Player 2's turn.");
do{
dice2 = diceRoll.nextInt(6) + 1;
System.out.println("You rolled a " + dice2);
if(dice2 == 1){
player2TurnScore = 0;
System.out.println("You lose your turn!");
System.out.println("Your total score is " + player2TotalScore);
break;
}else{
player2TurnScore += dice2;
System.out.println("Your turn score is " + player2TurnScore);
System.out.println("And your total score is " + player2TotalScore);
System.out.println("If you hold, " + player2TurnScore + " points will be added to your total score.");
System.out.println("Enter 'r' to roll again, or 'h' to hold.");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 'h'){
break;
}
}
}while(input.equalsIgnoreCase("r") || dice2 != 1);
player2TotalScore += player2TurnScore;
System.out.println("Your score is " + player2TotalScore);
player2TurnScore = 0;
if(player2TotalScore >= 100){
System.out.println("Your total score is " + player2TotalScore);
System.out.println("PLAYER 2 WINS!");
break;
}
}
keyboard.close();
}
}
I must use a Dice class with a roll() method, a Player class with void takeTurn(), void bankPoints(), void makeChoice(), and boolean hasWon() methods, a GameOfPig class with , and Project class with void play() method, and the main Project class with main().
I'm just having trouble conceptualization how I can move my code into those methods so the game will work the exact same way. Any help would be appreciated!
I'm also new to OOD. My brief answer is highly borrowed from your code. I hope other one could correct me. Any suggestion is appreciated.
public class PigGame {
Dice dice;
Player player1;
Player player2;
public PigGame() {
this.player1 = new Player("Player1");
this.player2 = new Player("Player2");
this.dice = new Dice();
}
public void play() {
while (!player1.hasWon() && !player2.hasWon()) {
player1.takeTurn(dice);
if (!player1.hasWon())
player2.takeTurn(dice);
}
if (player1.hasWon()) {
System.out.println("Player1 won!");
} else {
System.out.println("Player2 won!");
}
}
public static void main(String[] args) {
PigGame pg = new PigGame();
pg.play();
}
}
class Dice {
private static Random diceRoll = new Random();
public int roll() {
return diceRoll.nextInt(6) + 1;
}
}
class Player {
private int currentRoundScore = 0;;
private int totalScore = 0;
private String playerName;
public Player(String name) {
this.playerName = name;
}
public void takeTurn(Dice dice) {
currentRoundScore = 0;
System.out.println("-------It's " + playerName + "'s turn.--------");
Scanner keyboard = new Scanner(System.in);
String input = "r";
int diceValue = 0;
do {
diceValue = dice.roll();
System.out.println("You rolled a " + diceValue);
if(diceValue == 1){
currentRoundScore = 0;
System.out.println("You lose your turn!");
System.out.println("Your total score is " + totalScore);
break;
}else{
currentRoundScore += diceValue;
System.out.println("Your turn score is " + currentRoundScore);
System.out.println("If you hold, " + currentRoundScore + " points will be added to your total score. And your total score would be " + currentRoundScore + totalScore);
System.out.println("Enter 'r' to roll again, or 'h' to hold.");
input = keyboard.nextLine();
char repeat = input.charAt(0);
if(repeat == 'h'){
break;
}
}
} while (input.equalsIgnoreCase("r") || diceValue != 1);
bankPoints();
}
public boolean hasWon() {
return totalScore >= 100;
}
public void bankPoints() {
totalScore += currentRoundScore;
System.out.println(playerName + "'s total score is " + totalScore + "\n");
}
}
Okay.
Here is my question. I am having some difficulty while making a dice game.
The part I am having issue with is making it exit using a do while loop.
Here is my code. and I'll explain what I mean further in
import java.util.Scanner;
public class Dice
{
public static void main (String[] args)
{
int diceGuess;
int rollNum, roll1, roll2, roll3;
String playAgain = "yes";
Scanner sc = new Scanner(System.in);
// Create two separate dice objects to create a pair of dice
Roll die1 = new Roll();
Roll die2 = new Roll();
// get from the user the number of dice rolls
System.out.print ("Please enter a number between 2 and 12 to begin: ");
diceGuess = sc.nextInt();
do
{
// loop to show rolls
for (rollNum = 1; rollNum <=3; rollNum++)
{
System.out.println("**********Roll #: " + rollNum + " ************");
roll1 = die1.roll();
roll2 = die2.roll();
//if statement to display you win if you win, and to make the loop break.
if(diceGuess==roll1+roll2)
{
System.out.println("You win!");
rollNum = 4;
}
if(rollNum == 3)
{
System.out.println("You lose.\n");
System.out.println("Would you like to play again?");
playAgain = sc.nextLine();
rollNum ++;
}
}
}while(playAgain == "yes");
}
}
This is my utility class.
I want it to ask the user if they want to play again, and then if the user inputs no, I want it to quit.
I'm sure this is just a minor misunderstanding on my part.
Thank you very much stackoverflow.
and heres the other class
//Justin Le
//Dice class
import java.util.Random;
public class Roll
{
//variables used in class
private Random randomRoll = new Random();
private int roll;
boolean playAgain = false;
//constructor
public Roll()
{
roll = 0;
}
//method named roll to return roll number and inside, calls a method to display the roll.
public int roll()
{
roll = randomRoll.nextInt(6) + 1;
showRoll(roll); //accesses showRoll to output in driver class.
return roll;
}
public boolean test()
{
playAgain = !playAgain;
return playAgain;
}
//displays picture of dice roll
private void showRoll(int r)
{
switch(r)
{
case 1:
System.out.println("One: \n" +
" \n " +
" * \n" +
" \n ");
break;
case 2:
System.out.println("Two: \n" +
"* \n" +
" \n" +
" *\n");
break;
case 3:
System.out.println("Three:\n" +
"* \n" +
" * \n" +
" *\n");
break;
case 4:
System.out.println("Four:\n" +
"* *\n" +
" \n" +
"* *\n");
break;
case 5:
System.out.println("Five:\n" +
"* *\n" +
" * \n" +
"* *\n");
break;
case 6:
System.out.println("Six: \n" +
"* *\n" +
"* *\n" +
"* *\n");
break;
default:
System.out.println("error\n");
}
}
}
In your while, use equals() method to compare Strings.. : -
playAgain.equals("yes")
See this excellent post for difference in comparison using equals() and ==..
In your first code: -
if(rollNum == 3)
{
System.out.println("You lose.\n");
System.out.println("Would you like to play again?");
//playAgain = sc.nextLine();
// Change your nextLine() to next()
playAgain = sc.next();
rollNum ++;
}
change
playAgain == "yes"
to
"yes".equals(playAgain)
use while(plyaAgain.equals("yes"));
Follow this link for details on string comparision :
How do I compare strings in Java?
Change this:
while(playAgain == "yes");
to this:
while(playAgain.equals("yes"));