Issue with my if else statement in a do while loop - java

My do-while loop is supposed to print out numbers from 1 - 106 (including 1 and 106)
whats supposed to happen:
multiples of 3 are supposed to print out Big,
multiples of 5 are supposed to print out Mean,
multiples of 7 are supposed to print out Bugs,
multiples of 3 and 5 are supposed to print out BigMean,
multiples of 3 and 7 are supposed to print out BigBugs,
multiples of 5 and 7 are supposed to print out MeanBugs,
multiples of 3, 5 and 7 are supposed to print out BigMeanBugs.
What actually happens:
my do-while loop only runs the first "if" statement. Any help?
My code:
public static void main(String [] args){
int i = 0;
do{
++i;
if(i %3 == 0){
System.out.print("Big, ");
if(i %5 ==0){
System.out.print("Mean, ");
}
if(i %7 ==0){
System.out.print("Bugs, ");
}
if((i %3 == 0) && (i %5 == 0)){
System.out.print("BigMean, ");
}
if((i %3 == 0) && (i %7 == 0)){
System.out.print("BigBugs, ");
}
}else if((i %5 == 0) && (i %7 == 0)){
System.out.print("MeanBugs, ");
}else if((i %3 == 0) && (i %5 == 0) && (i %7 ==0)){
System.out.print("BigMeanBugs, ");
}else{
System.out.print(i + " ");
}
}while(i<=106);
}//closing main

As I could see your problem is probably that your if-statements are inside of first if-statement, so maybe you want this:
public class BigMeanBugsDoWhileLoop
{
public static void main(String [] args)
{
int i = 0;
do
{
++i;
boolean bug = false;
String result = "";
if(i %3 == 0)
{
result += "Big";
bug = true;
}
if(i %5 ==0)
{
result += "Mean";
bug = true;
}
if(i %7 ==0)
{
result += "Bugs";
bug = true;
}
if(!bug)
{
System.out.println(i + "");
}
else
{
System.out.println(result);
}
}while(i<106);
}//closing main
} // closing class
You don't need other if-statements because you don't use break so other expressions will be evaluated before next iteration.

First, if something is divisible by 3 and 7 it is divisible by 21.
Second, if you reverse the order, you will catch divisible by 3 and 5 before divisible by 3 or 5 separately (assuming that is what you want). If you do it the other way you may print the values prematurely or miss them altogether before checking the other possible factors. This behavior is also dependent on if vs if/else if statements.
I have limited the printout to 25 to avoid a long list. Modify as you see fit.
public class BigMeanBugsDoWhileLoop {
public static void main(String[] args) {
int i = 1;
do {
String bugType = "";
if (i % 105 == 0) {
bugType = "BigMeanBugs"; // 3 5 7
} else if (i % 35 == 0) {
bugType = "MeanBugs"; // 5 7
} else if (i % 21 == 0) {
bugType = "BigBugs"; // 3 7
} else if (i % 15 == 0) {
bugType = "BigMean"; // 3 5
} else if (i % 7 == 0) {
bugType = "Bugs"; // 7
} else if (i % 5 == 0) {
bugType = "Mean"; // 5
} else if (i % 3 == 0) {
bugType = "Big"; // 3
}
System.out.println(bugType.isEmpty() ? i : bugType);
i++;
} while (i <= 25);
}// closing main
} // closing class
Prints this.
1
2
Big
4
Mean
Big
Bugs
8
Big
Mean
11
Big
13
Bugs
BigMean
16
17
Big
19
Mean
BigBugs
22
23
Big
Mean

You have to increment the value of i in the end of loop
public static void main(String [] args){
int i = 1;
do{
if(i %3 == 0){
System.out.print("Big, ");
if(i %5 ==0){
System.out.print("Mean, ");
}
if(i %7 ==0){
System.out.print("Bugs, ");
}
if((i %3 == 0) && (i %5 == 0)){
System.out.print("BigMean, ");
}
if((i %3 == 0) && (i %7 == 0)){
System.out.print("BigBugs, ");
}
}else if((i %5 == 0) && (i %7 == 0)){
System.out.print("MeanBugs, ");
}else if((i %3 == 0) && (i %5 == 0) && (i %7 ==0)){
System.out.print("BigMeanBugs, ");
}else{
System.out.print(i + " ");
}
i++;
}while(i<=106);
}//closing main
} // closing class

