Java - Multiple Boolean Conditions - java

I have this problem: I want to check if an int is bigger than 10, if not than if he is bigger then 100..and so on.
Is there a better way than just doing this:
public void multipleIf(int x){
if(x > 10){
...
} else if(x > 100){
...
} else if(...
}
Thanks.

A number that is greater than 100 is always greater than 10.
If you want only numbers in the range 10-100 exclusive, you can use operators. You could test for a number that is greater than 10 but less than 100 by using logical operators:
if(x > 10 && x < 100) {
/* Body */
} else if(x > 100 && x < ....) {
/* Body */
}
The && is a logical AND operator that checks if both conditions are true. So, it checks if x is inside the range, exclusive.
If you want only numbers greater than 100, use separate if statements.
You can also use a switch statement.

Actually, if you know what your limit is (say 10,000), you can simply start from the top.
if(x > 10000)
....statement 1
else if (x > 1000) // using this else here is important
....statement 2
else if (x > 100)
....statement 3
else if (x > 10)
....statement 4
The else is important because it only executes if the previous if (or else if) is not executed (the statement is false). Thus we can see that statement 1 executes for any x greater than 10,000. If it's not greater than 10,000, but greater than 1000, then statement 2 executes. If x is not greater than 1,000, but greater than 100, then statement 3 executes. And at the end, depending on your code, you can just put an else statement somewhere.

Related

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);
}

40 If-Statements in a Loop, How to Avoid?

I am working with the library JInput to detect controller input in a java game. However, in order to get the direction the axis is moving, I use this:
gamePadContr.getComponent(Identifier.Axis.X).getPollData();
This gives me a decimal between -1 and 1, which tell the direction. I want the player to be able to move in more than just up, down, left, and right, so there are 40 if statements in my gameloop that check if the number is a certain set of numbers, and increasing the x and y coordinates accordingly. Here is an example:
if(x > .1 && x < .2 && y == 1){
// do stuff
} else
if(x > .2 && x < .3 && y == 1{
// do stuff
}
I have to check each one to make sure that most directions are accounted for.
My point is, 40 if statements is lagging. Is there anything I can do to optimize this?
A few edits to answer questions:
Didn't think it was relevant, but the reason increments of .1 have 40 different if statements is because I am checking the X and Y axis of the joystick. The possible combinations are (1, -1) (1, 1) (-1, 1) (-1, -1), giving me negatives and positives in 40 different combinations at increments of .1. (I don't know if that made sense.
//do stuff is just increasing the x and y coordinates of the player by certain amounts.
The best approach might be to discover a rule whereby you can directly compute the player's coordinate change directly from the joystick coordinates. For that, we would need details of what // do stuff is for each branch.
Another possibility, which is good if you don't have a simple relationship, is to convert your tests to a look-up by transforming the x and y values to array indexes
int xIndex = (int) (10 * x + 10); // an int between 0 and 20
int yIndex = (int) (10 * y + 10); // ditto
Then you can look up the player's coordinate changes in a 2-D array that you compute once ahead of time. More generally, you could have an array of Runnable objects, look up the appropriate Runnable based on the indexes, and run() it.
P.S. If each joystick coordinate can fall into any of 20 different ranges, then you have 400 cases, not 40. That is, unless you are always ignoring one or the other of the axes.
One thing you can do is nest your conditions. Instead of
if (x > .1 && x < .2 && y == 1){doStuff();}
else if (x > .2 && x < .3 && y == 1){doStuff();}
else if (x > .1 && x < .2 && y == 2){doStuff();}
else if (x > .2 && x < .3 && y == 2){doStuff();}
you may want to consider:
if (y == 1){
if (x > .1 && x < .2){doStuff();}
else if (x > .2 && x < .3){doStuff();}
}
else if (y == 2)
{
if (x > .1 && x < .2){doStuff();}
else if (x > .2 && x < .3){doStuff();}
}
Now your code can skip all the if checks that it knows aren't true. Instead of having to check up to 20*20 = 400 if statements, the program only has to check up to 20+20=40 if statements in any given loop. You will still HAVE a ton of if statements - in fact, you'll have slightly more than you had before - but 90% of them will be skipped, and they'll each be shorter, so the program will run faster.
You can also reduce the number of checks in each if statement with clever ordering. If you already checked x < .5 and it was false, then you already know that x < .4 is false. For example:
if (y == 1){
if (x > .9 ){doStuff();}
else if (x > .8){doStuff();} // no need to check if it's less than .9 since the previous line covered that case
}

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.

I have a program that calculates the first 200 prime numbers, but I do not understand a formula in it

I need to write a code which should calculate the first 200 prime numbers, but I can't hand it in as long as I can't explain everything. I used a piece of code from the internet as reference (http://crab.rutgers.edu/~dhong/cs325/chapter3/PrimeNumber.java).
Whole code:
public class Opdracht3 {
public static void main(String[] args) {
int limiet = 200;
int counter = 1;
int testpriem = 3;
boolean isPriem;
while (counter <= limiet) {
isPriem = true;
for (int i = 2; i <= testpriem / 2; i++) {
if (testpriem % i == 0) {
isPriem = false;
break;
}
}
if (isPriem) {
System.out.println(counter + ": " + testpriem);
counter++;
}
testpriem++;
}
}
}
Below part of code verifies if the number is a composite. If testpriem is composite, then comes out of the loop and starts over. Otherwise, it continues and prints the prime number testpriem.
The problem is here:
for (int i = 2; i <= testpriem / 2; i++) {
if (testpriem % i == 0) {
isPriem = false;
break;
}
}
I tested what happens to i, and one way or another it recognizes the divisor needed to calculate the composite. (With 4 divisor is 2, with 9 divisor is 3, with 221 divisor is 13) But I am flabbergasted as of why.
Any ideas?.
the % or ("remainder") operator in Java divides one operand by another and returns the remainder as its result. And of course if integer x is evenly divisible by another integer y (meaning x/y = some integer z with a remainder of zero), then x can not be prime.
First remember every number able to divide by its half or less. Consider number 7 it is possible divided by 1,2,3 because after 3, if try to divide number by 4 means 4x2 = 8 that is greater than 7. so it is optimum way to find divisor in this way. One more thing every number divided by 1 and number itself. so if number number is divided by 1 or itself then it is called prime so i starts from 2.
now consider testpriem =7 so you will get loop like
for (int i = 2; i <= 7 / 2(i.e 3); i++)
{
if(7 % i == 0)
{
isPriem = false;
break;
}
so first time it checks 7%2=1 so condition false. again check for 7%3 = 1 again condition false. and now this condition full fills here i <= 7 / 2(i.e 3) so loop stopped and it result 7 number is prime
Well, if testpriem % i == 0, it means that i divides testpriem, which means that testpriem is not a prime a number and i, is its first divider. % is the modulo operation, which is the rest of the division.
https://en.wikipedia.org/wiki/Modulo_operation
The break stops the for loop and moves to the next position in the while loop. So it does not restart the for loop for the current tested number.
The break is used for efficiency reasons. You could remove it and the algorithm would still work correctly but slower.

Categories

Resources