How to remove unwanted items from a printed list? - java

Write a Java function that accepts an integer, n, as input and outputs a string of integers from 1 to n where every number that is a multiple of 4 is replaced with "Hello", every number that is a multiple of 5 is replaced with "Wonderful" and every number that is a multiple of 7 is replaced with "World".
package Multiple;
import java.util.Scanner;
public class MultipleList {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter an integer number: ");
int n = reader.nextInt();
for (int i = 1; i <= n; i++) {
// Checking if the integer is a multiple of 4
if ((i % 4) == 0) {
// print
System.out.println("Hello");
}
// Checking if the integer is a multiple of 5.
if ((i % 5) == 0) {
// print
System.out.println("Wonderful");
}
// Checking if the integer is a multiple of 7.
if ((i % 7) == 0) {
// print
System.out.println("World");
}
System.out.println(i);
}
}
}
When I put n = 7 (for example) I expect the output "1, 2, 3, Hello, Wonderful, 6, World", but the actual output is "1, 2, 3, Hello, 4, Wonderful, 6, World, 7".

You have to do this:
if ((i % 4) == 0) {
System.out.println("Hello");
} else if ((i % 5) == 0) {
System.out.println("Wonderful");
} else if ((i % 7) == 0) {
System.out.println("World");
} else {
System.out.println(i);
}

Your last print statement, the unconditional
System.out.println(i);
should only be executed if nothing has previously been printed for this particular value of i.
There are two ways to go about this; (1) the brute force way, preceding that statement which says "if this is not a multiple of 4 and not a multiple of 5 and not a multiple of 7", and (2) tracking whether you've printed anything. I prefer the second approach.
I think it would be useful for you to supply the exact code, though, so I have not done so here.

You can change
if( n!=i)
Syso(i)
instead of end of the line of system.out.println(i);

Related

binary to decimal converter without using parseint or arrays