Related

I'm facing an issue with control structures

My problem is with output of my code. When I enter 20, the output must be weird, but I am getting not weird. Same with the value 18.
import java.util.Scanner;
public class conditional {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
String ans = "";
if(n%2 == 1){
ans = "Weird";
} else {
if(n <= 2 && n >= 5){
ans="Not weird";
} else if(n <= 6 && n >= 20){
ans = "Weird";
} else{
ans = "Not Weird";
}
}
System.out.println(ans);
}
}
the output must be weird,but i am getting not weird
Because, if(n%2 == 1) return false and fall to else block where
if(n <= 2 && n >= 5) is `false`
and
else if(n <= 6 && n >= 20) is also `false`
So, again falls to else block. You probably change
if(n <= 2 && n >= 5)
to
if(n >= 2 && n <= 5)
and
else if(n <= 6 && n >= 20)
to
else if(n >= 6 && n <= 20)
Otherwise, they will never be true and always falls to else.
In your program last else is being executed. Change && (logical AND) to || (logical OR) which will check if number is less than something OR higher than something, instead of checking if something is less or equal 5 AND higher or equal to 20 in the same time as it doesn't have a possibility to evaluate in any case.
I have come up with two solutions and also i see a flaw:
1. if(n%2 == 1) this code can be altered to if(n%2 == 0)
2. The flaw is **(n <= 2 && n >= 5)** . No number can be <2 and >5 at the same time. Try changing that to (n <= 2 || n >= 5) and same goes for (n <= 6 && n >= 20)
import java.util.Scanner;
public class conditional {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
String ans = "";
if(n%2 == 1){
ans = "Weird";
} else {
if(n <= 6 || n >= 20){
ans="Not weird";
} else if(n <= 2 || n >= 5){
ans = "Weird";
} else{
ans = "Not Weird";
}
}
System.out.println(ans);
}
}

Avoiding Multiple Function Calls?

