This question already has answers here:
Computing prime numbers up to N integers
(6 answers)
Calculating and printing the nth prime number
(11 answers)
Closed last year.
I am new to Java and am currently trying to create a program that will determine if the entered number is prime or composite. I've figured out most of it, but there's one part that has me stumped.
I want the code to print a message stating either "the number needs to be greater than 1" if a 0 or a negative number is entered, or "one is neither prime nor composite" if a 1 is entered.
Here's my code:
public class Main {
public static void main(String[] args) {
int num;
boolean prime = true;
String answer;
Scanner keyboard = new Scanner(System.in);
do {
System.out.print("Please enter a number ==> ");
num = keyboard.nextInt();
if (num < 1)
System.out.println("The number entered needs to be greater than one.");
else if (num == 1)
System.out.println("One is neither a prime nor composite number.");
else {
for (int ii = 2; ii <= num/2; ii++) {
if (num % ii == 0) {
prime = false;
break;
}
}
}
if (prime == true)
System.out.println("The integer " + num + " is prime.");
else {
System.out.println("The integer " + num + " is composite.");
}
System.out.print("Would you like to go again? (yes/no) ");
answer = keyboard.next();
System.out.print("\n");
} while (answer.equals("yes"));
}
}
My issue is that when I run the code and enter a 0, 1, or negative number, the code prints the correct message but adds "The integer "0, 1, -#" is prime."
I don't want it to do so, and only want it to print the corresponding message. What am I missing?
This code is executing no matter the value of num:
if (prime == true)
System.out.println("The integer " + num + " is prime.");
else {
System.out.println("The integer " + num + " is composite.");
}
To fix you can just move this inside the else statement
if (num < 1)
System.out.println("The number entered needs to be greater than one.");
else if (num == 1)
System.out.println("One is neither a prime nor composite number.");
else {
for (int ii = 2; ii <= num/2; ii++) {
if (num % ii == 0) {
prime = false;
break;
}
}
if (prime == true)
System.out.println("The integer " + num + " is prime.");
else {
System.out.println("The integer " + num + " is composite.");
}
}
Just move the print statements inside else to fix the logic.
Also, some more improvements are possible to exclude even numbers except 2, and look for the primes until a square root of num is achieved.
if (num < 1)
System.out.println("The number entered needs to be greater than one.");
else if (num == 1)
System.out.println("One is neither a prime nor composite number.");
else {
prime = num % 2 == 1 || num == 2;
for (int ii = 3; prime && ii * ii <= num; ii += 2) {
if (num % ii == 0) {
prime = false;
}
}
if (prime)
System.out.println("The integer " + num + " is prime.");
else {
System.out.println("The integer " + num + " is composite.");
}
}
The reason it is printing the statements is because the if piece of code will always run in case the value is less than 1 ( as you have already initialized prime boolean to be true ). A fix to this to to move the last if statement inside the else part.
public class Main {
public static void main(String[] args) {
int num;
boolean prime = true;
String answer;
Scanner keyboard = new Scanner(System.in);
do {
System.out.print("Please enter a number ==> ");
num = keyboard.nextInt();
if (num < 1)
System.out.println("The number entered needs to be greater than one.");
else if (num == 1)
System.out.println("One is neither a prime nor composite number.");
else {
for (int ii = 2; ii <= num / 2; ii++) {
if (num % ii == 0) {
prime = false;
break;
}
}
if (prime == true)
System.out.println("The integer " + num + " is prime.");
else {
System.out.println("The integer " + num + " is composite.");
}
}
System.out.print("Would you like to go again? (yes/no) ");
answer = keyboard.next();
System.out.print("\n");
} while (answer.equals("yes"));
}
}
then it does not give the additional print statement as earlier.
Please enter a number ==> 1
One is neither a prime nor composite number.
Would you like to go again? (yes/no)
Related
import java.util.*;
public class Eigth {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int x=0, number1, number2;
System.out.print("Enter first number: ");
number1=s.nextInt();
if(number1 == x) {
System.out.println("Error");
System.exit(0);
}
System.out.print("Enter second number: ");
number2=s.nextInt();
if (number2 == x) {
System.out.println("Error");
System.exit(0);
}
if(number2 <= number1) {
System.out.println("Error");
System.exit(0);
}
while (number1 <= number2) {
if ((number1 % 2) == 0)
System.out.println("\"" + number1 + " IS EVEN\"");
else
System.out.println("\"" + number1 + " IS ODD\"");
number1++;
}
int evenSum = 0, oddSum = 0, i = number1;
while(i <= number2) {
if(i % 2 == 0) {
evenSum += i;
}
else {
oddSum += i;
}
i++;
}
System.out.println("Sum of Even Numbers in Loop: " + evenSum);
System.out.println("Sum of Odd Numbers in Loop: " + oddSum);
System.out.println("Sum of All Numbers in Loop: " + evenSum + oddSum);
}
}
I have to prompt the user for two numbers and the first number entered is what the loop should start at and the second number entered is what the loop should go up to. If the first or second number is 0, I have to print out error. If the second number is not greater than the first, I have to do the same thing. Then, I have to print out the sum of all even, odd, and total sum of the numbers in the loop. However, with the code I have, it prints out as Sum of All even numbers: 0, sum of all odd numbers:0, and sum of all numbers: 0 , no matter what numbers I put in. I'm not sure where I'm going wrong.
No need to have a separate variable to keep the total sum as the sum of even and odd would return the total sum. Also, the while loop looks a bit complicated. you could simplify as below:
int evenSum = 0, oddSum = 0;
int i = number1;
while(i <= number2) {
if(i % 2 == 0) {
evenSum += i;
} else {
oddSum += i;
}
i++;
}
System.out.println("Sum of Even Numbers in Loop: " + evenSum);
System.out.println("Sum of Odd Numbers in Loop: " + oddSum);
System.out.println("Sum of All Nuumbers in Loop: " + (evenSum + oddSum));
You need to change the int i = 0 to int i = number 1 as you want to start from the number that is inputted.
Also putting these at the end works
System.out.println("Sum of Even Numbers in Loop: " + evenSum);
System.out.println("Sum of Odd Numbers in Loop: " + oddSum);
System.out.println("Sum of All Nuumbers in Loop: " + totalSum);
The output depends on the numbers input, if the first number input is smaller than the second number input then it gives the numbers. I tested this with the first number being 2 and the second number being 4 and my output was:
Enter a number
2
Enter another number
4
Sum of Even Numbers in Loop: 6
Sum of Odd Numbers in Loop: 3
Sum of All Numbers in Loop: 9
With another input:
Enter a number
8
Enter another number
20
Sum of Even Numbers in Loop: 54
Sum of Odd Numbers in Loop: 36
Sum of All Numbers in Loop: 90
After doing your range checks on number1 and number2 you can shorten your algorithm a little by using the remainder value as an index into an array to tally the values.
int[] sums = new int[2];
while (number1 <= number2) {
sums[number1 % 2] += number1++;
}
System.out.println("Sum of Even Numbers in Loop: " + sums[0]);
System.out.println("Sum of Odd Numbers in Loop: " + sums[1]);
System.out.println("Sum of All Numbers in Loop: " + (sums[0] + sums[1]));
Scanner sc = new Scanner(System.in);
boolean flag = true;
while(flag){
int start = sc.nextInt();
int end = sc.nextInt();
if((end - start) <= 0 || start == 0 || end == 0){
System.out.println("Error");
}else{
int evenSum = 0, oddSum = 0;
for(int i = start; i <= end; i++){
if(i % 2 == 0){
evenSum += i;
}else{
oddSum += i;
}
}
System.out.println("Sum of Even Numbers in Loop: " + evenSum);
System.out.println("Sum of Odd Numbers in Loop: " + oddSum);
System.out.println("Sum of All Numbers in Loop: " + (evenSum + oddSum));
flag =false;
}
}
inputs: 1 5
Output:
Sum of Even Numbers in Loop: 6
Sum of Odd Numbers in Loop: 9
Sum of All Numbers in Loop: 15
The first while loop is to take inputs until the user give valid inputs.
Michael, you have made a simple logical error. The origin of the error is in the first while loop. Here is the first while loop in your code:
while (number1 <= number2)
{
if ((number1 % 2) == 0)
System.out.println("\"" + number1 + " IS EVEN\"");
else
System.out.println("\"" + number1 + " IS ODD\"");
number1++;
}
The error is that you are constantly updating variable number1 here. After the first while loop add this statement:
//Debugging
System.out.println ("number1: " + number1 + " number2: " + number2);
For example: If you inputted number1 as 2 and number2 as 6. Then the above statement if placed after the first while loop, will print the following.
number1: 7 number2: 6
Since the value of number1 is always greater than number2, and you assign this updated value of number1 to i, this part of your code will never execute.
//if number1 = 2 and number2 = 6
//before the starting of the while loop below, the value of `i` is 7
//which is greater than number2 which is 6
while(i <= number2)
{
if(i % 2 == 0)
{
evenSum += i;
}
else
{
oddSum += i;
}
i++;
}
For your second doubt, you can get the correct answer if you change your statement to this:
//This statement is old and causing error
System.out.println ("Sum of All Numbers in Loop: " + evenSum+oddSum);
//This is updated statement that gives correct answer
//Notice the added brackets
System.out.println ("Sum of All Numbers in Loop: " + (evenSum+oddSum));
The reason this happens is because if you do not use extra brackets, evenSum and oddSum will be considered as String (You said you are a beginner. If you do not know what String is, skip this explanation. You will be taught later about it and then you will be able to understand it). which results in string concatenation. However, after using the extra brackets, evenSum and oddSum will be considered as int and normal addition is performed which results in total sum.
I also made an extra change and removed variable x. It was not necessary to use it. The if can be changed to this:
//Replace x with 0
if (number1 == 0)
{
System.out.println("Error");
System.exit(0);
}
Here is the whole updated code with added comments for better understanding:
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
//No need of x here
int number1, number2 , tempNumber1;
System.out.print("Enter first number: ");
number1 = scanner.nextInt();
//Replace x with 0
if (number1 == 0)
{
System.out.println("Error");
System.exit(0);
}
System.out.print("Enter second number: ");
number2 = scanner.nextInt();
//Replace x with 0
if (number2 == 0)
{
System.out.println("Error");
System.exit(0);
}
if( number2 <= number1)
{
System.out.println("Error");
System.exit(0);
}
//Storing the value of number1 is necessary to preserve its value
tempNumber1 = number1;
while (number1 <= number2)
{
if ((number1 % 2) == 0) System.out.println("\"" + number1 + " IS EVEN\"");
else System.out.println("\"" + number1 + " IS ODD\"");
number1++;
}
//Use total, it keeps the logic straight
//You can also use only oddSum and evenSum and calculate total later
//See below for more information
int evenSum = 0, oddSum = 0, i = tempNumber1, total = 0;
while(i <= number2)
{
if(i % 2 == 0) evenSum += i;
else oddSum += i;
total += i;
i++;
}
System.out.println("Sum of Even Numbers in Loop: " + evenSum);
System.out.println("Sum of Odd Numbers in Loop: " + oddSum);
//If you do not use total and have only used oddSum and evenSum, use the below commented line
//System.out.println ("Sum of All Numbers in Loop: " + (evenSum+oddSum));
System.out.println("Sum of All Numbers in Loop: " + total);
}
An advice: If you are not sure what is happening, try using System.out.println(*what you want to print*) for checking the value of different variables. I did this in my answer. If you want to see where, find the statement which has a //debugging comment above it . It will help you to find errors more quickly.
I hope I have helped you.
Sorry for such a question, but I just can't get through to it why the following code is not working
as it is supposed to.
As written in the title, a user should enter an integer for the code to check if it's prime.
If it is not, the user gets to enter an other int, but max 5 times.
I think the primality check is working, but what bothers me is the recursion, because it prints out
too much when first given a not-prime number and then a prime.
I hope somebody could explain to me why it is that way... :)
Here is the code:
import java.util.Scanner;
public class Task6v5 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an int: ");
int a = scan.nextInt();
int counter = 0;
isPrime(a, counter, scan);
}
public static void isPrime(int a, int counter, Scanner scan) {
boolean prime;
do {
if (a <= 1) {
counter = counter + 1;
System.out.println("Int to small. Enter a bigger one."
+ " Counter: " + counter);
a = scan.nextInt();
isPrime(a, counter, scan);
} else if (a == 2) {
prime = true;
} else if (a % 2 == 0) {
counter = counter + 1;
System.out.println("This int is even, "
+ "but not a 2. "
+ "Enter an other int."
+ " Counter: " + counter);
a = scan.nextInt();
isPrime(a, counter, scan);
}
for (int i = 2; i <= Math.sqrt(a); i++) {
if (a % i == 0) {
//System.out.println("Are we there?");
//isPrime = false;
counter = counter + 1;
System.out.println("This int is not a prime. "
+ "Enter an other int. Counter: " + counter);
a = scan.nextInt();
isPrime(a, counter, scan);
}
}
prime = true;
System.out.println("This is a prime.");
} while (counter <= 5 && prime == false);
}
}
I get this output for example:
Enter an int:
1
Int to small. Enter a bigger one. Counter: 1
4
This int is even, but not a 2. Enter an other int. Counter: 2
5
This is a prime.
This is a prime.
This int is not a prime. Enter an other int. Counter: 2
Every time your function returns, it is going to end up here:
prime = true;
System.out.println("This is a prime.");
Number is a 1? Ends up printing "This is a prime".
Number is a 2? Ends up printing "This is a prime".
Number is a 4? Ends up printing "This is a prime".
Number is 42? Well, that ends up printing "This is a prime" lots of times, once for every function call you make.
In order to get the recursive aspect of this correct, you have to return when you want the function to stop.
That being said, this approach won't work for what you're trying to accomplish. Focus on the algorithm first, and separate the part where you're counting the number of integers entered from the part where you're determining whether the integer is a prime.
Personally I would not use recursion here, start with prime = true, set it to false when necessary, and ask for a new number at the end of the outer loop:
public static void isPrime(int a, int counter, Scanner scan) {
boolean prime;
do {
prime = true; // <---
if (a <= 1) {
counter = counter + 1;
System.out.println("Int to small. Enter a bigger one."
+ " Counter: " + counter);
//a = scan.nextInt();
//isPrime(a, counter, scan);
prime = false; // <---
} else if (a == 2) {
prime = true; // well, it was true already
} else if (a % 2 == 0) {
counter = counter + 1;
System.out.println("This int is even, "
+ "but not a 2. "
+ "Enter an other int."
+ " Counter: " + counter);
//a = scan.nextInt();
//isPrime(a, counter, scan);
prime = false; // <---
} else { // now it's necessary, so 2 won't be tested
for (int i = 2; i <= Math.sqrt(a); i++) {
if (a % i == 0) {
counter = counter + 1;
System.out.println("This int is not a prime. "
+ "Enter an other int. Counter: " + counter);
//a = scan.nextInt();
//isPrime(a, counter, scan);
prime = false; // <---
break; // so the message doesn't get repeated many times
}
}
}
if(prime) {
System.out.println("This is a prime.");
} else {
a = scan.nextInt();
}
} while (counter <= 5 && prime == false);
}
My instructions are "Write a program that prompts the user for a number, then counts up (a ‘for’ loop) from one to that number and prints whether that loop number is even or odd (which will require an ‘if-else’ structure inside the loop)." So it needs to list:
1 is odd
2 is even
3 is odd...
public class AssmtEvenOrOddJulianP {
public static void main(String[] args) {
//variable
int num = 0;
//input
System.out.print("\nEnter a number less than 100: ");
num = Expo.enterInt();
//output
for (int i = 1; i <= num; i++)
if ((num % 2) == 0)
System.out.print("\n" + i + " Is Even");
else if ((num % 2) >= 0)
System.out.print("\n" + i + " Is Odd");
Right now if I input 3 it will print:
1 is odd
2 is odd
3 is odd
Minor mistake:
You should calculate the remainder of i by 2, not num by 2.
Always wrap for and if/else blocks in curly braces:
for (int i = 1; i <= num; i++) {
if ((i % 2) == 0) {
System.out.print("\n" + i + " Is Even");
} else if ((num % 2) >= 0) {
System.out.print("\n" + i + " Is Odd");
}
}
Avoid using redundant parantheses:
for (int i = 1; i <= num; i++) {
if (i % 2 == 0) {
System.out.print("\n" + i + " Is Even");
} else if (num % 2 >= 0) {
System.out.print("\n" + i + " Is Odd");
}
}
The else if condition has a minor bug that is "unreachable" right now, but could cause pain in the future
num % 2 >= 0 should be i % 2 < 0 || i % 2 > 0
The else if condition can be simplified to else:
for (int i = 1; i <= num; i++) {
if (i % 2 == 0) {
System.out.print("\n" + i + " Is Even");
} else {
System.out.print("\n" + i + " Is Odd");
}
}
Final result:
With some other minor improvements:
public class EvenOdd {
public static void main(String[] args) {
// input
System.out.print("\nEnter a number less than 100: ");
// variable
int num = Expo.enterInt();
System.out.println();
// output
for (int i = 1; i <= num; i++) {
if (i % 2 == 0) {
System.out.println(i + " Is Even");
} else {
System.out.println(i + " Is Odd");
}
}
}
}
The Following program will help you . for odd and Even number we need to divide by 2 and if number is divisible by 2 then number is Even Number (in this case reminder will be 0) and if the reminder is 1 then its Odd Number
public class EvenAndOddNumber {
public static void main(String[] args) {
System.out.println("Enter the number");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
for (int i = 1; i <= num; i++) {
if (i % 2 == 0) {
System.out.println(i + " is even number");
} else {
System.out.println(i + " is odd number");
}
}
}
}
public class Ex51 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter as many integers as you wish. Enter 0 to stop." + "\nReturns "
+ "\nNumber of negative integers input. " + "\nNumber of positive integers input." + "\nTotal sum."
+ "\nMean.");
int i = 0;
int sum = 0;
int temp = 0;
int minusCount = 0;
int plusCount = 0;
float mean = 0;
boolean isZero = false;
do {
System.out.print("Enter an integer: ");
temp = input.nextInt();
if (temp == 0 && i == 0) {
isZero = true;
break;
} else if (temp < 0) {
minusCount++;
} else if (temp > 0)
plusCount++;
if (temp != 0) {
i++;
sum += temp;
mean = (float) sum / (float) i;
}
} while (temp != 0);
if (!isZero) {
System.out.printf("\nThe number of positives is: %d" + "\nThe number of negatives is: %d"
+ "\nThe total is: %d" + "\nThe average is: %.2f", plusCount, minusCount, sum, mean);
} else {
System.out.println("No numbers are entered except 0.");
}
}
}
And this is a sample run:
Enter as many integers as you wish. Enter 0 to stop. Returns
Number of negative integers input. Number of positive integers
input. Total sum. Mean. Enter an integer: 8 Enter
an integer: 6 Enter an integer: 20 Enter an integer: -2
Enter an integer: 0 The number of positives is: 3 The
number of negatives is: 1 The total is: 32 The average is:
8$00
My problem is right at the bottom: 8$00
When I specify %.2f for the float with no special characters in between.
The desired output would be "8.00" for arg mean.
I posted all of the code because I think I would make obvious any beginner mistakes fairly obvious and if not is there any issues with my settings.
I'm running this on Eclipse with jre9.
You are missing a number before '.' for example 2.2f.
For the rest of the code, for initializing you can do it all in one line. The last if statement is useless because you already verified in the first if it is 0, so you dont need a condition for this one. And you will not get there anyway because your while condition is that temp is not 0.
For the mean you can do:
mean = (float)(sum/i);
I think you are just complecating your life.
you could do this:
int temp = 1;
int positive = 0;
int negative = 0;
int i = 0;
int sum = 0;
while (temp != 0)
{
System.out.print("Please enter an integer:");
temp = input.nextInt();
if(temp == 0)
//your print statement here
else if(temp > 0)
positive ++;
else
negative ++;
sum += temp;
i++;
}
For this assignment I need to take in a serious of inputs until 0 is entered which will terminate the code. After the input of each number it needs to output whether that number was prime or not. Then after inputting zero the code should stop and give some description of the numbers entered such as max, min, sum, etc.
My issue is that regardless of what number I put in, it says that every number is prime and I cannot seem to understand why. Any help would be greatly appreciated!
import java.util.Scanner;
public class Assignment4
{
public static void main (String[] args)
{
int input;
int max = 0;
int min = 100000000;
double sum = 0;
int count= 0;
double average = 0;
Scanner scan = new Scanner(System.in);
boolean isPrime;
do
{
System.out.println("Enter a postive integer. Enter 0 to quit");
input = scan.nextInt();
for (int i =2; i<= input/2; i++) //Determine if prime
{
if (input % i == 0)
isPrime = false;
else
isPrime = true;
if (isPrime = true)
System.out.println("The number " + input + " is a prime number");
else
System.out.println("The number " + input + " is not a prime number");
if (input > max)
{
max = input;
}
if (input < min)
{
min = input;
}
sum += input;
count = count + 1;
average = sum/count;
break;
}
}
while (input != 0);
System.out.println("The Max is " + max);
System.out.println("The Min is " + min);
System.out.println("The sum is " + sum);
System.out.println("The total numbers are " + count);
System.out.println("The average is " + average);
}
}
You are setting isPrime to true if i is not a divisor. If the last i you check is not a divisor, isPrime will be false even though there might have been a divisor in a previous iteration.
Solution: Remove the assignment to false and set isPrime to true before starting the for loop:
import java.util.Scanner;
public class Assignment4 {
public static void main (String[] args) {
int input;
int max = 0;
int min = 100000000;
double sum = 0;
int count= 0;
double average = 0;
Scanner scan = new Scanner(System.in);
boolean isPrime;
do
{
System.out.println("Enter a postive integer. Enter 0 to quit");
input = scan.nextInt();
isPrime = true; // I added this line
for (int i =2; i<= input/2; i++) //Determine if prime
{
if (input % i == 0) {
isPrime = false;
break;
}
//else
// isPrime = true;
}
if (isPrime)
System.out.println("The number " + input + " is a prime number");
else
System.out.println("The number " + input + " is not a prime number");
if (input > max)
{
max = input;
}
if (input < min)
{
min = input;
}
sum += input;
count = count + 1;
average = sum/count;
}
while (input != 0);
System.out.println("The Max is " + max);
System.out.println("The Min is " + min);
System.out.println("The sum is " + sum);
System.out.println("The total numbers are " + count);
System.out.println("The average is " + average);
}
}
Code untested, I am on my phone currently
Fun fact:
You just need to loop to Math.sqrt(input) (square root). To illustrate it: If input/2 is a divisor, 2 is a divisor too ;)
I can see a few problems:
1) Change:
if (input % i == 0)
isPrime = false;
else
isPrime = true;
To:
if (input % i == 0)
isPrime = false;
And insert
isPrime=true;
before the for loop.
(Because just because the current value of i is not a divisor does not make it prime).
2) Change:
if (isPrime = true)
To:
if (isPrime==true)
Or:
if (isPrime)
3) Delete break;
4) Check if isPrime is true outside the loop, after all the divisors have been checked, not in it.
5) Check values of i up to and including the square root of input, not half of it. It's quicker.
David Sherret is correct, you have an error in that if statement. It needs to change to if( isPrime ).
Also, you are printing the results of every input % i test. That output should happen after the for loop.
Right now, when testing 15, your code will print out:
The number 15 is a prime number
The number 15 is not a prime number
The number 15 is a prime number
The number 15 is not a prime number
The number 15 is a prime number
The number 15 is a prime number
This is because:
(15 % 2) equals 1
(15 % 3) equals 0
(15 % 4) equals 3
(15 % 5) equals 0
(15 % 6) equals 3
(15 % 7) equals 1
and you are printing the results for each of these tests.
Before the for loop, initialize isPrime with true and then only set it to false inside the loop if the number is not prime. Then, test isPrime after the loop and print the statement. Like this:
isPrime = true;
for (int i =2; i<= input/2; i++) //Determine if prime
{
if (input % i == 0)
isPrime = false;
if (input > max)
{
max = input;
}
if (input < min)
{
min = input;
}
sum += input;
count = count + 1;
average = sum/count;
break;
}
if (isPrime)
System.out.println("The number " + input + " is a prime number");
else
System.out.println("The number " + input + " is not a prime number");