Java - AND operator not working - java

newbie here,
I have two variables which generate random numbers through .Random. I want them keep rolling until both variables generate two different values, simultaneously. Therefore, I'm using while loop with && for this purpose. As I have understood, please correct me if I'm wrong, the line while ((diceRolled1 != 5) && (diceRolled2 != 4)) translates as, keep rolling until the values of diceRolled1 is not equal to 5 AND diceRolled2is not equal to 4. But the program ends if either variable matches its value (diceRolled1 = 5 OR diceRolled2 = 4). This is not what && is supposed to do, right? I have ran the code like 10s of times, but not a single time it generated 5 and 4 at the same time.
I also tried ==on both sides and either side, but in that case the program didn't run at all, nor it gave any error.
Your help will be much appreciated. Thanks
import java.util.Random;
import static java.lang.System.out;
public class DiceRoller {
public static void main(String[] args) {
Random dice1 = new Random();
Random dice2 = new Random(); //Removing this doesn't work either
int diceRolled1 = 0;
int diceRolled2 = 0;
while ((diceRolled1 != 5) && (diceRolled2 != 4)) { //& didn't work either
diceRolled1 = dice1.nextInt(6) + 1;
diceRolled2 = dice2.nextInt(6) + 1;
out.println(diceRolled1 + " " + diceRolled2);
}
out.println("Program ends");
}
}

Your logic is incorrect. The loop will continue as long as both values don't match - as soon as one value matches, the loop exits. We can invert your logic to show this:
while (!(diceRolled1 == 5 || diceRolled2 == 4)) {
which is logically equivalent to what you have.
What you want is this:
while (diceRolled1 != 5 || diceRolled2 != 4) {
which says "Continue while any variable does not have the desired value"

You're getting the logical result you describe, but it wasn't what you expect. Specifically, when either of your conditions evaluates to false the logical and will not evaluate to true. I think you wanted
while (!(diceRolled1 == 5 && diceRolled2 == 4)) {
which is while not dice1 equal to 5 and dice2 equal to 4. And then, using De Morgan's Laws that might also be expressed as
while (diceRolled1 != 5 || diceRolled2 != 4) {
which means loop while dice1 is not equal to 5 or dice2 is not equal to 4.

the while execute the statement untill the condition is true.
In your code the condition is given by (diceRolled1 != 5) && (diceRolled2 != 4).
The && operator require true that all operands be true.
Given this Your loop will end when at least one of the expression will be false.
To finish the program when it generate 5 and 4 you have to use this:
(!(diceRolled1 == 5) && (diceRolled2 == 4))

Yeah,it should be. The program should end if dicerolled is either 5 or 4 because as far as it is not 4 and not 5 it is in while loop. It exits the while loop if only the value is either 4 or 5. So your logic is incorrect. Sorry! :)
Try:
while (!(dicerolled ==4 && dicerolled == 5))

Related

reading from a file wont read the first value Java

So i Have this code going on, I need it to open a file, and scan the two integers in the file, then I need it to store the two numbers. The numbers are restricted to between 1 and 10 for the first number and between 1 and 39 for the second number. I have a valueCounter to make sure that the correct number gets stored in the correct variable. For some reason, the code always returns
"Your Initial Fib is out of range, eneter # between 1-10"
Which would be appropriate if the first number was greater than 10 or less than 1, but regardless of what i change the first number to, the code returns the same line. The only time it wont return that line is when i change the 2nd number to to be between 1 and 10. So I can conclude that the code is skipping the first number, but i cant figure out why. Any being of higher intelligence that can help?
private static File inFile = null;
private static PrintWriter outFile = null;
private static int startValue;
private static int lengthValue;
public static void main(String[] args) throws IOException
{
inFile = new File( inFileName);
Scanner in = new Scanner (inFile);
outFile = new PrintWriter (outFileName);
int valueCounter = 1;
while (in.hasNextInt())
{
int value = in.nextInt();
if ( value <= 39 && value >= 1 && valueCounter == 2)
{
lengthValue = value;
valueCounter ++;
}
if ( value > 39 || value < 1 && valueCounter == 2)
{
System.out.println("You are asking for too many Fib, eneter # between 1-39");
in.close();
System.exit(1);
}
if ( value <= 10 && value >= 1 && valueCounter == 1)
{
startValue = value;
valueCounter ++;
}
if ( value > 10 || value < 1 && valueCounter == 1)
{
System.out.println("Your Initial Fib is out of range, eneter # between 1-10");
in.close();
System.exit(1);
}
}
}
It is because of operator precedence, the && is evaluated before the ||. This makes the following expression
if ( value > 10 || value < 1 && valueCounter == 1)
evaluated to true the second round, because first value < 1 && valuecounter == 1 is evaluated, which is false. Next, value > 10 is evaluated, which is true. Or-ing both results in true, and the body executes. Use parentheses to control the order of evaluation.
if ( value > 10 || value < 1 && valueCounter == 1)
Seems to be always true and since its a normal outer "if" at the end of code, its always being called. overthink your "if" and its appearance

Lambda expression to find of a number is composite or not

private static boolean isCompositeLambda(int number) {
return number > 3 && Stream.iterate(2, i -> i + 1)
.filter(x -> number % x == 0)
.limit((long) Math.sqrt(number))
.count() > 0;
}
When i give 5 it goes into infinite loop.
Can anyone give the correct code
You have two problems, the filter is applied first, and the second is the limit is the number of values, not the value it self.
It goes into an very long (but not infinite) loop because it take a long time to generate your limit of numbers. e.g. for 5 it tries to get 2 numbers ((long) Math.sqrt(5)) == 2L, however to achieve the first solution when number == x however it has to check another ~4 billion values before it overflows and reaches -number to get a second solution and the limit is reached. i.e. 5 % 5 == 0 and 5 % -5 == 0
A simpler solution is
private static boolean isCompositeLambda(int number) {
return number > 3 &&
IntStream.rangeClosed(2, (int) Math.sqrt(number))
.anyMatch(x -> number % x == 0);
}

I am writing a java program that uses one loop to process the integers from 300 down to 200

Here are my instructions:
Write a program that uses one loop to process the integers from 300 down to 200, inclusive. The program should detect multiples of 11 or 13, but not both. The multiples should be printed left-aligned in columns 8 characters wide, 5 multiples per line. When all multiples have been displayed, the program should display the number of multiples found and their sum.
int sum = 300;
while (sum >= 200 && sum <= 300 ) {
sum = sum - 1;
System.out.println( sum % 11 == 0 || sum % 13 == 0 );
}
As you may know, I am getting true and false responses rather than the numbers. I am very much stuck and would like any help or advice I can get! Thank you.
The problem is that the == operator is an equality operator that returns a condition (either true or false). That's why you're printing true and false. If you want to print the actual multiples, first check if they are either a multiple of 11 or a multiple of 13 (but not both), and then print the number, sum.
int sum = 300;
while (sum >= 200 && sum <= 300 ) {
if((sum % 11 == 0) != (sum % 13 == 0)) { //checks if sum is a multiple of 11 or 13 but not both
System.out.println(sum);
}
sum = sum - 1;
}
What (sum % 11 == 0) != (sum % 13 == 0) means is that if sum is a multiple of both 11 and 13, then the expression will equate to false because the results of (sum % 11 == 0) and (sum % 13 == 0) are both true. Similar reasoning will let you see that if sum is only a multiple of one of 11 or 13, then the expression will result in true since one side of the expression will result in true while the other side will result in false.
Since this looks like homework, I don't want to just give the answer away, but I'd like to help, so I'll give you a couple of hints:
1) "if" statements are where you'd want to use comparisons to decide what to do, e.g.
if (blah == more_blah)
2) Since your numbers are all guaranteed to be 3 characters, there is a simple and easy way to get the exact spacing of 8 characters per column. (Hint: print() and println() are both things)
3) Since you want multiple columns, you might want some way to check how many columns you have already and then decide whether you want println or print. (bonus hint: using System.out.println("") could make your code simpler.)