I cannot figure out how to make it so it only calls check4 once... this was for a homework assignment last semester and I got 5 points off for calling it multiple times but I would not like to know how to do it (the professor never said how).
I tried moving the check4 to after the if block but it really needs to go in between the last else if and the else which is not possible. The ONLY way the number should print is if all of the steps do not print out a word instead.
public class CheeseCakeFactory_ajh187 {
public static void main(String[] args) {
int counter = 0;
int printNumber = 0; //number that will get changed to one of the terms
while (counter != 15 & printNumber < 210) { //as long as the counter is not 15 and print number is lesss than 210 it will keep looping.
printNumber++;
if (printNumber % 3 ==0 && printNumber % 5 == 0 && printNumber % 7 == 0) {
System.out.print("cheesecakefactory");
}
else if (printNumber % 3 == 0 && printNumber % 5 == 0){
System.out.print("cheesecake");
check4(printNumber);
}
else if (printNumber % 3 == 0 && printNumber % 7 == 0){
System.out.print("cheesefactory");
check4(printNumber);
}
else if (printNumber % 5 == 0 && printNumber % 7 == 0){
System.out.print("factorycake");
check4(printNumber);
}
else if (printNumber % 3 == 0){
System.out.print("cheese");
check4(printNumber);
}
else if (printNumber % 5 ==0){
System.out.print("cake");
check4(printNumber);
}
else if (printNumber % 7 ==0){
System.out.print("factory");
check4(printNumber);
}
else { //if the number is not divisible by any of the other numbers we still have to check for the 4
if (Integer.toString(printNumber).contains("4")) {
System.out.print("hoho");
}
else {
System.out.print(printNumber); //if its not divisible by 4, we just print the number
}
}
System.out.print(" ");
counter++;
if (counter == 15) { //once the counter is 15 we need to put the new items on a new line
System.out.print("\n");
counter = 0; //resets the counter so that we can accomplish this every 15 passes.
}
}
}
public static void check4(int printNumber) {
if (Integer.toString(printNumber).contains("4")) {
System.out.print("hoho");
}
}
}
First, I would update check4 to return a boolean (which you can save). Something like,
public static boolean check4(int printNumber) {
return String.valueOf(printNumber).contains("4");
}
Then you can also save your tests into boolean variables. Something like
boolean mod3 = printNumber % 3 == 0;
boolean mod5 = printNumber % 5 == 0;
boolean mod7 = printNumber % 7 == 0;
if (mod3 || mod5 || mod7) {
if (mod3 && mod5 && mod7) {
System.out.print("cheesecakefactory");
} else {
boolean isCheck4 = check4(printNumber); // <-- call it once
if (mod3 && mod5) {
System.out.print("cheesecake");
} else if (mod3 && mod7) {
System.out.print("cheesefactory");
} else if (mod5 && mod7) {
System.out.print("factorycake");
} else if (mod3) {
System.out.print("cheese");
} else if (mod5) {
System.out.print("cake");
} else if (mod7) {
System.out.print("factory");
} else {
if (!isCheck4) { // <-- it doesn't have a 4, print it.
System.out.print(printNumber);
}
}
if (isCheck4) {
System.out.print("hoho"); // <-- it does have a 4.
}
}
}
I hope I got your problem right so:
you create a global boolean variable named say isMethodCalled witch is false, then in the check4 method you make it true, and simple check if the isMethodCalled is false before calling the method.
boolean isMethodCalled = false;
if(!isMethodCalled) {
check4() // do wathever you need to do to call check4()
}
public static void check4(int printNumber) {
if (Integer.toString(printNumber).contains("4")){
System.out.print("hoho");
}
isMethodCalled = true;
}
Simply use a flag, set it to true initially.
Then, wherever you dont want the check4 to run, set it to false.
after the if-else, check if the flag istrue. if it is, execute 'check4(printNumber)'
public class CheeseCakeFactory_ajh187 {
public static void main(String[] args) {
int counter = 0;
int printNumber = 0; //number that will get changed to one of the terms
int flag=true;
while (counter != 15 & printNumber < 210) { //as long as the counter is not 15 and print number is lesss than 210 it will keep looping.
printNumber++;
if (printNumber % 3 ==0 && printNumber % 5 == 0 && printNumber % 7 == 0) {
System.out.print("cheesecakefactory");
flag=false;
}
else if (printNumber % 3 == 0 && printNumber % 5 == 0){
System.out.print("cheesecake");
}
else if (printNumber % 3 == 0 && printNumber % 7 == 0){
System.out.print("cheesefactory");
}
else if (printNumber % 5 == 0 && printNumber % 7 == 0){
System.out.print("factorycake");
}
else if (printNumber % 3 == 0){
System.out.print("cheese");
}
else if (printNumber % 5 ==0){
System.out.print("cake");
}
else if (printNumber % 7 ==0){
System.out.print("factory");
}
else { //if the number is not divisible by any of the other numbers we still have to check for the 4
if (Integer.toString(printNumber).contains("4")) {
System.out.print("hoho");
}
else {
System.out.print(printNumber); //if its not divisible by 4, we just print the number
}
flag=false;
}
if(flag)
check4(printNumber);
System.out.print(" ");
counter++;
if (counter == 15) { //once the counter is 15 we need to put the new items on a new line
System.out.print("\n");
counter = 0; //resets the counter so that we can accomplish this every 15 passes.
}
}
}
public static void check4(int printNumber) {
if (Integer.toString(printNumber).contains("4")) {
System.out.print("hoho");
}
}
}

How can I nest this conditional statement? in Java

