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");
}
}
}
Related
i set an if to check if the numbers being sent we're divisible by 3 or 7 or so on..
but it doesn't seem to do that.
i tried changing how it worked which is why it looks like this now but it still doesn't work.
public void primeNumbers() {
System.out.println("Enter the amount of prime numbers you'd like: ");
int numberOfPrimes = reader.nextInt();
int numbersFound = 0;
int foundCount = 0;
while(foundCount < numberOfPrimes) {
if (numbersFound < 2) {
numbersFound++;
}
else if(numbersFound % 3 == 0 || numbersFound % 5 == 0 || numbersFound % 7 == 0 || numbersFound % 11 == 0 || numbersFound == 2) {
System.out.print(numbersFound +" ");
foundCount++;
numbersFound++;
}
else {
numbersFound++;
}
}
}
no errors, it's just the numbers coming out aren't prime.
I figured out why it wasn't working.
I just forgot to set a condition that said that if the number is divisible by 2, then skip.
And instead of making all the numbers that are divisible by 3 7 5 and 11 be printed
i make them not be printed
im pretty sure
Sorry lol
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();
}
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.
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.
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.