Java, nested if, if/else statements to add words - java

I'm doing an assignment where I need to do a multitude of things that require nested if/else. Print the first 50 Fibonacci numbers, but:
if the number is a multiple of 3 - print "Cheese"
if the number is a multiple of 5 - print "Cake"
if the number is a multiple of 7 - print "Factory"
if the number is a multiple of 3 & 5 - print "CheeseCake"
if the number is a multiple of 3 & 7 - print "CheeseFactory"
if the number is a multiple of 5 & 7 - print "CakeFactory"
if the number is a multiple of 3 & 5 & 7 - print "CheeseCakeFactory"
if the number is a multiple of 2 - print "Blah"
At this point I'm repeating the conditions, and I'm sure there's a cleaner way to do it:
package Assignment1;
public class CheeseCakeFactory_163003984 {
public static void main(String[] args) {
long numberOne = 0;
long numberTwo = 1;
long sum = 0;
int counter = 0;
String word1 = "Cheese";
String word2 = "Cake";
String word3 = "Factory";
while (counter <= 50) {
sum = numberOne + numberTwo;
numberOne = numberTwo;
numberTwo = sum;
counter++;
if (sum % 3 == 0) {
System.out.print(word1 + ", ");
} else if (sum % 5 == 0) {
if (sum % 3 == 0) {
System.out.print(word1 + word2 + ", ");
} else if (sum % 3 == 0) {
if (sum % 5 == 0) {
if (sum % 7 == 0) {
System.out.print(word1 + word2 + word3 + ", ");
}
}
if (sum % 7 == 0) {
System.out.print(word1 + word2 + word3 + ", ");
} else if (sum % 2 == 0) {
System.out.print("Blah, ");
} else {
System.out.print(sum);
if (counter % 10 == 0) {
System.out.print("\n");
} else {
System.out.print(", ");
}
}
}
}
}
}
}

There is a good reason behind the names "CheeseFactory", "CakeFactory", and "CheeseCakeFactory". It is so that you do not have to repeat your statements.
Let us say you have an array with the first 50 fibonacci-numbers already called numbers.
for(int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + ": ");
if(numbers[i] % 3 == 0) {
System.out.print("Cheese");
}
if(numbers[i] % 5 == 0) {
System.out.print("Cake");
}
if(numbers[i] % 7 == 0) {
System.out.print("Factory");
}
System.out.println(""); //start a new line
}
I have not covered what will happen if it's a multiple of two, since it is ambiguous. What if it's both a multiple of two and three?

The idea here is that you want to build out the statements one at a time instead of all at once. Here I'm going to leverage something known as StringBuilder which will allow us to neatly and concisely build out the string we want.
If we know the sum to be divisible by 3, we add the word we want to the appender.
if (sum % 3 == 0) {
builder.append(word1);
}
If we know the sum to be divisible by 3 and by 5, we add the words we want to the appender.
if (sum % 3 == 0) {
builder.append(word1);
}
if(sum % 5 == 0) {
builder.append(word2);
}
Nothing special needs to happen in terms of other logic; simple if conditions will get you the result you need. If it's not true, the if block isn't executed.
I leave the other forms (including the even number form and actually also printing out the number - hint: if you haven't printed any other words, you may want to print the number) as an exercise for the reader.

I tried your code and it was printing all the time the word Cheese.
I refactored it a little bit to fulfill your requirements ( I hope I understood them :) )
public static void main(String[] args) {
long numberOne = 0;
long numberTwo = 1;
long sum = 0;
int counter = 0;
String word1 = "Cheese";
String word2 = "Cake";
String word3 = "Factory";
String word4 = "Blah";
while (counter <= 50) {
sum = numberOne + numberTwo;
numberOne = numberTwo;
numberTwo = sum;
counter++;
StringBuilder sb = new StringBuilder();
if (sum % 2 == 0) {
sb.append(word4);
} else {
if (sum % 3 == 0) sb.append(word1);
if (sum % 5 == 0) sb.append(word2);
if (sum % 7 == 0) sb.append(word3);
}
if (sum % 2 == 0 || sum % 3 == 0 || sum % 5 == 0 || sum % 7 == 0) {
sb.append(",");
System.out.println(String.format("%s %s", sum, sb.toString()));
}
}
}
You can then refactor it extracting it to a word factory method and so on
This will print
2 Blah,
3 Cheese,
5 Cake,
8 Blah,
21 CheeseFactory,
34 Blah,
55 Cake,
144 Blah,
610 Blah,
987 CheeseFactory,
2584 Blah,
6765 CheeseCake,
10946 Blah,
46368 Blah,
75025 Cake,
196418 Blah,
317811 Cheese,
832040 Blah,
2178309 CheeseFactory,
3524578 Blah,
9227465 Cake,
14930352 Blah,
63245986 Blah,
102334155 CheeseCakeFactory,
267914296 Blah,
701408733 Cheese,
1134903170 Blah,
4807526976 Blah,
12586269025 Cake,
20365011074 Blah,
32951280099 Cheese,

