How to remove the amounts of ifs from the application? [closed] - java

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 last month.
Improve this question
The code I say has to complete these assignments:
Given an integer,N, perform the following conditional actions:
If N is odd, print Weird
If N is even and in the inclusive range of 2 to 5 , print Not Weird
If N is even and in the inclusive range of 6 to 20 , print Weird
If N is even and greater than 20 , print Not Weird
Complete the stub code provided in your editor to print whether or not N is weird.
My code looked like this:
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int N = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
scanner.close();
int Numberparorimpa = N % 2;
if(N < 2 || Numberparorimpa ==1 || N <=20 && N >=6 ){
System.out.println("Weird");
}else{
if(N >=2 && Numberparorimpa == 0){
System.out.println("Not Weird");
}else{
if(Numberparorimpa == 0 && N >=6 || N<=20){
System.out.println("Weird");
}else{
if(Numberparorimpa== 0 && N> 20){
System.out.println("Not Weird");
}else{
return;
}
}
}
}
}
}
How can I reduce the IFs of this code?

I think an optimize version could be this :
if (N % 2 == 1 || (N >= 6 && N <= 20)) {
System.out.println("Weird");
}
else {
System.out.println("Not Weird");
}
If N is odd or N in range of 6 to 20 it's weird.
Else N is either even or not in the range so it's not weird.

You can reduce the complexity and improve the readability of your code by extracting your logic to method/class etc. Also, nested conditions are hard to read, you should avoid it.
Example:
public static void main(String[] args) {
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
scanner.close();
String print = isGivenNumberWeird(n) ? "Weird" : "Not Weird"
System.out.println(print);
}
private static boolean isGivenNumberWeird(int n) {
boolean isOdd = n % 2 == 1;
if (isOdd) {
return true;
}
if (n >= 2 && n <=5) {
return false;
}
if (n >= 6 && n <=20) {
return true;
}
if (n > 20) {
return false;
}
}

Related

Find the binary equivalent of integer in Java using a while loop

I'm new to Java. I've been writing code to find the binary equivalent of an integer in Java using a while loop. I've written the following code and it's not throwing any error, but it was not printing INVALID INPUT. It is printing the valid binary number of a given integer value. Can anyone suggest where and what I'm doing wrong? And how should I get the proper input?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if ((n >= 0) && n > 999) {
System.out.println("Invalid Input");
} else {
while (n > 1) {
if (n <= 999) {
System.out.println(Integer.toBinaryString(n));
break;
}
}
}
}
}
Change && to ||:
if (!(n >= 0) || n > 999) {
Or even better, express conditions without negation:
if (n < 0 || n > 999) {
Positive conditions, ie "a is b", are easier to read.
Why are you using a loop at all? You're just adding needless complexity. Your code can be re-written to this:
if (n >= 0 && n < 1000) {
System.out.println(Integer.toBinaryString(n));
return;
}
System.out.println("Invalid Input");
You haven't said if this is an assignment but typically it is done like this for such questions.
loop until value is 0
get remainder from division by 2.
prepend to string
divide n by 2 to expose next binary digit.
// get some input,
int n = 1249;
String s = "";
while(n != 0) {
s = (n%2) + s;
n/=2;
}
System.out.println(s);
prints
10011100001

What is my mistake in this problem. Simple Comparison Error [closed]

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 3 years ago.
Improve this question
Task
Given an integer, n, perform the following conditional actions:
If n is odd, print Weird
If n is even and in the inclusive range of 2 to 5 , print Not Weird
If n is even and in the inclusive range of 6 to 20, print Weird
If n is even and greater than 20, print Not Weird
I have written a code but it is showing error in printing 18 and 20.
public static void main(String[] args) {
int N = scanner.nextInt();
scanner.close();
if(N%2 != 0){
System.out.println("Weird");
}
else if(N%2 ==0 && N>=2||N<=5)
{
System.out.println("Not Weird");
}
else if(N%2 ==0 && N>=6||N<=20)
{
System.out.println("Weird");
}
else if(N%2 ==0 && N>20)
{
System.out.println("Not Weird");
}
}
}
You need to change your or condition || to and condition && to check for the range like
else if(N%2 == 0 && N >= 2 && N <= 5)

FizzBuzz: It gives me the wrong print statement. What is wrong?

Everybody knows that FizzBuzz question that interviewers ask students.
Basically, when you have an incrementor and for each number which is a divisible of 3 you say fizz, for a number divisible by 5 you say buzz, while if it is divisible by both(3 and 5) you say FizzBuzz, hence the name.
It is a relatively easy problem to solve and I have done it, but I think my solution is a bit clunky. This is it:
int[] numbers = new int[100];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i;
}
for (int i : numbers) {
if (i % 3 == 0) {
System.out.println("Fizz");
} else if(i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println("FizzBuzz");
}
}
But the problem is that when the number is divisible by both 3 and 5 it gives me "Fizz" for some reason. Can somebody explain to me, because I'm new to java programming. Thanks in advance!
The problem lies in the order of your if statements. Lets take a look at the number 15, which is the first number divisible by both 3 and 5. Because of the order in which you have your if statements, the first statement that is checked is
if ( 15 % 3 == 0)
The result of the operation is indeed equal to 0, as 15 is divisible by 3 and so "Fizz" is printed and your else is ignored.
Think about how you should structure the order of your if statements and which additional condition should you introduce to catch the specific case of being divisible by both i % 3 == 0 && i % 5 == 0.
When you enter the if statement and your number is 15 for exemple, you enter the first if statement and.. prints "Fizz" as you stated, because 15 % 3 == 0 returns true. Then it ignores the else.
You want the first if to be
if (i % 3 == 0 && i % 5 == 0) {
System.out.println("FizzBuzz");*
}
Try this code
public static void main(String[] args) {
int[] numbers = new int[100];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i;
}
for (int i : numbers) {
if ((i % 3 == 0) && (i % 5 == 0)) {
System.out.println("FizzBuzz");
} else if(i % 5 == 0) {
System.out.println("Buzz");
} else if (i % 3 == 0){
System.out.println("Fizz");
}
}
}