I am a Java student and I am having trouble with nesting the conditional statement of this program
Exercise CozaLozaWoza (Loop & Condition): Write a program called
CozaLozaWoza which prints the numbers 1 to 110, 11 numbers per line.
The program shall print "Coza" in place of the numbers which are
multiples of 3, "Loza" for multiples of 5, "Woza" for multiples of 7,
"CozaLoza" for multiples of 3 and 5, and so on. The output shall look
like:
1 2 Coza 4 Loza Coza Woza 8 Coza Loza 11
Coza 13 Woza CozaLoza 16 17 Coza 19 Loza CozaWoza 22
23 Coza Loza 26 Coza Woza 29 CozaLoza 31 32 Coza
......
I manage to do this
public class CozaLozaWoza {
public static void main(String[] args) {
for (int x = 1; x <= 110; x +=1) {
if (x % 3 == 0) {
System.out.print(" Coza");
}else if (x % 5 == 0) {
System.out.print(" Loza");
}else if (x % 7 == 0) {
System.out.print(" Woza");
}else if (x % 3 != 0 && x % 5 != 0 && x % 7 != 0) {
System.out.print(" " + x);
}
if (x % 11 == 0) {
System.out.println();
}
}
}
}
I can't merge the last if statement, can anyone help me? thank you
The if statements should be independent of each other, since more than one statement can be true for the same number (for example "CozaLoza" for multiples of 3 and 5).
for (int x = 1; x <= 110; x +=1) {
boolean regular = true;
System.out.print (" ");
if (x % 3 == 0) {
System.out.print("Coza");
regular = false;
}
if (x % 5 == 0) {
System.out.print("Loza");
regular = false;
}
if (x % 7 == 0) {
System.out.print("Woza");
regular = false;
}
if (regular) {
System.out.print(x);
}
if (x % 11 == 0) {
System.out.println();
}
}
package homePrac;
public class LOZAMOZACOZA
{
public static void main (String []args)
{
int max = 110;
for (int i=1; i<=max; i++)
{
if (i%3==0)
System.out.print("Coza");
else if (i%5==0)
System.out.print ("Woza");
else if (i%7==0)
System.out.print("CozaLoza");
else if (i%3!=0 || i%5!=0 || i%7!=0)
System.out.print(i);
if(i%11==0)
System.out.println("");
}
}
}

How can I get this program to print out ten items per line seperated by 1 space?

Here's my code so far
public class DivisibleBy5and6
{
public static void main (String []args)
{
for (int i = 100; i <= 200; i++)
{
boolean num = (i % 5 == 0 || i % 6 == 0) && !(i % 5 == 0 && i % 6 == 0);
if (num == true)
System.out.println(i + " is divisible");
}
}
}
Like stated previously how can I get the output to print out 10 items per line separated by a space?
How about:
int count = 0;
for (int i = 100; i <= 200; i++) {
boolean num = (i % 5 == 0 || i % 6 == 0) && !(i % 5 == 0 && i % 6 == 0);
if (num == true) {
count++;
System.out.print(i + " is divisible ");
if(count >= 10) {
System.out.println();
count -= 10;
}
}
}

Why isn't my FizzBuzz code processing both if statements when they both match? [duplicate]