Instead of nesting for each possible condition, you can check for multiple conditions in the same if statement. For example, to check if a number is a multiple of 3 and 5, you can simply write:
if(sum % 3 == 0 && sum % 5 == 0) // check if this number is a multiple of 3 and 5
System.out.print("cheesecake");
Using if statements like the example I just gave, you could do all of those things without nesting ifs and just use else ifs or additional, separate ifs.
If the way the statement is written is confusing, you can use parentheses to group the statements together for better readability:
if((sum % 3 == 0) && (sum % 5 == 0))
System.out.print("cheesecake");
Regardless of which way you write it, the result will be the same, though.

Related

Issue with getting this java program to display the proper whitespace in the answer

So my problem is, my output seems to be correct except it is giving me 0/10 for credit because of the whitespace after the output counts down to one in each situation. It is saying I need a newline after the one but I have tried several things and it's the same output every time.
2.31 LAB: Hailstone sequence
Given a positive integer n, the following rules will always create a sequence that ends with 1, called the hailstone sequence:
If n is even, divide it by 2
If n is odd, multiply it by 3 and add 1 (i.e. 3n +1)
Continue until n is 1
Write a program that reads an integer as input and prints the hailstone sequence starting with the integer entered. Format the output so that ten integers, each separated by a tab character (\t), are printed per line.
The output format can be achieved as follows:
System.out.print(n + "\t");
Ex: If the input is:
25
the output is:
25 76 38 19 58 29 88 44 22 11
34 17 52 26 13 40 20 10 5 16
8 4 2 1
import java.util.Scanner;
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int n;
n = scnr.nextInt();
System.out.print(n + "\t");
int count = 1;
while (n > 1) {
if (n % 2 == 0) {
n = n * 1 / 2;
} else {
n = 3 * n + 1;
}
System.out.print(n + "\t");
count++;
if (count % 10 == 0) {
System.out.print("\n");
}
}
}
This is what I came up with and I am new to java so it is probably something I am overthinking, any thoughts would be appreciated.
"enter image description here" is not an image description
If nothing works, I guess you can trick it by just skipping the tab on the 10'th print. So instead of your normal System.out.print(n + "\t"); print try:
if ((count + 1) % 10 == 0) {
System.out.print(n);
} else {
System.out.print(n + "\t");
}
instead of your normal print.
I figured it out, I just needed to change the order of the code a little and make (n != 1) and System.out.print(n) at the very end. Thanks for the help.
try this, changed the print condition to exclude the tab for end value and when n is 1.
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int n;
n = scnr.nextInt();
System.out.print(n + "\t");
int count = 1;
while (n > 1) {
if (n % 2 == 0) {
n = n * 1 / 2;
} else {
n = 3 * n + 1;
}
count++;
if (count % 10 == 0) {
System.out.println(n);
}else{
if(n==1) {
System.out.print(n);
}else{
System.out.print(n + "\t");
}
}
}
}

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

Want to print last sentence