multiple conditions else / if statement somehow wrong?

I'm doing a hackernet challenge where n is an int input. The conditions are:
If n is odd, print Weird
If n is even and in the inclusive range of 2 to 5, print Not Weird
If n is even and in the inclusive range of 6 to 20, print Weird
If n is even and greater than 20, print Not Weird.
Im sure the code makes logic and dont think theres syntax. It gives the correct responses and hackernet still says its incorrect so ive come here to see if anyone can see what the problem is
public static void main(String[] args)
{
int N = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
if (N % 2 != 0 || N % 2 == 0 && N >= 6 && N <= 20)
{
System.out.print("weird");
}
else
{
System.out.print("not weird");
}
}
The problem is the logic in your else condition, which would also catch values of N which are less than 2. Try this version:
if (N % 2 != 0)
{
System.out.print("weird");
}
else if (N >= 2 && N <= 5 || N > 20)
{
System.out.print("not weird");
}
else if (N >= 6 && N <= 20)
{
System.out.print("weird");
}
else
{
// NOTE: if the code still fails, remove this else condition
System.out.print("unexpected value of N");
}
Note: To get your code to pass the Hackernet task, you might have to completely remove the else condition. I added it for completeness, but Hackernet might test N=1 to see if nothing gets printed.
Read this condition :
if (N % 2 != 0 || N % 2 == 0 && N >= 6 && N <= 20)
as
if (N % 2 != 0 || (N % 2 == 0 && N >= 6 && N <= 20))
Then see how operator precedence changes the behaviour and yield desired results.
Check the following one
public static void main(String[] args)
{
int N = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
if(N%2!=0) {
System.out.print("weird");
}else if(N>=2 && N<=5) {
System.out.print("not weird");
}else if(N>=6 && N<=20) {
System.out.print("weird");
}else if(N>20) {
System.out.print("not weird");
}
}
For the technical part: start by reading about
precedence of java operators and then make your code easier to read.
Pushing that many conditions into a single if is not helpful. You see it yourself: you think the code is correct, but probably it isn't. And now you look to other people to explain your overly complex code back to you. And of course, all the other answers do all that for you ... but beyond that:
The "real" answer here is: learn how to test your code.
Instead of having a main that somehow asks for a number, and then makes decisions, write a method boolean isWeird() that takes a number and returns true/false according to your requirements.
And then simply test that method with all reasonable cases. And then check if that result is as expected.
Using JUnit, you could write something like
assertThat(isWeird(1), true);
assertThat(isWeird(21), true);
assertThat(isWeird(22), true);
...
Ideally, you write such tests before you implement that method. And then you implement all the conditions, and any check that fails tells you that you got something wrong.
I feel, In the if (N % 2 != 0 || N % 2 == 0 && N >= 6 && N <= 20) condition, you are verifiying the odd and even values at same time using && and || operator. Can you modify the condition into like this if (N % 2 != 0 || (N % 2 == 0 && N >= 6 && N <= 20)) and check? If N is odd weird will be printed or if N is even and it falls under the 6 and 20 inclusive, weird will be printed.
You already have a good few answers here but if you think logically about what you actually need, you can break it down easier.
It looks like the only "Not Weird" print out is 2, 4 and even numbers > 20
So an example could be something like:
if (n % 2 == 0) {
if ((n >= 2 && n <= 5) || (n > 20)) {
return "Not Weird";
}
}
return "Weird";
You can try this
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
if (n % 2 == 1 || (n >= 6 && n <= 20)) {
System.out.println("Weird");
} else {
System.out.println("Not Weird");
}
scanner.close();
}

