Replacing a number with a word Java - java

Been digging around the internet just about all day looking for a solution to this problem. I've just started programming about 2 weeks ago nearly and the fact that I don't really know the proper java lingo yet could be the reason I'm not finding what I'm looking for.
Anyway the program is supposed to:
print out all the numbers from 1 to 100 and if during the iteration the program comes across a number that's divisible by 3 it has to replace that number with "Crackle", if it comes across a number that's divisible by 5 it has to replace that number with "Pop" and it comes across a number that's divisible by both then it has to replace that number with "CracklePop
I can't get it to print CracklePop for numbers that are divisable by both 3 and 5, but I can get it to print Crackle & Pop but not replace the numbers.
I've tried using:
Integer.toString(); , Integer.valueOf(); , Integer.parseInt();
None of which I can get to work. This is the code so far:
int counter = 0;
int max = 100;
for (int i = 1; i <= max; i++){
if (counter % 3 == 0) {
System.out.println("Crackle");
}
else if(counter % 5 == 0){
System.out.println("Pop");
}
else if (counter % 3 == 0 && counter % 5 == 0){
System.out.println("CracklePop");
}
System.out.println(counter);
counter++;
}
If if you could also suggest a solution that would be the most robust way of writing a program like this that would be good too.

There is no need for the counter variable. You can just use the i counter itself.
Also you should place the check for both being divisible by 3 and 5 first:
int max = 100;
for (int i = 1; i <= max; i++){
if (i % 3 == 0 && i % 5 == 0){
System.out.println("CracklePop");
} else if (i % 3 == 0) {
System.out.println("Crackle");
} else if(i % 5 == 0){
System.out.println("Pop");
} else {
System.out.println(i);
}
}
The last else will make sure you replace the number with the corresponding string if it matches one of the conditions of being divisible by 3 and/or 5.

for counter = 15 your last 2 else if will never get invoked, you need to re order your if else like
if (counter % 5 == 0 && counter % 3 == 0){
System.out.println("CracklePop");
} else if (counter % 3 == 0) {
System.out.println("Crackle");
} else if(counter % 5 == 0){
System.out.println("Pop");
} else{
System.out.println(counter);
}
still you can store result of % in a boolean variable to avoid multiple time calculation in worst case

You need to put your last else/if statement at the beginning. The problem is, when one of your if statements is valid, it will execute that statement and end the if statement. Your last statement will never be executed. Your statement should be:
public class CodeCracklePop {
public static void main(String[] args) {
int counter = 0;
int max = 100;
for (int i = 1; i <= max; i++){
if (counter % 3 == 0 && counter % 5 == 0){
System.out.println("CracklePop");
}
else if (counter % 3 == 0) {
System.out.println("Crackle");
}
else if(counter % 5 == 0){
System.out.println("Pop");
}
System.out.println(counter);
counter++;
}
}
}

The reason the numbers aren't replaced is because the Crackle and Pop are printed, but the numbers are also printed afterwards. CracklePop never is printed because anything that would fulfill it would just print Crackle instead. You need to reorder your logic in order for it to fit your needs.

Replace
System.out.println(counter);
With
else {
System.out.println(counter);
}
In addition, as Jigar pointed out above you should test for 3 and 5 first

Try this one
public static void main(String[] args) {
int max = 100;
for (int i = 0; i < max; i++) {
if (i % 3 == 0 || i % 5 == 0) {
if (i % 3 == 0) {
System.out.print("Crackle");
}
if (i % 5 == 0) {
System.out.print("Pop");
}
} else {
System.out.print(i);
}
System.out.println();
}
}

public class CodeCracklePop {
public static void main(String[] args) {
/* int counter = 0; omit this*/
int max = 100;
boolean flag = false;
for (int i = 1; i <= max; i++){
if(i % 3 == 0){
System.out.print("Crackle");
flag = true;
}
if(i%5==0){
System.out.print("Pop");
flag = true;
}
if(!flag)
System.out.print(""+i);
flag = false;
System.out.println("");
}
}
}
A fun way of getting the job done.

Related

What am I doing wrong in solving this easy competitive programming question? (Project Euler - Problem 5)

This is my first question on StackOverflow so please pardon any mistakes but let me know about them. I am trying to do problem 5 on Project Euler in Java. I feel like my code is correct but I can not get the answer.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
public class Main {
public static void main(String[] args) {
boolean a = true;
int counter = 0;
int b = 1;
while (a) {
for (int i = 1; i <= 20; i++) {
if (b % i == 0) {
counter++;
}
if (counter == 20) {
System.out.println(b);
a = false;
}
else {
b++;
}
counter = 0;
}
}
}
}
The problem is that your nesting is wrong.
Within the for (int i = 1; i <= 20; i++) loop you increment counter if b is divisible by i.
The you do some checks and in the end set counter to zero again.
That means that your counter only ever reaches a maximum value of 1 (if b is divisible by a specific i).
You probably meant to write
for (int i = 1; i <= 20; i++) {
if (b % i == 0) {
counter++;
}
}
if (counter == 20) {
System.out.println(b);
a = false;
}
else {
b++;
}
counter = 0;
which will give the correct result - although the algorithm is still terribly slow.

