I have tried to do this in java however the && symbols keep on giving error.
Below is the code that I used:
int d = 18;
{
if ((d % 2) && (d% 3));
{
System.out.println("True!");
}
{
System.out.println("False!");
}
}
This is my code. I am not sure why its not working. Thanks
The error message is The operator && is undefined for the argument type(s) int, int. #
I have got it to work now. I have an else error . "The error says Syntax error on token "else", delete this token"
public class CS1702_Lab3_4 {
int d = 18;
{
if ((d % 2 == 0) && (d % 3 == 0));
{
System.out.println("True!");
}
else
{
System.out.println("False");
}
}
}
Also when I add an else it says Syntax error on token "else", delete this token
Please learn about the modulus operator, and how to check divisibility in java.
if ((d % 2 == 0) && (d % 3 == 0))
{
System.out.println("True!");
}
Also, you had a rogue semi-colon at the end of your if statement.
EDIT: Fixed code
public class CS1702_Lab3_4 {
public static void main(String[] args) { // Entry into our program
int d = 18;
if ((d % 2 == 0) && (d % 3 == 0)) {
System.out.println("Divisible!");
} else {
System.out.println("Not divisible!");
}
}
}
I'd recommend looking at some basic Java tutorials, however the fixes I applied included:
Contained your code inside of a method, specifically the main method, which is the entry point to a runnable Java application. Java is not a procedural language, code outside of variable, method, class, package and import declarations need to be contained inside of a method
Fixed syntax on your if statement, removed rogue semi colon
if ((d % 2) && (d% 3)); you have a semicolon ; at the end,
remove it.
If d == 18, then ((d%2) && (d%3)) = (0 && 0) = 0 So in this
case, What java sees is: if(0){ // ... }
If I remember correctly, this is valid in C/C++, but not in Java. That is why you get error.
Anyways, to fix the problem, you can do this:
if (((d % 2) == 0) && ((d % 3) == 0)){
System.out.println("Divisible!");
} else {
System.out.println("Not divisible!");
}
if condition expects boolean. Mod operation would not return boolean, this is why compiler is intelligent and gives you this error.
if you try to run
if (1 && 2) // this will give you an error as well.
The expressions need to evaluate to a boolean (either true or false) in order to understand operators like && and ||
Moreover, you statement will not work since you are using ; at the end.
Related
Convert the following without if/loops. You can still use recursion, &&, || etc...
public boolean mystery(int n){
if(n == 0){
return false;
}
if(n%10 == 7){
return true;
}
return mystery(n/10)
}
I would like hints.
But I've been experimenting around.
We know that true && false == false and only true && true == true
So we must have that
return (n%10 == 7) && ....
Then for the second part, we could either get true or false, and if the second part is true, then our first part being true will result in everything being true, so I am thinking.
return (n%10 == 7) && ...
But I am thinking an issue might be that if n%10 isnt 7 right off that bat everything is false.
In my view, the ternary operator is still pretty much an 'if' statement - but that becomes a semantic debate. You can avoid using it entirely.
return (n % 10 == 7) || (n != 0 && mystery(n/10));
There are many ways: but to give you a start:
if(n == 0){
return false;
}
if(n%10 == 7){
return true;
}
return mystery(n/10)
}
is equivalent to
return n==0 ? false : n%10==7 ? true : mystery(n/10);
is equivalent to
return n!=0 ? n%10==7 ? true : mystery(n/10): false;
is equivalent to
return n!=0 && n%10!=7 ? mystery(n/10) : n!=0;
Was an interesting activity to solve. Solution below with proof of testing till 10k. mystery2 is the method of interest for you.
How I got the solution:
Started printing the results from 0 to 100 and identify the pattern - found the ones starting or ending with 7 would return true and all others false. The first if block which compares with zero is actually encountered by all the numbers which do not qualify reminder 7 rule in any position. Thus, reminder 7 is the only condition to get true result and everything else would enter recursion until it becomes 0 after the unit's position is complete. Equating to 0 is required as we should have a condition that ends the recursion (or ends in StackOverflowException).
public static void main(String[] args) {
for(int i = 0 ; i<=10000; i++){
if(mystery(i) != mystery2(i)){
System.out.println("Mismatch... "+i);
}
}
}
static boolean mystery(int n) {
if (n == 0) {
return false;
}
if (n % 10 == 7) {
return true;
}
return mystery(n / 10);
}
static boolean mystery2(int n) {
return n % 10 == 7 || (n != 0 && mystery2(n / 10));
}
I'm working on a project for school that requires me to move a robot. How far the robot will move each second (variable t) is calculated by the function below.
The first function is easy. The 2nd and 3rd on the other are where I'm stuck. How would I write F(t-1)? Below is what I have so far.
if (t == 0) {
distance = 2;
} else if (t > 0 && <=6 || t > 12) {
// No clue on how to write the 2nd distance equation.
} else if (t >= 7 && <=12) {
// No clue on how to write the 3rd distance equation.
}
Recursion really isn't necessary to solve this.
Note that in each of the non-zero time cases, F(t) = F(t-1) + something.
So you can simply do:
double f = 2; /* Initial value at t=0 */
for (int t = 1; t <= maxT; ++t) { // maxT is the maximum value of t.
if (t <= 6 || t > 12) {
f += /* something for case 2 */;
} else {
f += /* something for case 3 */;
}
}
System.out.println(f);
You can do this with recursion, but you will get a StackOverflowError if maxT becomes modestly large; by contrast, using a loop will work for arbitrarily large maxT (modulo floating point errors).
As pointed out by #Andreas, you can do this without looping over all values of t:
double f = 2 * (maxT + 1);
for (int t = 7; t <= maxT && t <= 12; ++t) {
f += log(t) - 2;
}
and you can eliminate that loop too by precomputing the values.
This is a problem which involves the use of recursion. By and large, pay close attention to the notation Ft-1, since that refers to an evaluation of the specific function at t-1.
I won't write out all of the code, but I'll give you some of the basics:
When t = 0, return 2. This is your base case.
When t is between 0 and 6 inclusive or greater than 12, return an evaluation of the function at t-1 and add 2.
When t is between 7 and 12 both inclusive, return an evaluation of the function at t-1 and add log2(t).
Here's something to get you at least started in the right direction.
public double evaluateDistance(int t) {
if(t == 0) {
return 2;
} else if(t > 0 && t <= 6) || (t > 12) {
// Think about this - it would involve another call to evaluateDistance, but what is t again?
} else if(t >= 7 && t <= 12) {
// Another evaluation involving the function.
// For free, the change of base operation you'll need to get base-2 evaluation for the log:
return ??? + Math.log(t)/Math.log(2);
}
}
Think I figured it out. Sorry if I wasn't clear on what I needed, just needed to figure out how to write the equations in the function. Think I figured it out though.
public double move()
{
int t = 0;
if(t == 0) // After the first second, robot moves 2
{
distance = 2;
}
else if(t > 0 && t <= 6 || t > 12) // From seconds 0 to 6 and after 12, robot moves distance equation
{
distance = (2*t)+2;
}
else if(t >= 7 && t <= 12) // From seconds 7 to 12, robot moves distances equation
{
distance = (2*t)+(Math.log(t)/Math.log(2));
}
position = position + distance;
return position;
}
}
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))
here is what i tried. it says second operand is boolean whereas first is long. so & operator is undefined for long and boolean .
public static void powerOfTwo(long a){
if(a & (a-1) == 0 )
System.out.println("it's a power of two");
else
System.out.println("NOT a power of two");
}
You have to wrap the expression in extra parenthesis:
public static void powerOfTwo(long a) {
if ((a & (a - 1)) == 0)
System.out.println("it's a power of two");
else
System.out.println("NOT a power of two");
}
That's because the operator == takes precedence over & (see here), so without the braces, you have
a & (a - 1) == 0
which is the same as
a & ((a - 1) == 0)
and then the compiler complains about comparing a long (a) with a boolean (a-1 == 0)
You can use
return a != 0 && ((a & (a-1)) == 0);
however this is obscure. A simpler way is
return Long.bitCount(a) == 1
This is not entirely obvious either but having exactly one bit set means it must be a power of 2.
what is the java syntax for saying
if x is not equal to a or b
I am trying to write an if else statement .. if a certain value is not equal to say 2 or 3 then do something else do something else :) thats confusing lol
Try this:
if (x != a && x != b) {
// Something (action x)
} else {
// Something else (action y)
}
Note that it's an "and" condition even though you're asking whether x is equal to a or b because each condition is negative. The other way you could represent this (if you find it more readable) is:
if (!(x == a || x == b)) {
// Something (action x)
} else {
// Something else (action y)
}
And at that point you may find it more readable still to get rid of the negation, but switch round what you do in the blocks:
if (x == a || x == b) {
// Action y
} else {
// Action x
}
These three blocks of code all do the same thing, but I think I'd find the bottom one the most readable as the condition is simple.
if ((x != a) && (x != b)) {
// do stuff
} else {
// do other stuff
}
if( x != a && x != b )
Notice it's an &&, not an ||
The condition ( x != 2 || x != 3 ) is always true: if x = 2, then x != 3 and the condition is true. if x = 1, then x != 2 and the condition is true.
What you're really saying is: if x is not one of 2 or 3, which is, x is not in the array [2,3], which is "x is not 2 neither 3", which is x != 2 and x != 3.
directly mimics the english sentence: if x is not equal to a or b
if (!(x == a || x == b))
{
doSomething();
}
else
{
somethingElse();
}
but if the extra not operator and parentheses hurts your eyes, use this(note the absence of the word Or in this condition, not anymore parallel with english sentence):
if (x != a && x != b)
{
doSomething();
}
else
{
somethingElse();
}
see my answer on programmer's ignorance pet peeve and Is it acceptable to only use the ‘else’ portion of an ‘if-else’ statement?, why i advocate constructing simple conditions(directly mimics english sentence, i.e. without sticky ANDs and too much NOTs)
if(x!=a && x!=b){
//do...
}
in java if-else is a control statement which is used to test condition and transfer the control based on the evolution of condition.
if((x!='a')||(x!='b'))//if a,b is char use quotes else avoid
{
//if expression is true
}
else
{
//if expression is false
}
if you want that code should be executed when x=a and x=b both then use '&&' instead of '||'.
For more details:
http://java.meritcampus.com/t/60/If-else-if-ladder?tc=mm70