Getting string index out of range but I don't understand why I've went through it about 50 times
import java.util.Scanner;
public class binary {
public static void main(String[] args) {
System.out.println("Enter the first binary number");
Scanner keyboard = new Scanner(System.in);
String num1 = keyboard.next();
//System.out.println("Enter the second binary number");
//String num2 = keyboard.next();
int total = 0;
for(int i = num1.length(); i>0;i--) {
if(num1.charAt(i) == 1) {
total += 2*i;
}
}
if(num1.charAt(3) == 1) {
total -= 1;
}
System.out.println(total);
}
}
Here's a complete solution to what you're trying to do, including a set of tests:
class binary {
private static int binaryToInt(String binary) {
int total = 0;
for (int i = 0 ; i < binary.length(); i++) {
total *= 2;
if (binary.charAt(i) == '1')
total += 1;
}
return total;
}
private static void test(String binary, int expected) {
int n = binaryToInt(binary);
String rightWrong = "right";
if (n != expected) {
rightWrong = String.format("WRONG! (should be %d)", expected);
System.out.printf("%s -> %d is %s\n", binary, n, rightWrong);
}
public static void main(String[] args) {
test("0", 0);
test("1", 1);
test("10", 2);
test("100", 4);
test("111", 7);
test("0000111", 7);
test("1010101010", 682);
test("1111111111", 1023);
System.out.println("");
// test sanity check
System.out.println("This last test should fail (we are just testing the test method itself here)...");
test("1010101010", 0);
}
}
Result:
0 -> 0 is right
1 -> 1 is right
10 -> 2 is right
100 -> 4 is right
111 -> 7 is right
0000111 -> 7 is right
1010101010 -> 682 is right
1111111111 -> 1023 is right
This last test should fail (we are just testing the test method itself here)...
1010101010 -> 682 is WRONG! (should be 0)
One significant problem in your code hasn't yet been addressed in the comments or earlier answers. Note this line vs the one in your code:
if (binary.charAt(i) == '1')
You were testing for the numeric value 1, which is never going to be true because you're getting back a character from charAt(), not a number.
While length() counts the number of elements, their indexes start at 0. For a string of "1111" the last character would be at index 3, not 4, so .length()-1. You would need to either change your for statement to for(int i = num1.length()-1; i>=0;i--) (notice also the condition change) or change the charAt statement to if(num1.charAt(i-1) == '1').
Also, based on what you are trying to do, I assume for total += 2*i you actually need something like total += Math.pow(2, i-length()) depending on what you decide to do with i first.

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

Java Question .What is the problem in my code?

Sometimes, the normal if-else isn't enough. In such cases, we have what we call ladder if and else conditions. So here we'll learn to use them.
Given a positive integer N. Your task is to check if it divisible as given below:
If it is divisible by 2, print "Two".
If it is divisible by 3, print "Three".
If it is divisible by 11, print "Eleven".
If not follow above three rules, print "-1".
Note: If N is divisible by more than one of the above given numbers, print the one which is largest.
Input Format:
First line of input contains number of testcases T. For each testcases, there will be a single line containing N.
Output Format:
For each testcase, check divisibility and print statements accordingly as given in above steps (without quotes).
Your Task:
Your task is to complete the function to check divisibility as required.
Constraints:
1 <= T <= 10
1 <= N <= 106
Example:
Input:
2
3
11
Output:
Three
Eleven
** For More Input/Output Examples Use 'Expected Output' option **
class Geeks {
static void isDivisibleByPrime (int n)
{
//Your code here
Scanner sc=new Scanner(System.in);
int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
if(a[i]%2==0)
System.out.println("Two");
else if(a[i]%3==0)
System.out.println("Three");
else if(a[i]%11==0)
System.out.println("Eleven");
else
System.out.println("-1");
}
}
}
First use braces around every block of code. it is easier to reading for everyone.
Second the point in your spec was to print the largest value if divisible, so you
should start with checking if it divides by 11 first, then 3 and then 2.
Right code is here:
static void isDivisibleByPrime(int n) {
if (n % 11 == 0) {
System.out.println("Eleven");
} else if (n % 3 == 0) {
System.out.println("Three");
} else if (n % 2 == 0) {
System.out.println("Two");
} else {
System.out.println("-1");
}
System.out.println();
}
First things first - always use braces around every block of code - especially a beginner to the language. It will make your life easier, and anyone reading your code.
Second, the point in your spec was to print the largest value if divisible, so you should start with checking if it divides by 11 first, then 3 and then 2.
And lastly, I would get all the input first, and not in the isDivisibleByPrime method, and just call that method for each input.
So just leave your isDivisibleByPrime as
static void isDivisibleByPrime(int n) {
if (n % 11 == 0) {
System.out.println("Eleven");
} else if (n % 3 == 0) {
System.out.println("Three");
} else if (n % 2 == 0) {
System.out.println("Two");
} else {
System.out.println("-1");
}
}
And call it elsewhere with the values
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of test cases:");
int numOfTestCases = sc.nextInt();
for (int i = 0; i < numOfTestCases; i++) {
System.out.println("Enter value to check:");
int valueToCheck = sc.nextInt();
isDivisibleByPrime(valueToCheck);
}
Obviously there's no error handling or whatnot, but as you're likely new to this, I'm sure it's not a requirement.
Here's an online example.

Java8-StringIndexOutOfBoundsException

This is my code snippet:
import java.util.Scanner;
public class Numrs {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int pos, i = 1;
char d;
while (num <= 10) {
String line = in.nextLine();
pos = line.length();
if (line.length() <= 1000000) {
if (line.charAt(i) == 'R') {
line.replace('R', 'K');
i++;
}
if (line.charAt(i) == 'K') {
line.replace('K', 'R');
i++;
}
num++;
}
}
}
It's showing a StringIndexOutOfBoundsException when I enter a single digit number like 3, and even if a 2 digit number is entered, it's getting terminated without reading the string. Please help.
Well, if you enter only one character /digit, then size will be 1 but it will be placed in index 0. and you are trying to do line.charAt(i) where i=1
There are many problems in this approach.
1. The input you need to pass is more than a digit, like 3 this works because after the 3 your in expects some string.
you are not updating num. So it will end up in an infinite loop
This won't work if you give any value more than 10. I m not sure what you wanted to achieve.
Start i from 0, Developers start with 0 :)

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