Why is eclipse showing it is a dead code?

class PrimeNo {
public static void main(String[] args) {
int n = 8;// assumed to be any random number
int i;
if (n == 0 || n == 1)
System.out.println("Not a prime number");
else {
for (i = 3; i < n; i++) {
if (n % i == 0) {
System.out.println("Not a prime number");
} else {
System.out.println("Prime number");
}
break;
}
}
}
}
I have written a basic code to find a given number is Prime number or not? I tried this by not using flags. Let we assume "n" to be any number. When I run the code it prints both "Prime" and "Not Prime" in different lines. Also, why is this code a dead code? If we go through logic this code should have runned perfectly. Help me out guys!!!
Your break is the culprit, it will break at first iteration, i will never get incremented and hence dead code.
I have written a basic code to find a given number is Prime number or
not? I tried this by not using flags.
Given below is how you can do it without using a flag:
public class Main {
public static void main(String[] args) {
int n = 8;// assumed to be any random number
int i;
if (n == 0 || n == 1)
System.out.println("Not a prime number");
else {
for (i = 2; i < n; i++) {
if (n % i == 0) {
System.out.println("Not a prime number");
break;
}
}
// If n % i == 0 doesn't become true throughout the loop, it means n is prime
if (i == n) {
System.out.println("Prime number");
}
}
}
}
Output:
Not a prime number
Note that I have started the loop from 2 which is also a prime number.
Another important thing to consider is that you do not need to divide and check until n (i.e. i < n), checking till the square root of n is sufficient. Check this to learn more about it. Thus, an efficient way of doing it as follows:
public class Main {
public static void main(String[] args) {
int n = 8;// assumed to be any random number
int i, sqrt = (int) Math.sqrt(n);
if (n == 0 || n == 1)
System.out.println("Not a prime number");
else {
for (i = 2; i <= sqrt; i++) {
if (n % i == 0) {
System.out.println("Not a prime number");
break;
}
}
// If n % i == 0 doesn't become true throughout the loop, it means n is prime
if (i > sqrt) {
System.out.println("Prime number");
}
}
}
}
Output:
Not a prime number
Also, why is this code a dead code?
When your loop runs for i = 3, it will be terminated by break; statement. This, i++ will never get a chance to run and thus, it is a dead code.
Since you are using 'break;' in your code, for loop was running only once. This means the 'i++' part in your for loop was never been called and hence the dead code error.
You might want to write your logic something similar to this:
class PrimeNo {
public static void main(String[] args) {
int n = 8;// assumed to be any random number
int i;
boolean isNumberPrime = true;
if (n == 0 || n == 1)
isNumberPrime = false;
for (i = 2; i < n; i++) {
if (n % i == 0) {
isNumberPrime = false;
}
}
if (isNumberPrime) {
System.out.println("Number is prime number");
} else {
System.out.println("Number is not prime number");
}
}
}
Sorry I missed the no flag part. We could implement the code as below with no flags:
class PrimeNo {
public static void main(String[] args) {
int n = 8; // assumed to be any random number
int i;
if (n == 0 || n == 1)
System.out.println("Number is not prime number");
for (i = 2; n > 1 && i < n; i++) {
if (n % i == 0) {
System.out.println("Number is not prime number");
break;
} else if (i == n - 1) {
System.out.println("Number is prime number");
}
}
}
}

Sequence of integer (in ascending or descending order)