HackerRank challenge, what am I doing wrong? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am trying to do this challenge https://www.hackerrank.com/challenges/java-if-else
I tried doing this:
public class Main {
public static void main(String[] args) {
int x;
x = 34;
if ((x % 2) != 0) {
System.out.println("Weird");
} else if (((x % 2 == 0) & ((x >= 2) & (5 >= x)))) {
System.out.println("Not Weird");
} else if (((x % 2 == 0) & ((x >= 6) & (20 >= x)))) {
System.out.println("Weird");
} else if ((x % 2 == 0) & (x > 20)) {
System.out.println("Not Weird");
}
}
}
I ran this in Intellij and it works fine, but here, I only get three test cases right. What am I doing wrong? I was overwhelmed by the scanner stuff, as I have not even covered that stuff yet in my own reading.
HackerRank challenge, what am I doing wrong?
You are not reading the number from Standard Input, so the tests are all checking the output for the number 34.
Replace
int x;
x = 34;
With this (which is what the test started with)
Scanner sc=new Scanner(System.in);
int x=sc.nextInt();
Do that, your tests pass fine.
Alternate solution
boolean even = x % 2 == 0;
boolean weird = !even || (even && (6 <= x && x <= 20));
System.out.println(weird ? "Weird" : "Not Weird");
You should be using && as a conditional operator. Also you don't need to have the if statement check if it is even, as the first if statement provided in their code already checks if it's odd. If it isn't (only other option is even) it goes to the else statement. Elegant solution listed below.
The scanner simply is just what is passed in, don't worry about it, just use the value n, they will pass the value into the code.
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
String ans="";
if(n%2==1){ // only if it's odd
ans = "Weird";
}
// only enters else if the value is even
else{
if (n >= 6 && n <= 20) { // between 6 and 20
ans = "Weird";
} else { // only other option is greater than 20
// or below 6 which includes 2 through 5
ans = "Not Weird";
}
}
System.out.println(ans);
}
EDIT: Saw that his ranges are in a non-traditional order, so it is fine. Not sure what was wrong prior.
The above answer is better^^
I cannot comment (rep too low), but you don't need to check if it is even each time after the first check. You can assume that if it is not odd, then it is even.
An easier/simpler way of writing your code is:
String answer = "";
if ((x % 2) != 0) {//if odd
answer = "Weird";
}
else { //if even
if ((x > 1) && (x < 6)) {
answer = "Not Weird";
}
else if ((x > 5) && (x < 21)) {
answer = "Weird";
}
else if (x > 20) {
answer = "Not Weird";
}
System.out.println(answer);
By not using "equal to" operators and changing your order in the "less than" side you could solve your problem.
Your code is OK, has passed HackerRank tests, inside their else:
if ((n % 2 == 0) & ((n >= 2) & (5 >= n)))
System.out.println("Not Weird");
if ((n % 2 == 0) & ((n >= 6) & (20 >= n)))
System.out.println("Weird");
if ((n % 2 == 0) & (n > 20))
System.out.println("Not Weird");
Just changed to "else if" to "if".

Categories