Sorry for the large amount of code, but I'm not sure why
int timesWon;
is getting a unreachable code error on line 90.
Anything that is put on line 90 is unreachable code, meaning anything after it isn't readable.
This is my code for a game of craps for an assignment:
package homework2_3;
import java.security.*;
public class Craps
{
static enum score
{
win, lose
}
public static void main(String[] args)
{
//random Number for a dice roll
SecureRandom random = new SecureRandom();
//ints for the totals on the two dice
int dice1;
int dice2;
//array for times won/lost
score[] total = new score[1000000];
//int for the score of the first throw, if it was not an imediate win or loss
int throw1Score = 0;
//count how many times a win or loss happened at each roll from 1-21
int[] rollWon = new int[22];
int[] rollLost = new int[22];
//loop for each game from 1-1000000
for(int indexGame = 1; 1 <= 1000000; indexGame++)
{
//loop for each throw within a game
for(int indexThrow = 1; total[indexGame] != score.win || total[indexGame] != score.lose; indexThrow++)
{
//get the total of blips on the dice
dice1 = random.nextInt(6) + 1;
dice2 = random.nextInt(6) + 1;
//check if the throw total in throw 1
if(indexThrow == 1)
{
//check if throw 1 is an instant win
if((dice1 + dice2) == 7 || (dice1 + dice2) == 11)
{
total[indexGame] = score.win;
rollWon[indexThrow]++;
}
//check if throw 1 is an instant loss
else if((dice1 + dice2) == 2 || (dice1 + dice2) == 3 || (dice1 + dice2) == 12)
{
total[indexGame] = score.lose;
rollLost[indexThrow]++;
}
//get your "point"
else
{
throw1Score = dice1 + dice2;
}
}
//anything other than throw 1
else
{
//check if you "made your point"
if((dice1 + dice2) == throw1Score)
{
total[indexGame] = score.win;
if(indexThrow <= 20)
{
rollWon[indexThrow]++;
}
else if(indexThrow > 20)
{
rollWon[21]++;
}
}
//check if you rolled a 7 (lost)
else if((dice1 + dice2) == 7)
{
total[indexGame] = score.lose;
if(indexThrow <= 20)
{
rollLost[indexThrow]++;
}
else if(indexThrow > 20)
{
rollLost[21]++;
}
}
}
}
}
//ints to add up all the wins and losses in the array of scores
int timesWon;
int timesLost;
//loop for the adding
for(int winLossCheck = 1; winLossCheck <= 1000000; winLossCheck++)
{
if(total[winLossCheck] == score.win)
{
timesWon++;
}
if(total[winLossCheck] == score.lose)
{
timesLost++;
}
}
//print the total times you won/lost
System.out.println("you won " + timesWon + " times, and you lost " + timesLost + " times");
}
}
As far as I can tell, everything is logically correct and syntactically correct.
Thanks in advance for any help!
1 <= 1000000 is always true
You have a for loop in which the condition is 1 <= 1000000. This loop will not exit, thus making all code after the loop unreachable. Change the the condition to something where the code will exit.
For example:
for(int i = 1; i<=10; i++) {
System.out.println(i);
}
This code will print out the integers from 1-10. However if I create another for loop with a condition that is always true like 0<7. Since the loop won't end, all code after it is unreachable. Change your for loop to have a condition that won't always be true, so the program will continue.
Related
What I’m trying to do with the following code is to print numbers and to replace the number with a word for the number that are divisible for 3, for 5 and for both 3 and 5.
So, when the user starts the code, it has to choose how many players are going to play.
The problem is that my code print all the numbers from 1 to 100 four times, one time for every player.
Can someone kindly explain me where is the mistake? Thanks!
Here are two solutions to that problem.
Option 1
In your case, there is no player object needed. So you could make use of a counter. That one will start by 1 and be incremented until it equals the selected number of players. Then you have to reset it to 1 again.
int player = 1;
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0 && i % 5 == 0) {
System.out.println("player " + player + " says: divisible for 3 and 5");
} else if (i % 3 == 0) {
System.out.println("player " + player + " says: divisible for 3");
} else if (i % 5 == 0) {
System.out.println("player " + player + " says: divisible for 5");
} else {
System.out.println("player " + player + " says: " + i);
}
if (player < playersNumber) {
player++;
} else {
player = 1;
}
}
Option 2
If you really need a player object, I will advise you to make use of a queue. Also therefore you do not need an extra for-loop.
final Queue<Integer> allPlayers = new LinkedList<>();
for (int i = 1; i <= playersNumber; i++) {
allPlayers.add(i);
}
for (int i = 1; i <= 100; i++) {
final int player = allPlayers.poll();
allPlayers.add(player);
if (i % 3 == 0 && i % 5 == 0) {
System.out.println("player " + player + " says: divisible for 3 and 5");
} else if (i % 3 == 0) {
System.out.println("player " + player + " says: divisible for 3");
} else if (i % 5 == 0) {
System.out.println("player " + player + " says: divisible for 5");
} else {
System.out.println("player " + player + " says: " + i);
}
}
Both solutions are not perfect, but there are working ones.
If something is unclear with these solutions do not hesitate to ask me.
I can post here a working example, but that will have no learning effect for you. So please answer my question.
What was your intention to use this:
for(int p = 0; p <= 100; p++){
for(int i = 1; i <= 100; i++){
}
}
Why do you think, you need two for-loop with each 100 iterations?
Keep it simple and don't overcomplicate things without a need. You alredy seem to be familiar with the modulo operator. Just use that to get the current player:
public static void main(String args[]) {
int playersNumber;
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the number of players (min 2, max 6)");
playersNumber = scanner.nextInt();
//add so many players as user interd number
ArrayList<String> players = new ArrayList<>();
for (int i = 1; i <= playersNumber; i++) {
players.add("Player " + i);
}
// use modulo operator to get the current player.
// Note: list indexes are zero based, but your player number start with one,
// so you need to substract one from i
for(int i = 1; i <= 100; i++){
if(i % 3 == 0 && i % 5 == 0){
System.out.println(players.get((i-1) % playersNumber) + " says: divisible for 3 and 5");
} else if (i % 3 == 0) {
System.out.println(players.get((i-1) % playersNumber) + " says: divisible for 3");
} else if (i % 5 == 0) {
System.out.println(players.get((i-1) % playersNumber) + " says: divisible for 5");
} else {
System.out.println(players.get((i-1) % playersNumber) + " says: " + i);
}
}
}
I've written a simple Java program to display the results of 20 dice rolls on the console. The results I'm getting are listed below:
3
1
java.util.Random#62efae3b
1
5
4
1
java.util.Random#62efae3b
1
java.util.Random#62efae3b
java.util.Random#62efae3b
1
6
java.util.Random#62efae3b
1
java.util.Random#62efae3b
java.util.Random#62efae3b
1
2
3
3
When I ran it for a few times, the string after "#" is different, but basically in the same format. What have I done wrong?
Here is the code:
import java.util.Random;
public class QiProb3 {
public static void main(String[] args) {
Random diceNumber = new Random();
for (int count = 0; count <= 20; count++) {
if ((diceNumber.nextInt(6) + 1) == 1) {
System.out.println("1");
} else if ((diceNumber.nextInt(6) + 1) == 2) {
System.out.println("2");
} else if ((diceNumber.nextInt(6) + 1) == 3) {
System.out.println("3");
} else if ((diceNumber.nextInt(6) + 1) == 4) {
System.out.println("4");
} else if ((diceNumber.nextInt(6) + 1) == 5) {
System.out.println("5");
} else if ((diceNumber.nextInt(6) + 1) == 6) {
System.out.println("6");
} else {
System.out.println(diceNumber);
}
}
}
}
else {
System.out.println(diceNumber);
}
You are printing the address of diceNumber by invoking its default toString() function in your else clause.
That is why you are getting the java.util.Random#62efae3b
The more critical issue is why it gets to the 'else' clause, I believe that is not your intention.
Note: In the question, a new number is generated in each if/else if clause, which is why the code actually gets to the final else clause.
What you should be doing is:
for (int count = 0; count < 20; count++) {
int rollValue = diceNumber.nextInt(6) + 1;
if (rollValue == 1) {
System.out.println("1");
} else if (rollValue == 2) {
System.out.println("2");
} else if (rollValue == 3) {
System.out.println("3");
} else if (rollValue == 4) {
System.out.println("4");
} else if (rollValue == 5) {
System.out.println("5");
} else if (rollValue == 6) {
System.out.println("6");
} else {
// This else is now redundant
System.out.println(diceNumber);
}
}
or a more straight-forward method would be:
// count < 20 instead of count <= 20
for (int count = 0; count < 20; count++) {
int rollValue = diceNumber.nextInt(6) + 1;
System.out.println(rollValue);
}
Credit goes to 'Elliott Frisch' for realizing that the loop is
executed 21 times instead of 20.
You're Re-Rolling
With each if you re-roll the dice. Store the value, and test it!
Random diceNumber = new Random();
for (int count = 0; count <= 20; count++) {
int roll = diceNumber.nextInt(6) + 1;
if (roll == 1) {
System.out.println("1");
} else if (roll == 2) {
System.out.println("2");
} else if (roll == 3) {
System.out.println("3");
} else if (roll == 4) {
System.out.println("4");
} else if (roll == 5) {
System.out.println("5");
} else if (roll == 6) {
System.out.println("6");
} else {
System.out.println("RNG Error: " + diceNumber);
}
}
It Could be More Concise
Your posted code might be shortened like
for (int count = 0; count <= 20; count++) {
int roll = diceNumber.nextInt(6) + 1;
System.out.println(roll);
}
Note
Also, you get 21 rolls using the above <= 20 test.
You can do this without the large if-else ladder:
int x = 0;
int i = 0;
while(i < 20){
x = (int)(Math.random() * 7);
if(x != 0)
{
System.out.println((int)Math.floor(x));
i++;
}
}
Math.random() gets a value between 0 and 1 and this value is multiplied to 7. If the dice turns out to be zero, skip the roll and do another one. The Math.floor() value will round the decimal value down to the nearest integer (if product = 6.2 then the output of the roll will be 6).
I'm making a Craps java program and I'm having some trouble adding a "Do you want to play again" statement at the end. If you can help me out that would be greatly appreciated! Also, the counter that I have to count how many games the user won/lost is not working properly. If you see the problem can you please tell me!
import java.util.Scanner;
public class Lab5 {
static int dice2;
public static void main(String[] args) {
//variables
int dice1;
int dice2;
int numWins = 0;
int numLosses = 0;
//Call the welcome method
welcome();
//fetch random numbers
/*
* **************************************************************
*welcome method
*welcome user
*no parameters
*no return
****************************************************************
*/
}
public static void welcome() {
System.out.println("Welcome to a Lucky (for me) Dice Game! \nFEELING LUCKY?!? Hope you brought lots of CASH!");{
}
int die1 = (int) (Math.random()*6 + 1);
int die2 = (int) (Math.random()*6 + 1);
int dice = die1 + die2;
System.out.println("Roll: total = " + dice);
int numWins = 0;
int numLosses = 0;
if (dice == 7 || dice == 11){
System.out.println("Woah!!! With a: "+dice+ " You WIN!!!!!!!!");
numWins++;
}
else if (dice == 2 || dice == 3 || dice == 12){
System.out.println("Sorry, with a "+dice+" You lose:(");
numLosses++;
}
while (dice != 0){
int die3 = (int) (Math.random()*6 + 1);
int die4 = (int) (Math.random()*6 + 1);
int dice2 = die3 + die4;
System.out.println("Roll: total = "+dice2);
if (dice2 == 2|| dice2 == 3 || dice2 == 12){
System.out.println("Sorry, with a "+dice2+" You lose:(");
numLosses++;
dice = 0;
}
else if (dice2 == 7 || dice2 == 11){
System.out.println("Woah!!! With a: "+dice2+ " You WIN!!!!!!!!");
numWins++;
dice = 0;
}
{
System.out.println("So far you have won " + numWins +
" times and lost " + numLosses + " times, ");
{
}
}
}
}}
This is my output when I run it:
Welcome to a Lucky (for me) Dice Game!
FEELING LUCKY?!? Hope you brought lots of CASH!
Roll: total = 2
Sorry, with a 2 You lose:(
Roll: total = 8
So far you have won 0 times and lost 1 times,
Roll: total = 10
So far you have won 0 times and lost 1 times,
Roll: total = 8
So far you have won 0 times and lost 1 times,
Roll: total = 3
Sorry, with a 3 You lose:(
So far you have won 0 times and lost 2 times,
The counter should only be stated after the win or lose. How do I fix this?
To repeat something, use a loop, such as a while loop or a do-while loop if you're not sure how manny times you'll loop. To get user input, use a Scanner object -- which you've already imported. The do-while loop structure will be something like...
do {
// code to do inside of the loop
} while (somethingIsTrue);
You will need to use some sentinel variable to change in the loop and then test inside of the while boolean check. It could be a String, in which case you'd use the String equals(...) or equalsIgnoreCase(...) method in your while's boolean check.
So consider prompting for input at the end of the do block of code using System.out.print(...), getting the input with your Scanner, and then testing that input in the while boolean test.
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Lab5
{
static int dice2;
public static void main(String[] args)
{
//variables
int dice1;
int dice2;
int numWins = 0;
int numLosses = 0;
//Call the welcome method
//welcome();
//fetch random numbers
/*
* **************************************************************
*welcome method
*welcome user
*no parameters
*no return
****************************************************************
*/
while(true)
{
welcome();
}
}
public static void welcome()
{
System.out.println("Welcome to a Lucky (for me) Dice Game! \nFEELING LUCKY?!? Hope you brought lots of CASH!");
int die1 = (int) (Math.random()*6 + 1);
int die2 = (int) (Math.random()*6 + 1);
int dice = die1 + die2;
System.out.println("Roll: total = " + dice);
int numWins = 0;
int numLosses = 0;
if (dice == 7 || dice == 11)
{
System.out.println("Woah!!! With a: "+dice+ " You WIN!!!!!!!!");
numWins++;
}
else if (dice == 2 || dice == 3 || dice == 12)
{
System.out.println("Sorry, with a "+dice+" You lose:(");
numLosses++;
}
while (dice != 0)
{
int die3 = (int) (Math.random()*6 + 1);
int die4 = (int) (Math.random()*6 + 1);
int dice2 = die3 + die4;
System.out.println("Roll: total = "+dice2);
if (dice2 == 2|| dice2 == 3 || dice2 == 12)
{
System.out.println("Sorry, with a "+dice2+" You lose:(");
numLosses++;
dice = 0;
}
else if (dice2 == 7 || dice2 == 11)
{
System.out.println("Woah!!! With a: "+dice2+ " You WIN!!!!!!!!");
numWins++;
dice = 0;
}
{
System.out.println("So far you have won " + numWins +
" times and lost " + numLosses + " times, ");
{
}
}
}
System.out.printf("\n\nWould you like to play again? ");
Scanner scanner = new Scanner(System.in);
String uinput = scanner.nextLine();
if(uinput.isEmpty() ||
uinput.equals("n") || uinput.equals("no"))
{
scanner.close();
System.out.println("Goodbye.");
return;
}
System.out.println();
}}
this are comments that explain the game so you can test it, but the main problem is when you are suppose to run the while loop if you a point value then it becomes an infinite loop. How do I get it to not be an infinite loop?
import java.util.Random;
public class Craps {
private int roll1;
private int roll2;
private Random randGen;
private int sum;
private int thePoint = sum;
private int bet;
private int newSum;
// instance classes
public Craps() {
randGen = new Random(); // this is the random generator
}
// when you win you double your money
// when you lose you lose everything
public void roll(int bet) { // you can bet as much money as you want
roll1 = (randGen.nextInt(6) + 1);
roll2 = (randGen.nextInt(6) + 1);
sum = roll1 + roll2; // you must add the two rolls and that is your sum
if (sum == 2 || sum == 3 || sum == 12) { // if the sum is 2 you lose
System.out.println("The sum is 2. You Lose!");
System.out.println("Your credit:" + " " + bet * 0);
} else if (sum == 7 || sum == 11) { // if it 7 you win
System.out.println("The sum is 7. You Win!");
System.out.println("Your credit:" + " " + bet * 2);
} else {
System.out.println("You rolled a" + " " + sum + ". " + "That is your point. Roll again.");
sum = thePoint;
}
}
public void rollAgain() {
while (sum != 7 || sum != thePoint) { // whatever the the sum is that is not one of the numbers above becomes your point.
roll1 = (randGen.nextInt(6) + 1);// you must role the die again until you get your point again the you win or until you get a 7 and then you lose.
roll2 = (randGen.nextInt(6) + 1);
sum = roll1 + roll2;
if (thePoint == sum) { // if the point equals the sum you win
System.out.println("You're on point. You Win!");
System.out.println("Your credit:" + " " + bet * 2);
} else if (sum == 7) { // if it equals 7 you lose.
System.out.println("You got a 7. You lose!");
System.out.println("Your credit:" + " " + bet * 0);
}
}
}
}
You need to change your loop condition.
while (sum != 7 || sum != thePoint) what happens here is that as soon as the first condition is met (sum is not seven), the loop starts executing.
if you change it to while (sum != 7 && sum != thePoint) then both these conditions need to be met - the loop only starts executing again if sum is not seven or the value of thePoint.
I'm trying to create a game that rolls 2 set of dice, three times in a row. It has the user guess a number between 2-12 just once. If that one guess matches any of the three rolls he/she wins, otherwise he/she loses. I have another class to display results and I have a counter for how many loops it's been through. It comes out 0 if the user correctly guessed it, otherwise it comes out as 1. I'm guessing the loop just loops once so if anyone can point out what I'm doing wrong to make it so it loops three times(and stopping if the user gets the answer right).
import javax.swing.JOptionPane;
/**
* #author Marcus
*
*/
public class Dice {
int randomDieNum1;//random number generator for dice
int randomDieNum2;//random number generator for dice
private final int MINVALUE1 = 1, //minimum die value
MAXVALUE1 = 6;//maximum die value
private final int MINVALUE2 = 1, //minimum die value
MAXVALUE2 = 6;//maximum die value
int userNum = Integer.parseInt(JOptionPane.showInputDialog(null, "Guess a number between 1-12", "Guess a Number",
JOptionPane.INFORMATION_MESSAGE));//gets user input
String result ; //results
int start = 0 ; //counter to see how many turns were taken
public Dice()
{
for (int i = 1 ; i <= 3; i++)
randomDieNum1 = ((int)(Math.random()* 100) % MAXVALUE1 + MINVALUE1);
randomDieNum2 = ((int)(Math.random()* 100) % MAXVALUE2 + MINVALUE2);
int total = randomDieNum1 + randomDieNum2;
if (randomDieNum1 + randomDieNum2 != userNum)
{
result = "You did not guess the \n number correctly";
++ start;
}
else if (randomDieNum1 + randomDieNum2 == userNum)
{
result = randomDieNum1 + "+" + randomDieNum2 + "=" + total + "\n" +
"You guessed the number correctly";
}
else
{
result = "You Did not guess the number correctly";
}
}
public String get() //used in another class to display count
{
String temp;
temp = "" + start;
return temp;
}
}
EDIT
Thanks guys. I added both suggestions and added a break to stop the loop after the user gets the answer right.
This is what it looks like:
public Dice()
{
for (int i = 1 ; i <= 3; i++)
{randomDieNum1 = ((int)(Math.random()* 100) % MAXVALUE1 + MINVALUE1);
randomDieNum2 = ((int)(Math.random()* 100) % MAXVALUE2 + MINVALUE2);
int total = randomDieNum1 + randomDieNum2;
if (randomDieNum1 + randomDieNum2 == userNum)
{result = randomDieNum1 + "+" + randomDieNum2 + "=" + total + "\n" +
"You guessed the number correctly";
++ turns; //
break; //stops the loop if condition is meet
}
else if(randomDieNum1 + randomDieNum2 != userNum)
{
result = "You did not guess the \n number correctly\n\n";
++ turns;
}
}
}
Apart from the missing { in for (int i = 1 ; i <= 3; i++) {
You might have to reconsider the logic used in the if condition
if(x+y != c)
{// do operation A}
else if (x+y == c)
{// do operation B}
the else condition after the else-if will never get executed.
This isn't encapsulating everything in the loop
for (int i = 1 ; i <= 3; i++)
You're missing the brackets for encapsulating
for (int i = 1 ; i <= 3; i++) {
}