A sequence of whole numbers, check if it is ordered true (in ascending or descending order), otherwise it is false. If a number has the same value as the number below, it will not break the order. The sequence ends with 0.
Sample Input 1: 9 8 7 6 5 4 3 2 1 0
Sample Output 1:true
--------------------------------
Sample Input 2: 1 2 3 3 9 0
Sample Output 2:true
--------------------------------
Sample Input 3: 1 2 5 5 2 3 0
Sample Output 3: false
--------------------------------
I need help, I've been trying for days ... I really appreciate any help ...
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int a = 0;
while (s.hasNextInt()) {
int i = s.nextInt();
a = i;
if (i < a) {
if (i < a) {
System.out.println("true");
} else if (i > a) {
System.out.println("false");
break;
}
} else if (i > a) {
if (i > a) {
System.out.println("true");
} else if (i < a) {
System.out.println("false");
break;
}
} else if (i == a) {
}
}
}
}
I will not tell you the code as that would not be of much help but I can help with the approach you need to take.
With first 2 inputs assess if the pattern will be increasing or
decreasing.
Then with the pattern check if the number is always = or less/greater than the number
Check for the last value. It must be 0 but it may or may not be according to pattern (in some cases it may come as the correct pattern itself confusing if it is a valid number or end of list)
If last number is not 0 then the output should be false.
I assume 0 can't appear anywhere but at the end.
static boolean ordered(Scanner s)
{
int curr, prev;
curr = prev = s.nextInt();
while(s.hasNextInt() && (curr = s.nextInt()) == prev);
if(curr < prev)
while(s.hasNextInt() && (curr = s.nextInt()) <= prev) prev = curr;
else
while(s.hasNextInt() && (curr = s.nextInt()) >= prev) prev = curr;
return curr == 0;
}
Test:
public static void main(String[] args)
{
test("0");
test("1 0");
test("1 1 0");
test("9 9 8 7 6 6 5 4 3 2 1 0");
test("1 1 2 3 3 3 9 0");
test("1 2 5 5 2 3 0");
test("9 8 7 6 7 8 9 0");
}
static void test(String str)
{
System.out.format("%s : %b%n", str, ordered(new Scanner(str)));
}
Output:
0 : true
1 0 : true
1 1 0 : true
9 9 8 7 6 6 5 4 3 2 1 0 : true
1 1 2 3 3 3 9 0 : true
1 2 5 5 2 3 0 : false
9 8 7 6 7 8 9 0 : false
You need to change your code like this:
Scanner sc = new Scanner(System.in);
int prev = sc.nextInt();
int curr = sc.nextInt();
while (sc.hasNextInt() && prev == curr) {
prev = curr;
curr = sc.nextInt();
}
boolean flag = prev < curr;
while (sc.hasNextInt()) {
prev = curr;
curr = sc.nextInt();
if (prev < curr && flag) {
System.out.println("Ascending");
} else if (prev > curr && !flag) {
System.out.println("Descending");
} else if (prev == curr) {
System.out.println("Equal");
} else {
System.out.println("Not sorted");
break;
}
}
You can put this in a method and return false from the else and return true from the end of the method.
Based on the first two inputs (you will need a counter variable e.g. count), decide whether the remaining numbers should be in ascending order or in descending order. You can use a boolean variable e.g. asc to store this result i.e. if the second number is greater than the first number, the value of asc will be true; otherwise, false.
Once you have decided the value of asc from the first two numbers, you need to check if the next number follows this pattern or not. If the next number doesn't follow the pattern, print false and break the processing.
For every number that the scanner reads, you also need to check if it is 0. If yes, print true and break the processing. Also, since your requirement mentions, "If a number has the same value as the number below, it will not break the order.", simply continue when the number read by the scanner has the same value as the last read number.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean asc = true;
int i = 0, j = 0, count = 0;
while (true) {
if (count < 2) {
i = s.nextInt();
if (i == 0) {
System.out.println(true);
break;
}
count++;
} else {
// Store the last input to `i` and read a new number into `j`
i = j;
j = s.nextInt();
// Continue if the new number has the same value as the last read number
if (i == j) {
continue;
}
if (j == 0) {
System.out.println(true);
break;
}
count++;
}
if (count <= 2) {
j = s.nextInt();
// Continue if the new number has the same value as the last read number
if (i == j) {
continue;
}
if (j == 0) {
System.out.println(true);
break;
}
count++;
}
// Based on the first two inputs decide whether the remaining numbers should be
// in ascending order or in descending order.
if (count == 2 && j < i) {
asc = false;
}
// Check if the next number (i.e. the value of `j`) follows this pattern or not
if ((asc == true && j < i) || (asc == false && j > i)) {
System.out.println(false);
break;
}
}
}
}
A sample run:
9 8 7 6 5 4 3 2 1 0
true
Another sample run:
1 2 3 3 9 0
true
Another sample run:
1 2 5 5 2 3 0
false
Another sample run:
9 9 8 0
true
Another sample run:
5 5 6 0
true
The above code is failing on one test condition.
Test Condition:
4 4 1 2 3 0
Minor change needed in the above code i.e, if (i == j && i<j)
So the code will look like:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean asc = true;
int i = 0, j = 0, count = 0;
while (true) {
if (count < 2) {
i = s.nextInt();
if (i == 0) {
System.out.println(true);
break;
}
count++;
} else {
i = j;
j = s.nextInt();
if (i == j) {
continue;
}
if (j == 0) {
System.out.println(true);
break;
}
count++;
}
if (count <= 2) {
j = s.nextInt();
if (i == j && i < j) {
continue;
}
if (j == 0) {
System.out.println(true);
break;
}
count++;
}
if (count == 2 && j < i) {
asc = false;
}
if ((asc == true && j < i) || (asc == false && j > i)) {
System.out.println(false);
break;
}
}
}
}

