I am programming a Pit scoring system and I have a piece of code that looks like this:
while(highestConverted<scoreConverted||highestConverted!=scoreConverted)
It will always return true and repeat the code within it regardless of the value of scoreConverted or highestConverted. I don't think it really matters but both values or ints which are converted from scanner variables using Integer.parseInt . I don't have that much experience with Java but I do know some of the basics.
Consider your code:
while(highestConverted<scoreConverted||highestConverted!=scoreConverted)
Let's suppose highestConverted = 5 and scoreConverted = 2.
highestConverted < 2 = 5 < 2 -> false
highestConverted != 2 -> 5 != 2 -> true
false || true = true.
So the while loop will always repeat.
It should be
while(highestConverted<scoreConverted && highestConverted!=scoreConverted)
Or, better
while(highestConverted<scoreConverted)
highestConverted<scoreConverted implicitly includes highestConverted!=scoreConverted as it will stop at scoreConverted - 1.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 months ago.
Improve this question
hello i wanted to know why contain is not working and how to make it work. my Goal is to be able to print out false if it has 2 or 3. i am not sure if i am doing it correctly or if i'm on the right track.
public class Assignment7 {
public static void main(String[] args) {
int[] array0 = {3, 5, 6};
System.out.println("Your implementation of no23 method printed out: " + no23(array0) );
}
public static void no23(boolean array0){
int number = 2;
int numberB = 3;
int theNumbers = number & numberB;
boolean statemnt = array0.contains(theNumbers);
}
}
You have multiple problems.
Arrays have no contains method
array0.contains(theNumbers)
You cannot call contains on an array. Arrays have no such method.
There are several ways to search an array in Java. If your array is sorted, use Arrays.binarySearch.
Ampersand (&) flips bits
Your use of & is not doing what you think. That operator manipulates bits. See The Java Tutorials by Oracle.com, free of cost.
What you meant to do was create a collection of int values. To do that use an array or use a Collection object such as List or Set. See The Java Tutorials by Oracle to learn about the Java Collections Framework.
Solution
Use a pair of vertical bars for a logical OR operator. Returns true if either or both conditions are true. See The Java Tutorials by Oracle.
int[] arr = { 3, 5, 6 } ;
int x = 2 ;
int y = 3 ;
boolean arrayContainsEitherNumber =
( Arrays.binarySearch( arr , x ) < 0 )
||
( Arrays.binarySearch( arr , y ) < 0 )
;
Get fancy with streams.
int[] arr = { 3 , 5 , 6 };
boolean hit =
Arrays
.stream( arr ) // Returns an `IntStream`, a series of each `int` value in the array.
.filter( i -> ( i == 2 ) || ( i == 3 ) ) // Skips any elements not meeting our criteria.
.findAny() // Halts the stream when first element reaches this point.
.isPresent(); // Returns true if the payload of this optional exists, false if no payload.
System.out.println( "hit = " + hit );
hit = true
Declare a return type
As commented by Dawood ibn Kareem, your method neglected to return the result to the calling code.
Change the void:
public static void no23( boolean array0 ) { … }
… to boolean and return your result:
public static boolean no23( boolean array0 ) {
…
return statemnt ;
}
You may detect a theme in this Answer: Study The Java Tutorials by Oracle before posting here.
I don't understand your question very well, but theNumbers is always equal to 00000010 & 00000011 = 00000010 = 2.
& operator is not the same as the && operator. The first one takes two numbers in binary form, and performs an AND operation like shown above.
2 in binary = 00000010
3 in binary = 00000011
2 & 3 is 00000010 & 00000011 which is 00000010
The second takes two booleans, and returns true if both are true, else returns false.
Effectively, your function is just checking if your array contains the number 2. If you want to check if there is either the number one (1) or the number two (2), you need to do :
public static void no23(int[] array0){ // Also, should be an array
boolean containsTwoOrThree = array0.contains(2) || array0.contains(3);
System.out.println(containsTwoOrThree); // Will print either true or false
if(containsTwoOrThree) System.out.println("Contains two or three");
else System.out.println("Doesn't contain");
// Simple java arrays do not have a "contain" method.
// Either use Java Lists, or use a for loop to check for values in.
}
EDIT: Arrays in java don't have a contains function. Check this answer:
How do I determine whether an array contains a particular value in Java?
boolean riddle = !( 1 < 8 || (5 > 2 && 3 < 5));
boolean is a true or false.
! = not
|| = or
&& = and
but I still dont understand this syntax... can someone explain me what this syntax excactly does?
Just dissect it:
There are some comparisons such as
5 > 2 ... true
3 < 5 ... true
Those two are pulled together using &&; so true && true --> true
1 < 8 ... true
That one is or'ed to the rest; so we get true or true --> true
Finally, not (true) --> false
Long story short: if you don't understand the whole picture, break it down into the parts you understand; and then pull those together again.
Edit: and of course, the order I am using in my explanation isn't what happens in reality. There, 1 < 8 is evaluated first; and as that is true; and "true or X" is always true, the other comparisons are not even computed.
The not ! operator negates what it is in front of. In this case !() it will produce the opposite of the what is inside of the parenthesis.
the || or operator checks to see if one condition or the other is true. At least one must be true for the condition to return true.
Finally the && checks both sides of the conditional statement to see if they are both true, and both of them must be true to proceed.
boolean riddle = !( 1 < 8 || (5 > 2 && 3 < 5));
Let's parse it the way Java does :
boolean : Here comes a boolean, i.e. true or false.
riddle : The variable riddle is declared to be a boolean.
= : The boolean variable riddle is initialized with the expression on the right.
!(...) : It returns a boolean, the negation (=opposite) of the boolean inside of the parentheses.
Inside the parentheses is a bool1 || bool2 expression, where || is a "lazy OR" operator. If bool1 is true, there's no need to evaluate bool2.
bool1 is 1 < 8, which is true.
bool2 isn't evaluated
bool1 ||bool2 is true
!(...) is false
riddle is initialized with false
At no point in time are 5 > 2 or 3 < 5 evaluated. Eclipse warns that those 2 expressions are "dead code" and could be removed.
The whole expression could be :
boolean riddle = !( 1 < 8 || (5 > 2 && doSomethingVeryDangerous()));
the result would be the same and no method call would happen at all.
The problem that you have is that you initialize at the same time as you are checking if it's true or false. You cannot compare boolean with integer. If you want to do it then you need to solve it in another way by converting from one datatype to another, or involve another variable in your solution. The way you need to solve your syntax problem is by dividing it like this:
How you did it...
boolean riddle = !( 1 < 8 || (5 > 2 && 3 < 5));
How to potentially solve it...
boolean riddle;
"...some code to decide if riddle will be true or
false and assign it to the variable riddle..."
if (riddle == true){
"...do some code here...";
}
if (riddle == false){
"...do some code here...";
}
Or you can solve the problem by not using boolean as datatype and instead only use integers like this...
int riddle;
"...some code to decide what value riddle will
have and assign it to the variable riddle..."
if ( riddle < 8 && riddle > 1){
"...do some code here...";
}
I am trying to do in Java:
int i=5;
while(i-- >0) {
System.out.println(i);
}
When running this program the output is:
4
3
2
1
0
I am very surprised to see 0 in output. I am new in development. Can anyone justify this?
In your while condition i-- > 0, the variable i is evaluated first and then decremented.
When i reaches the value 1, it will pass the loop test and then get decremented to 0. This is why the print statement shows 0 in the output.
Here is a mnemonic you can use to keep track of how the decrement and increment operators work:
int i = 5;
System.out.println("When i = 5 then:");
System.out.println("i-- is " + i--);
i = 5;
System.out.println("--i is " + --i);
Output:
When i = 5 then:
i-- is 5
--i is 4
Simply, because you compare i>0 and decrement i afterwards.
// If I is 1, you compare 1>0 and decrement i afterwards.
// This is how the postdecrement operator works
while(i-- >0) {
System.out.println(i);
}
the loop will behave like the following.
is i=5 > 0?
decrement i to 4
output i = 4.
is i=4 > 0?
decrement i to 3
output i = 3.
...
and so on
As you can see the value you compare to 0 is allways higher then the one you are outputing. This happens due to how the -- operator works. If it´s preceding to the i as --i it will decrement the variable i first and return it´s value afterwards. If it´s not preceding as in your case i-- you will have the value of i returned first and i beeing decremented afterwards.
Postdecrement/Increment operator works on the principle "Use first and then Change"
Initially value of i=5, when it enters while loop it will compare value of i first and then it prints the decremented value. Here i will show you each iteration along with checks performed in each iteration,
Now value of i=5(in memory), inside while(5>0), it prints 4.
Now value of i=4(in memory), inside while(4>0), it prints 3.
Now value of i=3(in memory), inside while(3>0), it prints 2.
Now value of i=2(in memory), inside while(2>0), it prints 1.
Now value of i=1(in memory), inside while(1>0), it prints 0.
Hope now you are clear to go ahead. Gud Luck.
The post-decrement operator -- is like a post-paid service. Like a credit card, first you use, then you pay.
I thought I can give you a real-life idea of what really is occurring in this statement, when i == 1
while(i-- >0)
So, first you check if i(1)>0. 1>0 So, yes it is. Right after this statement is done, i becomes 0. Then, you print that value.
Alternatively, you might also get this intuition by noticing that although your loop started with i=5, the value 5 never got printed.
Since you are using the post-decrement operator in the while loop, when i is 1, i-- returns 1, and then inside the loop you get 0 when you print i for the last time.
Only because of post decrement operator (i--) will check the condition first then decrease the value of i. Output is giving such. Thank you
int i=5; //initialize with 5
while(i-- >0) { //post decrements operator so, check condition first then decrease the value.
System.out.println(i);
}
In first iteration of while loop will check 5 > 0 will be checked after that decrease the value of i and i will become 4 So, Print it 4 not 5.
When i = 5 conditional statement will be (5>0) (true) and print 4.
i = 4 conditional statement will be (4>0) (true) and print 3.
i = 3 conditional statement will be (3>0) (true) and print 2.
i = 2 conditional statement will be (2>0) (true) and print 1.
i = 1 conditional statement will be (1>0) (true) and print 0.
Now, i became 0 so conditional statement will be (0>0) (False).
So, loop exits.
To get desired output try this
while(--i >0) {
System.out.println(i);
}
Is following true in java:
In java if you use || then after getting first true condition it neglects the rest conditions. That is If you write if(a || b || c) in java and java finds a is true then it will not check for b and c, just go into the if case.
Yes this is called short circuiting, if you put less expensive checks to the left you might avoid the expensive ones to follow.
This works for || and &&
one of the best uses is checking a value from an object that might be null:
if(myList != null && myList.size() > 6)
the previous line is null safe, reversing the condition will cause a null pointer exception in case myList is null
This is correct. || is called short-circuit OR evaluation, or an OR-ELSE operator.
This is important in situations when evaluating the right-hand side may cause an undesirable consequence:
if (myString == null || myString.indexOf("hello") != -1)
...
would crash if it were not for short-circuiting.
Yes, This way the compiler avoids unnecessary checking and calculation overhead.
That's correct, and that's not just laziness on part of the language implementation, but rather it is a crucial feature - short-circuiting allows you to write something like this:
if (myarray.length > 10 && myarray[10] == 5) { /* ... */ }
Here the second condition may only even be evaluated if the first one is true. Thanks to short-circuiting, if the first condition is false the second is never touched.
YES
(AFAIK)
The same things applies to && but in reverse manner.(for first false).
The same rule as in circuits for AND and OR gates.
Yes, it's called short-circuiting. It also will short circuit &&, i.e.
if (a && b && c)
If a is false then the condition cannot be true, neither b nor c are checked.
This can be problematic if you call methods that return booleans. To get around this, you can use bitwise & and |.
Yes it is correct. If you use | this operator to check OR condition then it checks rest all conditions. It also applied on AND(&) operator.
Yes, and one important thing, if you do any operations in the second part, they will not be made. For example:
int a = 5;
int b = 5;
if ( a == b || a++ == b){
...
}
//a = 5
//b = 5
BUT in case:
int a = 3;
int b = 5;
if ( a == b || a++ == b){
...
}
//a = 4
//b = 5
I tried to make a simple example, but sometimes you call a method in the second part, (which will not be called if first part was true in case of ||), or the first part was false in case of &&
I'm trying to build an array of prime numbers in Java.
if(c % 2 != 0 || c % 3 != 0 || c % 5 != 0) {
n.add(c);
}
But my program seems to ignore the condition and just adds every number to my list.
But if I just use one condition for example,
if(c % 2 != 0)
The code works perfectly in ignoring any number which is a multiple of 2. What am I missing here?
You need to use logical and (&&) instead of or(||), as you want all conditions to be true before adding.
With logical or, each condition is evaluated from left to right, until finding one that matches.
Your condition right now evaluates to true if the number is not divisible by any of (2,3,5). This holds for all numbers except multiples of (all of) 2, 3, and 5. Try logical and (&&) instead of logical or (||).