You must deliver exactly N kilograms of sugar to a candy store. The sugar made in the sugar factory is contained in a bag. The bag has 3 kg bag and 5 kg bag.
I try to carry as little bags as possible. For example, when you need to deliver 18 kilograms of sugar, you can take 6 bags of 3 kilograms, but if you deliver 3 kilograms and 3 kilograms, you can deliver a smaller number of bags.
Write a program to find out the number of bags you should take when you have to deliver exactly N kilograms of sugar.
(3<=N<=5000 AND If you can not make exactly N kilograms, print -1.)
In case of only 4 or 7 , it is not divided so I made it to print -1.
And to get the minimum bag, I used the code below.
But when I run this, the case if it is not divided by 5 or 3, the bottom sentence should be printed out but it is not working.
I want to know how does it works. Thank you.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int N = input.nextInt();
if (N % 5 == 0) {
System.out.println(N / 5);
} else if (N == 4 || N == 7) {
System.out.println(-1);
} else
for (int i = 1; (N - 3 * i) % 5 != 0; i++) {
if ((N - 3 * i) % 5 == 0)
System.out.println(i + (N - 3 * i) / 5);
break;
}
}
}
Looks there is a logic issue with your solution. Try the following :
boolean isPossible = true;
if (N % 5 == 0) {
System.out.println("You need : " + (N / 5) + " bags");
} else {
int diff = 0;
for (int i = N; i > 0 && N >= 0; i--) {
if (N % 5 != 0) {
diff = N % 5;
N = N - diff;
} else {
if (diff % 3 == 0) {
System.out.println("You need : " + (N / 5 + diff / 3) + " bags");
isPossible = true;
break;
} else {
N = N - 5;
diff = diff + 5;
}
}
}
}
if (N <= 0 || !isPossible)
System.out.println(-1);
Logic is explained below :
Basically here we find the modulus of N with 5 and check if the
remainder (in the example diff) is a multiple of 3.
If the remainder (diff) is not a multiple of 3 then we reduce N by
5 and increase diff by 5. This continues until we have found a match (isPossible) or else if not found -1 is printed out.
So as far as I understand, you're trying to use the smallest amount of 3kg bags in the last for loop and you want to break out as soon as the remainder is divisible by 5kgs.
(int i = 1; (N - 3 * i) % 5 != 0; i++)
Could you not have the middle part as i < 5?
(int i = 1; i < 5; i++)
Also, you could get rid of the if condition
if (N % 5 == 0) {
part by starting i at 0, so you account for the case N is divisible by 5:
(int i = 0; i < 5; i++)
Scanner input = new Scanner(System.in);
int N = input.nextInt();
int sum = 0;
boolean isFound = false;
for (int i = 0; i < N / 2; i++) {
for (int j = 0; j < N / 2; j++) {
if ((5 * i) + (3 * j) == N) {
sum = i + j;
isFound = true;
}
}
}
if (isFound ) {
System.out.println("You require " + sum + " bags");
} else {
System.out.println(-1);
}
Explanation:
The above code aims to find the possible combinations of the sum of the factors of 3 and 5 that give the number, i.e N:
For example:
N = 32
For each iteration, the following condition is checked.
if((5 * i) + (3 * j) == N)
The check continues until the smallest numbers that satisfy the condition are found.
5*0 + 3*0 = 0 which is not equal to 32
5*0 + 3*1 = 3 which is not equal to 32
5*0 + 3*2 = 6 which is not equal to 32
.
.
5*1 + 3*0 = 5 which is not equal to 32
5*1 + 3*1 = 8 which is not equal to 32
5*1 + 3*2 = 11 which is not equal to 32
5*1 + 3*4 = 17 which is not equal to 32
.
.
5*4 + 3*0 = 20 which is not equal to 32
5*4 + 3*1 = 23 which is not equal to 32
5*4 + 3*2 = 26 which is not equal to 32
5*4 + 3*3 = 29 which is not equal to 32
5*4 + 3*4 = 32
In this case, i=4 and j=4, i.e sum of bags required (i+j) = 8
isFound is set to true to indicate that the combination is found.
If no combination is found, isFound remains to be false, and -1 is printed.

using mod 3 in Java

So, I want to find what numbers between 1 and 100 are divisible by 3 and 7. I got it to work, except for one of the numbers. For some reason, 3 % 3 is giving me 3 as a remainder, but 6 % 3 is giving me 0. This is my code:
public class factors
{
public static void main(System args[])
{
//Variables
int integer, remainder;
//Displays header
System.out.print("Integers less than 100 that are \nevenly divisible by 3 or 7");
//Loops through each integer
for (integer = 1; integer <= 100; integer++)
{
remainder = integer % 3; //determines if 3 is a factor
if (remainder == 0) //displays integer
{
System.out.println(integer + " is divisible by 3");
}
remainder = integer % 7; //determines if 7 is a factor
if (remainder == 0) //displays integer
{
System.out.println(integer + " is divisible by 7");
}
}
}
}Does anyone know why this isn't working for the number 3?
You code is actually doing
remainder = 3 % 7; // equals 3.
The best way to determine why your code is not doing what you think is to step through your code using a debugger.
All the multiples of 3 & 7 will be multiples of 21, i.e. 21, 42, 63, 84.
Your 3 is getting tacked onto the end of the line of text above. You'll be seeing
Integers less than 100 that are
evenly divisible by 3 or 73
because you wrote print instead of println for this line of text. The % operator is working just fine, and 3 % 3 is indeed 0, not 3.
You are not outputting a remainder - you are displaying integer. So for 3 it should print 3.
Make you print statements more definite:
System.out.println(integer + " is divisible by 3"); // for the first `if`
and
System.out.println(integer + " is divisible by 7"); // for the second `if`
This should clear your confusion.
Your logic prints number divisible by 3 or 7.
Firstly, your code can be shortened to:
//and
for (int i = 1; i <= 100; i++){
if(i % 3 == 0 && i % 7 == 0) {
System.out.println(i);
}
}
//or
for (int i = 1; i <= 100; i++){
if(i % 3 == 0 || i % 7 == 0) {
System.out.println(i);
}
}
Also I note you're not declaring a type for your integer, remainder variables. I didn't attempt to recreate with those issues; start by solving that.

FizBuzz program: how to make the output correct?

I got a question about this program, it says: The FizzBuzz Challenge: Display numbers from 1 to x, replacing the word 'fizz' for multiples of 3, 'buzz' for multiples of 5 and 'fizzbuzz' for multiples of both 3 and 5. Th result must be:1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 ...
So my problem is at the time to print the output, I dont know what to do.
public class Multiplos {
public static void main(String args[]) {
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0) {
System.out.print(i + " ");
System.out.print(" fizz ");
}
if (i % 5 == 0) {
System.out.print(" " + i);
System.out.print(" " + "buzz ");
}
if((i % 3 == 0)&&(i % 5 == 0)){
System.out.print(i + " ");
System.out.print(" fizzbuzz ");
}
}
}
}
Here's the pseudocode:
for i in 1 to 100
if(i % 5 == 0) AND (i % 3 == 0) print 'fizzbuzz'
else if(i % 3 == 0) print 'fizz'
else if(i % 5 == 0) print 'buzz'
else print i
I'll leave it as an exercise for you to convert it into Java, as that might help with the understanding as to how this works.
The problem is of course that when (i % 3 == 0)&&(i % 5 == 0) is true, the two preceding conditions are also true, so you get duplicated output. The easiest way to fix that is to check that the other condition is not true in the first two cases. I.e. make the first condition if((i % 3 == 0)&&(i % 5 != 0)) and the same for the second.
The other problem with your code is that you're printing the number when any of the cases is true, but you're supposed to print it when none of them are. You can fix that by making a fourth if-condition which checks that none of the conditions are true and if so, prints i.
Now if you did the above, you'll see that you ended up with some code duplication. If you think about it a bit, you'll see that you can easily fix that, by using if - else if - else if - else, which allows you to assume that the previous conditions were false when the current condition is checked.
Hm, I think I'll only hint:
Think of the correct order: What happens if a number is a multiple of 3, but also of (3 and 5)?
There is an else if statement.
Use else if so that the conditional don't overlap.

Categories