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);
}
}
}
Related
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.
I'm trying to make a simple java simulator horse race game using only arrays and loops. My program was nearly finished. My only problem is that when you enter the number of horses who will join in the contest, that particular number you enter will win even if other horses are finished. Example, when you type 5 horses that will join in the contest, that "5" number will win even if the other number finished first. i can't really determine the winner. My program seems to work well. Any advice would be appreciated. Thank You!
Here's my code:
public static void main(String[] args) throws InterruptedException {
Scanner input = new Scanner(System.in);
int[] tracks = new int[70];
int bet;
System.out.println("==============");
System.out.println("||HORSE RACE||");
System.out.println("==============");
System.out.println("WHO'S GONNA WIN IN THIS EPIC RACE?");
System.out.println("ENTER HOW MANY HORSES WOULD YOU LIKE TO JOIN:"
+ "\n 2-10 HORSES are allowed to join!");
int horses;
do {
horses = input.nextInt();
} while (horses < 2 || horses > 10);
int[] move = new int[horses];
double[] betHorse = new double[horses];
System.out.println("Enter how many person will bet?");
int number = input.nextInt();
for (int i = 1; i <= number; i++) {
do {
for (int j = 1; j <= horses; j++) {
System.out.println("[" + j + "]" + " for HORSE " + j);
}
System.out.println("Person no." + i + ": Enter the number of horse:");
bet = input.nextInt();
} while (bet < 1 || bet > horses);
for (int p = 1; p <= horses; p++) {
if (bet == p) {
System.out.println("Enter the amount of your bet?");
betHorse[bet - 1] += input.nextDouble();
}
}
for (int j = 1; j <= horses; j++) {
System.out.println("Bet for HORSE " + j + ":P" + betHorse[j - 1]);
}
}
System.out.println("OKAY THAT'S SETTLED");
System.out.println("Race begins in:");
int num3 = 3;
for (int i = 1; i <= num3; num3--) {
System.out.println(num3);
Thread.sleep(1000);
}
do {
Thread.sleep(100);
int[] numbers = new int[horses];
for (int i = 0; i < horses; i++) {
numbers[i] = 1 + (int) (Math.random() * 6);
}
for (int i = 0; i < horses; i++) {
if (numbers[i] >= 1 && numbers[i] <= 3) {
move[i]++;
} else if (numbers[i] == 4 && numbers[i] == 5) {
move[i] = move[i] + 3;
} else if (numbers[i] == 6) {
move[i] = move[i] + 5;
}
}
System.out.println("\n\n\n");
for (int i = 1; i <= horses; i++){
System.out.println("Horse " + i +" position:" + move[i-1]);
}
for (int i = 1; i <= horses; i++) {
for (int j = 0; j < move[i - 1]; j++) {
System.out.print("--");
}
System.out.println(i + "H" + move[i - 1]);
}
} while (move[horses-1] < tracks.length );
for (int i = 1; i <= horses; i++) {
if (move[i - 1] > tracks.length) {
System.out.println("HORSE " + i + " finished the track! One who bets for HORSE " + i + " won P" + betHorse[i - 1] * 2);
}
}
}
}
The condition in your while loop :
while (move[horses-1] < tracks.length)
means that the loop will end once the last horse (whose index is horses-1) finishes. You should change the condition to end the loop when any horse finishes.
Whenever you update move[i], you should test if move[i]>=tracks.length, and if it is, set some boolean variable to true - ended = true;.
Then change the loop's condition to while (!ended) .
There are several problems with your simulation.
As #Eran said, you most serious problem is the termination condition. The loop stops when the horse in the horses - 1 position finishes, even if other horses were actually winning.
You may wonder why it was always winning, though. After all, your printing loop at the end should have seen another horse if the horses - 1 one finished but the other one finished first. This is probably because you actually gave all the horses very little chance to advance.
The horses have a 50% chance of advancing one step (numbers[i] is between 1 and 3). Then they have a 33% of not advancing at all ( numbers[i] is 4 or 5, but you asked for numbers[i] == 4 && numbers[i] == 5, and it can't be both at the same time so this if is never entered). They have a 16% chance of advancing 5 steps. So most of the time, the other horses are advancing as much or less than the horses - 1 horse. If you change that condition to || instead of &&, there are higher chances that you'll see another winning horse even if you don't correct your while condition (but you should correct it, of course).
That loop at the end is really not necessary. When you keep your ended boolean, you can also keep an int winner and set it to the i of the horse that finished. Then you don't have to loop, just give the results for that particular winner.
Your tracks variable is set to be an array, but you are not actually using it. You are only using the moves array for the horses. So you should really just keep a simple int that says what the length of the track is, because that's the only thing that's interesting you - have the horses made enough moves to cover the whole length of the track?
You also don't need the numbers array. You can loop on the horses, and roll a single number for the current horse, and make your decision based on that number.
for (int i = 0; i < horses; i++) {
int die = 1 + (int)(Math.random()*6);
if (die >= 1 && die <= 3) {
move[i]++;
} else if (die == 4 || die == 5) { // Note the || condition
move[i] = move[i] + 3;
} else { // Note that 6 is the only possibility remaining
move[i] = move[i] + 5;
}
}
The most important things are the loop condition and the ||, of course.
public static void notDivisible(int n, int x, int y)
{
Scanner kb = new Scanner(System.in);
System.out.println("These are the ints from 1 to" + n + "that are not divisible by" + x + "or" + y);
n = kb.nextInt();
x = kb.nextInt();
y = kb.nextInt();
if((n%x) == 0)
{
}
else
{
System.out.println()
}
if((n%y) == 0)
{
}
else
{
System.out.println();
}
So this is all I have so far. I know that I have to use modulus and print out the numbers that aren't divisible by the number, but how can I do it?
Reading "not divisible by x or y" as "divisible by neither x nor y":
for (int i = 1; i <= n; ++i) {
if (i%x!=0 && i%y!=0) {
System.out.println(i);
}
}
Make a loop from 1 to the limit (n).
for(int i = 1; i < n; i++)
{
if(i % x != 0 || i % y != 0)
{
System.out.println(i);
}
}
The modulus (%) is the rest of the division. If i % x is different from 0 that means i cannot be divided by x.
First of all you will need to ask the user the numbers n, x and y before printing them.
Then what you want to achieve is a typical job for for loops:
for(int i=0; i<n; ++i) {
if(i%x != 0 && i%y != 0) {
System.out.println(i);
}
}
Try doing your next exercise alone ;)
This reeks of homework. But against my better judgment:
for(int z=1; z<n; z++) { // Test all numbers from 1 to n
if((z % x) == 0) {
System.out.println(z + " is divisible by " + x);
} else System.out.println(z + " isn't divisible by " + x);
if((z % y) == 0) {
System.out.println(z + " is divisible by " + y);
} else System.out.println(z + " isn't divisible by " + y);
}
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++) {
}