Math.random if statement error - java

int Comproll1= (int) (Math.random()*6+1);
int Comproll2= (int) (Math.random()*6+1);
while (m==1)
{
{
if (Comproll1==1 || Comproll2==1)
{
System.out.println("One of the computer's dice rolls was a 1, it lost all the points for the round & it is now your turn!");
cr= cr-cr;
m++;
}
else if (Comproll1==1 && Comproll2==1)
{
System.out.println("The Computer rolled 2 1's, their total number of points is now 0 & it is now your turn!");
cp=cp-cp;
m++;
}
else
{
cr= Comproll1+Comproll2;
cp= cp+cr;
}
}
Hey everyone! Above is my code- for some reason regardless, it WILL ALWAYS, no matter what, always display the first option, which is "One of the computer's dice rolls was a 1, it lost all points for the round...". Even when I change the order of the statements, it still does this. Can someone please explain to me why this is happening?? Thanks!

As far as I can tell, because you aren't re-rolling
int Comproll1= (int) (Math.random()*6+1);
int Comproll2= (int) (Math.random()*6+1);
while (m==1)
{
Should be
while (m==1)
{
int Comproll1= (int) (Math.random()*6+1);
int Comproll2= (int) (Math.random()*6+1);
Also, Java naming convention is camel case for variables (and starts with a lower case letter). So, Comproll1 might be compRoll1. Finally, I personally prefer Random.nextInt() and for 6 sided dice that might look like
Random rand = new Random();
while (m==1)
{
int compRoll1 = rand.nextInt(6) + 1;
int compRoll2 = rand.nextInt(6) + 1;
Edit Actually, you also need to reverse the order of your tests. Because if either is true then it will never be possible that the test for both being true will be entered.
if (Comproll1==1 || Comproll2==1) {
// Here.
}else if (Comproll1==1 && Comproll2==1) {
// Will never enter here.
}
Switch the order to,
if (Comproll1==1 && Comproll2==1) {
// Both.
}else if (Comproll1==1 || Comproll2==1) {
// Either.
}

The problem is that you need to check if they are both 1, before checking if either of them are 1s. If we look at the code:
if (Comproll1==1 || Comproll2==1)
{
System.out.println("One of the computer's dice rolls was a 1, it lost all the points for the round & it is now your turn!");
cr= cr-cr;
m++;
}
else if (Comproll1==1 && Comproll2==1)
{
System.out.println("The Computer rolled 2 1's, their total number of points is now 0 & it is now your turn!");
cp=cp-cp;
m++;
}
if:
Comproll1 = 1
Comproll2 = 1
You expect that it will go into the else if (Comproll1==1 && Comproll2==1) however, if this is true than if (Comproll1==1 || Comproll2==1) will always be true.
To fix this simply change the order of the ifs, like this:
if (Comproll1==1 && Comproll2==1)
{
System.out.println("The Computer rolled 2 1's, their total number of points is now 0 & it is now your turn!");
cp=cp-cp;
m++;
}
else if (Comproll1==1 || Comproll2==1)
{
System.out.println("One of the computer's dice rolls was a 1, it lost all the points for the round & it is now your turn!");
cr= cr-cr;
m++;
}
Hope this helps :)
(Also you need to reroll the dice (as Elliott Frisch Said in his answer))

Try changing the order of your if statements. Logically, if one of the two comparisons are true, the first statement will execute. In the case that the second conditions else if (Comproll1==1 && Comproll2==1) are true, the first conditions if (Comproll1==1 || Comproll2==1) will also be true.
Since you've chained the if statements in an if-else-if fashion, the first if statement to equate to true will execute.
if (Comproll1==1 && Comproll2==1)
{
System.out.println("The Computer rolled 2 1's, their total number of points is now 0 & it is now your turn!");
cp=cp-cp;
m++;
}
else if (Comproll1==1 || Comproll2==1)
{
System.out.println("One of the computer's dice rolls was a 1, it lost all the points for the round & it is now your turn!");
cr= cr-cr;
m++;
}
else
{
cr= Comproll1+Comproll2;
cp= cp+cr;
}

Related

how to get loop to solve common divisor method

how do I get this loop to print all the divisors with two user inputted numbers including 1 but just print 1 and relatively prime when the two numbers have no common divisors.
System.out.println("Common divisors of " + a + " and " + b + ":");
for (int i = 1; i <= b; i++)
if (a % i == 0 && b % i == 0) {
if (a % i == 0 && b % i == 0) {
System.out.println(i);
if (i == 1)
System.out.println("Relatively Prime");
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter two positive integers:");
int input1 = scan.nextInt();
int input2 = scan.nextInt();
printCommonDivisors(input1, input2);
}
}
Right now it says relatively prime after 1 even if the numbers have common divisors.
I am just trying to get it to say relatively prime when the two numbers only common divisor is 1 but also not print relatively prime after 1 when the numbers do have more common divisors. this the output right now.
Please enter two positive integers:
10
20
Common divisors of 10 and 20:
1
Relatively Prime
2
5
10
You need a boolean value to store whether you have found a greater-than-one divisor inside the loop. Instead of
if (i == 1)
System.out.println("Relatively Prime");
Check the boolean value after the loop and print "Relatively Prime" if a divisor was not found.
You have the line if (a % i == 0 && b % i == 0) { twice, you only need to have one of it, make sure to remove the closing brace for it as well.
If you want to print "relatively prime" only if there were no other divisors, you should check for other divisors first (for instance by starting with the large numbers and working your way down, rather than starting with small numbers and working your way up) and if you find one, somehow record this fact so you later know not print "relatively prime".
In code:
boolean divisorFound = false;
for (int i = b; i > 1; i--) {
if (a % i == 0 && b % i == 0) {
System.out.println(i);
divisorFound = true;
}
}
System.out.println(1);
if (!divisorFound) {
System.out.println("relatively prime");
}
Of course, there are more efficient algorithms. For instance, one could use euklid's algorithm to efficiently determine the greatest common divisor, then find its prime factors, and use that to efficiently iterate all divisors.
this works good but the output code is in descending order I need it ascending sadly
Actually, since we take the 1 out of the loop, the order of the loop doesn't matter anymore :-)
System.out.println(1);
boolean divisorFound = false;
for (int i = 2; i <= b; i++) {
if (a % i == 0 && b % i == 0) {
System.out.println(i);
divisorFound = true;
}
}
if (!divisorFound) {
System.out.println("relatively prime");
}

How to swap numbers in while loop java

import java.util.Scanner;
public class Swap {
// if the number is less than 10, swap the last two numbers and print them.
public static void main(String[] args) {
// User to enter a number between 1 and 10, but not zero.
Scanner number = new Scanner(System. in );
System.out.println("Enter a Integer(whole number) between 1 and 10. : ");
int userNum = number.nextInt();
while (userNum > 10 || userNum < 0) {
System.out.println("Try again: ");
userNum = number.nextInt();
}
System.out.println("Your number loop");
while (userNum <= 10) {
System.out.println(userNum);
userNum++;
}
System.out.println("Guess the two swap numbers:");
}
}
How do I swap the last two numbers? I am a beginner learning java and OOP. I have created this program where the user has to enter a number between 1 and 10. If the user enters a number below 1 and above 10, the user gets prompted to try again. Then it prints the list of numbers based off the users input. e.g. if the user enters 8, its prints the loop 8,9 and 10. I have having trouble, I understand how to swap two variable, not inside a loop. Thank you and much appreciated for your help.
Let's assume that the maximum number is a parameter N, so that you could swap any last two numbers and place N before N - 1
private static final int N = 10;
There are several ways to do this using different Java operators:
if, to update delta parameter
while (userNum <= N) {
int delta = 0;
if (userNum >= N - 1) {
delta = userNum == N - 1 ? 1 : -1;
}
System.out.println(userNum + delta);
userNum++;
}
or simply skip N - 1 and print it after the loop:
while (userNum <= N) {
if (userNum != N - 1) {
System.out.println(userNum);
}
userNum++;
}
System.out.println(N - 1);
switch
while (userNum <= N) {
int printNum = userNum++;
switch(printNum) {
case N:
printNum--; break;
case N - 1:
printNum++; break;
default:
break;
}
System.out.println(printNum);
}
two consequent loops (the second going backwards):
while (userNum < N - 1) {
System.out.println(userNum++);
}
userNum++;
while (userNum >= N - 1) {
System.out.println(userNum--);
}
another way this can be solved is by creating a loop(for or while) and taking the two numbers you can use the math functions- Math.max(a,b) || Math.min(a,b) to find the biggest and smallest numbers. Afterwards you can create more variables- c&d to save the two numbers.
goodluck
a=max
b=min
then
c=a
d=b;
then a=d and b=c.

Java working out which number hits zero first

I'm building a simple fighting game to test out loops and if statements, however I've run into a kind of complex logic issue.
The loop ends when either the player or enemy HP hits zero however I've discovered that my code can't detect which HP hits zero first results in the player always winning.
Is there a simple way of tracking which number hits zero first therefor breaking the loop?
do {
#SuppressWarnings("resource")
Scanner reader = new Scanner(System.in);
System.out.println("1: Attack. 2: Defend");
int n = reader.nextInt();
if (n == 1){
PHP = (PHP-EATK);
EHP = (EHP-PATK);
} else if (n == 2){
PHP = (PHP-Math.max(0, EATK-PDEF));
}
System.out.println("P "+PHP);
System.out.println(EHP);
}
while (PHP >= 1 || EHP >= 1);
if(PHP <= 0){
System.out.println("You Lose!");
}else if (EHP <= 0){
System.out.println("You win!");
}
Look at your loop continuation condition:
while (PHP >= 1 || EHP >= 1)
It means "while the player or his enemy can fight, go on". In other words, you continue fighting until they both die, at which point you declare the player the winner, even though it's a draw.
Changing the condition to ""while the player and his enemy can fight" will fix this problem.
change while (PHP >= 1 || EHP >= 1); to while (PHP >= 1 && EHP >= 1);.
You using OR operation where you want AND

Java: Do-while loop with multiple conditions

I am trying to create the scissors-paper-stone-game in Java with a do-while loop. The computer will randomly select 1, and the user makes his choice. The exit condition is if the user wins twice (userWin) or the computer wins twice (compWin). If there is a draw, neither counter increases.
// Scissors, paper, stone game. Best of 3.
// scissors = 0; paper = 1; stone = 2;
import java.util.Scanner;
public class Optional2 {
public static void main(String[] args) {
int userWin = 0;
int compWin = 0;
do {
//comp choice
int comp = 1; //TEST CASE
// int comp = (int) (Math.random() * (2 - 0 + 1) + 0);
//user choice
System.out.println("0 for scissors, 1 for paper, 2 for stone");
Scanner sc = new Scanner(System.in);
int user = sc.nextInt();
//Draw
if (comp == user) {
System.out.println("Draw");
//Win =)
} else if (comp == 0 && user == 2 || comp == 1 && user == 0 ||
comp == 2 && user == 1) {
System.out.println("WIN!");
userWin++;
//Lose =(
} else {
System.out.println("Lose =(");
compWin++;
}
} while (compWin < 2 || userWin < 2);
System.out.println("You won " + userWin + " times!");
}
}
For int comp, it should be random, but I am setting it to 1 (paper) for easy testing.
However, presently only the 1st condition will exit the loop if it becomes true. I am expecting the 2nd condition to exit the loop too if it becomes true with the || operator, but the loop just keeps looping even if it comes true.
ie. if I put while (userWin < 2 || compWin < 2), it will exit if the user wins twice but not if the computer wins twice. If I put while (compWin < 2 || userWin < 2), it will exit if the computer wins twice but not if the user wins twice.
I tried changing it to while ((userWin < 2) || (compWin < 2)) too but it doesn't work.
but the loop just keeps looping even if it comes true
A while loops keeps looping as long as the condition remains true.
I think the problem is that you should rewrite the condition to:
while ((userWin < 2) && (compWin < 2))
with && instead of ||. Indeed: now the while loop is something like: "Keep looping as long as the the user has not won two or more times, and the computer has not won two or more times."
You should use && instead:
while (userWin < 2 && compWin < 2);
This is because you want to be in the loop as long as none of the user or comp gets 2 consecutive wins
That is translated into
userWin < 2 && (=AND) compWin < 2
Which means: as long as both the user AND the comp has less than 2 consecutive wins, stays in the loop.
Or in other words, as you have phrased it: if any of user or comp gets two consecutive wins, gets out from the loop.
Try replace with &&. You need both less that 2 to keep loop going on

Having trouble with || and &&

I am new to programming and wanted to make a dice rolling programm in Java for execise.
The code is the following:
import java.math.*;
public class Dices {
public static int dice1=0;
public static int dice2=0;
public static int x;
public static void main(String args[]){
do {
x++;
dice1=(int) (Math.random()*6+1);
dice2=(int) (Math.random()*6+1);
System.out.println(dice1+", "+dice2);
} while(dice1 !=1 || dice2 !=1);
System.out.println("Finalthrow: "+dice1+", "+dice2);
System.out.println("Snake-Eyes after "+x+" tries.");
}
}
This way it works fine, but in my opinion there is something wrong with the code. In the while condition should actually be. But if I use && it stops as soon as it rolls a 1 on the first dice. I thought && means "AND" and || means "OR". So actually it should behave exactly the other way around, or am I misinterpreting something?
Some understanding about Morgan's laws could help here. The law says (sorry for the weird syntax, but I think the message is clear) that :
(!P) OR (!Q) == !(P AND Q)
(!P) AND (!Q) == !(P OR Q)
So when you use || (OR) in your condition
while(dice1 !=1 || dice2 !=1)
is exactly the same as
while(!(dice1 == 1 && dice2 == 1))
so it will looop until both dice are 1.
On the other hand, if you use && (AND):
while(dice1 !=1 && dice2 !=1)
it's the same as
while(!(dice1 == 1 || dice2 == 1))
so it means that it will loop until one or two of the dice is/are 1.
&& means and
|| means or
So (dice1 != 1 || dice2 != 1) means continue the loop while dice1 is not 1 or dice 2 is not 1.
So (dice1 != 1 && dice2 != 1) means continue the loop while dice1 is not 1 and dice 2 is not 1.
The code is fine. You want the loop to end when dice1 == 1 and dice2 == 1. So it must loop until that is true, or until its opposite is false. The opposite of dice1 == 1 && dice2 == 1 is !(dice1 == 1 && dice2 == 1) which is equivalent to dice1 != 1 || dice2 != 1.
Think of it this way: if dice1 != 1, keep looping. Also, if dice2 != 1, keep looping. So if either is true, keep looping. And to test if either is true, regardless of if both are true, use ||.
The behavior is wright. You're saying with dice1 !=1 && dice2 !=1 that repeat the loopuntil BOTH of the dices are NOT 1. But when one dice rolls a 1 the condition is false and the loop escapes. Try it with a truth table.
Let's make a truth table.
What can we conclude from this? If you want your loop to continue while either A or B are different from 1 (or, as De Morgan's laws say: until both of them are equal to 1) then you can narrow it down to these values:
Since we need to find the operator that allows us to continue the loop (aka: the condition is true), we take the column that returns true for all 3 different kinds of inputs, which is A || B.
Note that A && B and A || B refer to the result of A != 1 and B != 1, not the actual input.

Categories

Resources