Prime Number test in java

public static boolean isPrime(int number)
{
boolean result = true;
if (number == 0)
{
result = false;
}
for (int i=2; i < number/2; i++)
{
if (number % i == 0)
{
result = false;
}
}
return result;
}
Any ideas why when int number = 4, the result returns as true? What can I do to fix this? I am happy with the code I have but why does 4 return as true?
for (int i=2; i < number/2; i++)
If you enter 4 here, it will never enter the loop because
2 < 4 / 2
never equates to true (2 is not smaller than 2).
Instead, use <=.
Effective way how to do this method is :
(sorry for duplication, but after some time, someone can find this topic and not previous one)
public static boolean isPrime(int number) {
//Everything less or equal 1 is not prime number
if (number <= 1) {
return false;
}
//2 is very special case, so I check it separately
if (number == 2) {
return true;
}
//This will help me rid off all even numbers
if (number % 2 == 0) {
return false;
}
//It is important to count the sqrt before using it in for-loop condition.
//If you use it in for-loop condition, it will be counted every single iteration.
int square = (int) Math.sqrt(number);
//I already checked %2, so now I need to check only odd numbers
for (int i = 3; i <= square; i += 2) {
if (number % i == 0) {
//If I find one number, I do not have to continue
return false;
}
}
return true;
}
Your for loop never executes when number = 4. This is because:
for (int i=2; i < number/2; i++)
Executes when i == 2 and i < 2. That will never happen if number == 4, because then it'll be i < 4 / 2 which is i < 2. To solve this, remove the /2 or do something else... not quite sure what you're going for there.
When number==4 the boolean condition of the first if is false and the first evaluation of the for condition is also false. So the result is the value you used to initialize result (true).
Also, you might want to return the result instead of storing it in a variable because the code will continue to execute after the first conditional... So here is the working solution:
public static boolean isPrime(int number) {
if (number <= 1) { /* Since 1 isn't technically a prime number */
return false;
}
for (int i=2; i <= number/2; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
Another solution:
public static boolean isPrime(int number) {
if (number < 2) {
return false;
}
for (int i=2; i <= (int)Math.sqrt(number); i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
Better and faster version of your code:
public static boolean isPrime(int number) {
if (number <= 1) {
return false;
}
for (int i=2; i*i <= number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}

Trouble with factor generator

I'm having some trouble in completing this factor generator from my programming class. It's supposed to take a number, and print out all the factors using the nextFactor method. When I set the number to factor to let's say 150, it prints out "1 2 3 5", where it's supposed to print "2 3 5 5". So, where should I go from here? I've looked at Java - Factor Generator program nextfactor method, but it didn't awnser any of my inqueries
public class FactorGenerator
{
//user inputs int from scanner in FactorTester class
public FactorGenerator(int i)
{
num = i;
}
//Checks to see if num can be factored, but does not factor it.
//Goes through all possible factors of num and returns true if the remainder == 0
public boolean hasMoreFactors()
{
for(int i = 1; i < num; i++)
{
//check if the remainder is anything other then 0
if(num % i == 0)
{
return true;
}
}
return false;
}
//Actually factors num and prints out the factor at the end of every loop.
public void nextFactor()
{
for(int i = 1; i < num; i++)
{
//check if the remainder is anything other then 0
if(num % i == 0)
{
System.out.println(i);
num /= i;
}
}
System.out.println("Done.");
}
private int num;
}
try this factors can duplicate so you need to loop until you have extracted all the instances of that factor
public void nextFactor()
{
for(int i = 2; i <= num; i++)
{
//check if the remainder is anything other then 0
while (num >= i && num % i == 0)
{
System.out.println(i);
num /= i;
}
}
System.out.println("Done.");
}
an alternative way is to do the increment in the body of the loop
public void nextFactor()
{
for(int i = 2; i <= num;)
{
//check if the remainder is anything other then 0
if (num % i == 0)
{
System.out.println(i);
num /= i;
} else {
i++;
}
}
System.out.println("Done.");
}
For starters, it will always print out 1 because any integer / 1 will always have remainder of zero. You can start i from 2 instead of 1 in your for if you want to skip 1.
I'd suggest something like this: (note this is based in part on BevynQ's answer below):
for(int i = 2; i <= num; i++){
while (num >= i && num % i == 0) {
System.out.println(i);
num /= i;
}
}

Categories

Resources