Write a program in java to print the sum of all numbers from 50 to 250(inclusive of 50 and 250) that are multiples of 3 and not divisible by 9

/* when I run this code there is no error in fact output generated is also correct but I want to know what is the logical error in this code? please can any one explain what is the logical error. */
class abc
{
public static void main(String arg[]){
int sum=0;
//for-loop for numbers 50-250
for(int i=50;i<251;i++){
// condition to check if number should be divided by 3 and not divided by 9
if(i%3==0 & i%9!=0){
//individual number which are selected in loop
System.out.println(i);
//adding values of array so that total sum can be calculated
sum=sum+i;
}
}
//final display output for the code
System.out.println("the sum of intergers from 50 to 250 that are multiples of 3 and not divisible by 9 \n"+sum);
}
}
My philosophy is "less code == less bugs":
int sum = IntStream.rangeClosed(50, 250)
.filter(i -> i % 3 == 0)
.filter(i -> i % 9 != 0)
.sum();
One line. Easy to read and understand. No bugs.
Change this:
if(i%3==0 & i%9!=0){
to this:
if(i%3==0 && i%9!=0){
& = bitwise and operator
&& = logical operator
Difference between & and && in Java?
The only problems I saw were:
The variable sum was undeclared
Use && in place of &
int sum = 0;
for (int i = 50; i <= 250; i++) {
if (i % 3 == 0 && i % 9 != 0) {
System.out.println(i);
sum = sum + i;
}
}
System.out.println("the sum of intergers from 50 to 250 that are multiples of 3 and not divisible by 9 \n" + sum);
Well, instead of touching every single value from 50 to 250 like you would do here for(int i=50;i<251;i++), you can consider something like this...
int i = 48;
int sum = 0;
while(i < 250) {
i += 3;
if(i%9 != 0)
sum += i;
}
This is somewhat optimized in the sense that I am skipping over values that I know are not possible candidates.
But, there is a much bigger issue in your code. The following code block prints true, sure. But, it is a bad idea to depend on the & since that is not its job. The & is for bitwise AND whereas the && is for logical AND, which is what you are trying to do.
boolean t = true;
boolean f = false;
System.out.println(f&t);
Why?
In Java, if it is a && operation, as soon as you find the first false, you are sure that the expression will evaluate to false. Meanwhile, in your implementation, it would need to evaluate both sides. f&t will evaluate to false, but the JVM would need to look at both the f and t variables. Meanwhile, on using &&, it wouldn't even need to look at the t.

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