This question already has answers here:
Conditional statement true in both parts of if-else-if ladder
(4 answers)
Closed 2 years ago.
For those who don't know, FizzBuzz is the following problem:
Write a program that prints the numbers from 1 to 100. But for
multiples of three print "Fizz" instead of the number and for the
multiples of five print "Buzz". For numbers which are multiples of
both three and five print "FizzBuzz".
Every FizzBuzz solution I find is either some crazy esoteric solution made for the sake of being original, or your basic if-else chain:
for(int i = 1; i <= 100; i++) {
if(i % 3 == 0 && i % 5 == 0) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
I am looking for a simple solution that aims to take out the "FizzBuzz" if statement. I have this in mind:
for(int i = 1; i <= 100; i++) {
if (i % 3 == 0)
System.out.print("Fizz");
if (i % 5 == 0)
System.out.println("Buzz")
else
System.out.println(i);
}
But this doesn't work. I assume it would be able to print FizzBuzz by entering both ifs, for Fizz and for Buzz, but if the number is, for example, 3, it would print Fizz3. How do I avoid this?
What you're trying to do is
if (a)
...
if (b)
...
else // if neigther a nor b
...
This is simply not possible. An else can only belong to a single if. You have to go with the slightly longer variant.
To avoid doing redundant evaluations of the modulo operator, you could formulate the loop body as
boolean fizz = i % 3 == 0;
boolean buzz = i % 5 == 0;
if (fizz)
System.out.print("Fizz");
if (buzz)
System.out.print("Buzz");
if (!(fizz || buzz))
System.out.print(i);
System.out.println();
Another one would be
String result = "";
if (i % 3 == 0) result = "Fizz";
if (i % 5 == 0) result += "Buzz";
if (result == "") result += i;
System.out.println(result);
Your first if statement is all alone.
So, your code hits the first statement, which is ONLY an if statement, and then goes on to the next, which is an if/else statement.
RosettaCode has a good example without using AND operators.
int i;
for (i = 0; i <= 100; i++) {
if ((i % 15) == 0)
cout << "FizzBuzz" << endl;
else if ((i % 3) == 0)
cout << "Fizz" << endl;
else if ((i % 5) == 0)
cout << "Buzz" << endl;
else
cout << i << endl;
}
If your only goal is to avoid using &&, you could use a double negation and DeMorgan's laws:
for(int i = 1; i <= 100; i++) {
if(!(i % 3 != 0 || i % 5 != 0)) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
You can avoid && using the fact that i % 3 == 0 and i % 5 == 0 implies i % 15 == 0, as per RFC1337's answer.
Another solution is to use a switch on the remainder (mod 15, which is 5 times 3):
for(int i = 1; i <= 100; i++) {
final int mod = i % 15;
switch (mod) {
case 0:
case 3:
case 6:
case 9:
case 12:
System.out.print("Fizz");
if (mod != 0) break;
case 5:
case 10:
System.out.print("Buzz");
break;
default:
System.out.print(i);
}
System.out.println();
}
This is my solution. Granted, it's a bit convoluted (as in roundabout), but I believe it suits your requirement.
int main()
{
char fizzpass=0;
unsigned short index=0;
for(index=1;index<=100;index++)
{
if(0 == (index%3))
{
printf("Fizz");
fizzpass = 1;
}
if(0 == (index%5))
{
if(1 == fizzpass)
{
fizzpass = 0;
}
printf("Buzz\n");
continue;
}
if(1 == fizzpass)
{
fizzpass = 0;
printf("\n");
continue;
}
printf("%d\n",index);
}
return 0;
}
Regards.
Just add a flag variable and use System.out.print:
package com.stackoverflow;
public class FizzBuzz {
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
boolean printed = false;
if (i % 3 == 0) {
printed = true;
System.out.print("Fizz");
}
if (i % 5 == 0) {
printed = true;
System.out.print("Buzz");
}
if (printed) {
System.out.println();
} else {
System.out.println(i);
}
}
}
}
This doesn't take out the if statements but does not use the && (and) operator, you could flip the binary operators.
//FizzBuzz Case
if(!(a % 3 != 0 || a % 5 != 0)){ //flips
result[index] = "FizzBuzz";
index++;
}
Don't use an if statement at all.
import java.util.*;
import java.lang.*;
import java.io.*;
class FizzBuzz
{
public static void main (String[] args) throws java.lang.Exception
{
String[] words = {"", "Fizz", "Buzz"};
String[] nwords = {"", ""};
for(int i = 1; i < 101; ++i)
{
int fp = (i % 3 == 0) ? 1 : 0;
int bp = ((i % 5 == 0) ? 1 : 0) * 2;
int np = ((fp > 0 || bp > 0) ? 1: 0);
nwords[0] = Integer.toString(i);
System.out.print(words[fp]);
System.out.print(words[bp]);
System.out.println(nwords[np]);
}
}
}
See it on ideone.
public class fizzbuzz
{
public static void main(String[] args)
{
String result;
for(int i=1; i<=100;i++)
{
result=" ";
if(i%3==0)
{
result=result+"Fizz";
}
if(i%5==0)
{
result=result+"Buzz";
}
if (result==" ")
{
result=result+i;
}
System.out.println(result);
}
}
}
This is the most efficient way I could come up with. Hope it helps! :)
Crazy albeit unrelated solution done in Python3
#!/usr/bin/python3
for i in range(1,100):
msg = "Fizz" * bool(i%3==0)
msg += "Buzz" * bool(i%5==0)
if not msg:
msg = i
print(msg)

Categories