If statement and too much printing - java

I can't seem to figure out what is wrong here. In the third scenario if (i == n && i % 2 == 0), I only want it to print out 16 once (as given in the main method). But for some odd reason it prints it out 3 times. Can somebody explain why???
public class Foursix {
public static void main(String[] args) {
printEven(1,7);
printEven(21,2);
printEven(16,16);
//main
}
public static void printEven(int i, int n) {
System.out.print("[ ");
//n is greater than i
if (i <= n) {
for (int t = i; t <= n; t++) {
if (t % 2 == 0) {
System.out.print(t + " ");
//if statement inner
}
//for loop
}
//if statement outer
}
//i is greater than n
if (i >= n) {
for (int t = i; t >= n; t--) {
if (t % 2 == 0) {
System.out.print(t + " ");
//if statement inner
}
//for loop
}
//if statement outer
}
//i is the same as n
if (i == n && i % 2 == 0) {
System.out.print(i);
//if statement
}
System.out.print("]");
System.out.println();
//printEven
}
//class
}

You're passing in 16,16, so all three of your if() conditions are TRUE:
if (i <= n) { 16 <= 16 -> TRUE
if (i >= n) { 16 >= 16 -> TRUE
if (i == n && i % 2 == 0) { 16 == 16 && 16 % 2 -> TRUE
Given that you're explicitly testing for all three of greater than/less than/equal, you probably want these:
if (i < n) { ... }
else if (i > n) { ... }
else if (i % 2 == 0) { ... }

Related

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

Why is my program not continuing after the first 10 Palindromic numbers? And also Why is my isPrime method not returning false for the number 4?

I'm not sure why my ct is not going all the way to 100 even though I clearly set it to go until it reaches 100.
public class PalindromicPrime
{
public static void main(String [] args)
{
int ct = 0;
while(ct < 100)
{
if(isPalindrome(ct) && isPrime(ct))
{
if(ct % 10 != 0)
{
System.out.print(ct + " ");
}
else
{
System.out.print("\n");
}
}
ct++;
}
public static boolean isPalindrome(int p)
{
int palindrome = p;
int reverse = 0;
while (palindrome != 0)
{
int remainder = palindrome % 10;
reverse = reverse * 10 + remainder;
palindrome = palindrome / 10;
}
if (p == reverse)
{
return true;
}
return false;
}
I'm assuming my isPrime code is wrong since I'm getting a 4 in my output. What's wrong with this method?
public static boolean isPrime(int p)
{
for(int i = 2; i < p/2; i++)
{
if(p % i == 0)
{
return false;
}
}
return true;
}
}
First change you should do in your method isPrime() is change this line
for(int i = 2; i < p/2; i++)
to
for(int i = 2; i <= p/2; i++) // you can easily find the reason why it is necessary(=)
And also you are printing palindromic numbers less than 100 which are prime,not first 100 palindrome numbers, if you want to print first 100 palindrome numbers you can take another counter which will keep track of the numbers printed.
You can modify your main method like this:
public static void main(String [] args)
{
int ct = 0,n=0; // n to count numbers printed/found
while(n < 100) // change the condition to check n<100
{
if(isPalindrome(ct) && isPrime(ct))
{
System.out.print(ct + " ");
if(n % 10 == 0)
{
System.out.println();
}
n++; // incementing n after a number is found!
}
ct++;
}
}
Your palindrome method is fine. It's your isPrime method that's not working because to check if a number is prime, you're supposed to test factors up to the square root of the number. So a simple change in the condition should do it,
public static boolean isPrime(int p)
{
for(int i = 2; i <= Math.sqrt(p); i++)
{
if(p % i == 0)
{
return false;
}
}
return true;
}
}
Change your isPrime function to following (replace < with <= as 4/2 is 2 and loop will not run at all for p=4):
public static boolean isPrime(int p) {
for (int i = 2; i <= p / 2; i++) {
if (p % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int ct = 2;
int count = -1;
while (count < 99) {
if (isPalindrome(ct) && isPrime(ct)) {
count++;
if (count % 10 == 0) {
System.out.print("\n" );
}
System.out.print(ct + " ");
}
ct++;
}
}
The only numbers that are palindrome and prime and less than 100 are:
1 2 3 5 7 11
Try changing the value of 100 to 102. Then you get the following output as 101 is the next palindromic prime after 11:
1 2 3 5 7 11 101

Replacing a number with a word 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.

Why does my code of computing Greatest Common Divisor of multiple integers return nothing?

I wrote the following codes to calculate gcd of unspecified number of integers.
import java.util.Scanner;
public class GcdOfUnspecifiedNumberOfIntegers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] list = new int[5];
for (int i = 0; i < 5; i++) {
System.out.println("Enter a number: ");
list[i] = input.nextInt();
}
gcd(list);
}
// Get the gcd of multiple integers
public static void gcd(int...numbers) {
int gcd = 1;
for (int i = 0; i < numbers.length; i++) {
gcd = gcdOfTwo(gcd, numbers[i]);
}
System.out.println("The gcd is: " + gcd);
}
// Get the gcd of two integers
public static int gcdOfTwo(int a, int b) {
int gcdOfTwo = 1;
int possibleGcd = 1;
while (gcdOfTwo <= a && gcdOfTwo <= b) {
if (a % possibleGcd == 0 && b % possibleGcd == 0) {
gcdOfTwo = possibleGcd;
possibleGcd++;
}
}
return gcdOfTwo;
}
}
My thought is to get the gcd of two numbers (say it's GCD), and get the gcd of GCD and the third number, and so on and so forth.
The problem looks like "gcd(list)" isn't working correctly. After I enter all the integers, and press enter key, nothing happens.
--- update ---
I've moved possibleGcd++ out of if statement, but it still has something wrong as the console gave me this:
Enter a number:
1
Enter a number:
2
Enter a number:
3
Enter a number:
4
Enter a number:
5
Exception in thread "main" java.lang.ArithmeticException: / by zero
at GcdOfUnspecifiedNumberOfIntegers.gcdOfTwo(GcdOfUnspecifiedNumberOfIntegers.java:35)
at GcdOfUnspecifiedNumberOfIntegers.gcd(GcdOfUnspecifiedNumberOfIntegers.java:22)
at GcdOfUnspecifiedNumberOfIntegers.main(GcdOfUnspecifiedNumberOfIntegers.java:14)
Solved
I should use while (possibleGcd <= a && possibleGcd <= b) instead of while (gcdOfTwo <= a && gcdOfTwo <= b).
Change your while loop to this :
while (possibleGcd <= a && possibleGcd <= b) {
if (a % possibleGcd == 0 && b % possibleGcd == 0) {
gcdOfTwo = possibleGcd;
}
possibleGcd++;
}
this loop:
while (gcdOfTwo <= a && gcdOfTwo <= b) {
if (a % possibleGcd == 0 && b % possibleGcd == 0) {
gcdOfTwo = possibleGcd;
possibleGcd++;
}
}
runs infinetely since you not increase gcdOfTw (in case you dont get inside if gcdOfTwo = possibleGcd and possibleGcd++ is never executed)
while (gcdOfTwo <= a && gcdOfTwo <= b) {
if (a % possibleGcd != 0 || b % possibleGcd != 0) {
break;
}
gcdOfTwo = possibleGcd;
possibleGcd++;
}

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