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");
Related
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)
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);
}
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++;
}
my problem is the following. If I input number 2, the code counts it as an odd number.
Remainder for 2 / 2 = 0 so the error doesn't make sense.
Below is the program:
import java.util.Scanner;
public class Ohjelma {
public static void main(String[] args) {
// Tänne voit kirjoittaa ohjelmakoodia. Ohjelmasi voit ajaa
// valitsemalla menusta Run->Run File tai painamalla Shift+F6
Scanner reader = new Scanner(System.in);
System.out.println("Type numbers: ");
int number = Integer.parseInt(reader.nextLine());
int sum = 0;
int many = 0;
double average = 0;
int even = 0;
int odd = 0;
while (number != -1) {
System.out.println("Type numbers: ");
sum = sum + number;
number = Integer.parseInt(reader.nextLine());
many++;
average = (double)sum / many;
if (number%2 == 0) {
even++;
} else {
odd++;
}
}
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + many);
System.out.println("Average: " + average);
System.out.println("Even numbers: " + even);
System.out.println("Odd numbers: " + odd);
The main problem is that for the critical part of your program it largely ignores the first input, apart from adding it to the running sum. You want to recast it like this:
Scanner reader = new Scanner(System.in);
int sum = 0;
int many = 0;
double average = 0;
int even = 0;
int odd = 0;
do {
System.out.println("Type numbers: ");
number = Integer.parseInt(reader.nextLine());
if (number == -1)
break;
sum = sum + number;
many++;
average = (double)sum / many;
if (number%2 == 0) {
even++;
} else {
odd++;
}
} while (true);
This will certainly processes even and odd numbers correctly.
Your code reads the second line of input into number before it checks whether number is odd ... and -1 is odd.
I am doing an assignment and have most of what i think will work down, i have to promt the user for random numbers, then display how many negatives as well as positives then sum and average, can anyone help me as i cannot get my code to display the correct amount of values for negative or positive or get it to sum. Here is what i have so far( i also added the break in the end , otherwise it went to an infinate loop)
//Random number evaluation
package chapter_4;
import java.util.Scanner;
public class Four_One {
public static void main(String[] args) {
int positive = 0;
int negative = 0;
int sum = 0;
int count = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter in a value, if 0 is entered program stops: ");
int data = input.nextInt();
while (data != 0) {
sum += data;
if (data < 0)
negative++;
else if (data > 0)
positive++;
count++;
System.out.println("The number of positives is: " + positive);
System.out.println("The number of negatives is:" + negative);
System.out.println("The total is: " + sum);
System.out.println("The average is: " + sum / data);
break; }
}
}
You are not asking for the nextInt() within the while loop - you do want to ask more than once, correct?
Your average is not an average. I suggest dividing by count instead of data.
at the end of the loop (instead of the break) add data = input.nextInt();
btw for average you should display sum/(double)count (the cast to double is there so you'll see the fraction)
This might help you.
Explanation: Using a do-while loop might be easier because it asks for input and than checks the input. Also put the input statement inside the do-While loop so it asks for multiple inputs.
public static void main(String[] args)
{
int positive = 0;
int negative = 0;
int sum = 0;
int count = 0;
Scanner input = new Scanner(System.in);
int data = 0;
do
{
System.out.print("Enter in a value, if 0 is entered program stops: ");
data = input.nextInt();
sum += data;
count ++;
if(data < 0)
negative ++;
else if(data > 0)
positive ++;
}
//Stops if the value of data is ZERO(0) and continues if it's not
while(data != 0);
System.out.println("Positive Numbers = " + positive);
System.out.println("Negative Numbers = " + negative);
System.out.println("Sum of Numbers = " + sum);
System.out.println("Total Numbers = " + count);
}
import java.util.Scanner;
public class Four_One {
public static void main(String[] args) {
int positive = 0;
int negative = 0;
int sum = 0;
int count = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter in a value, if 0 is entered program stops: ");
int data = input.nextInt();
while (data != 0) {
sum += data;
if (data < 0)
negative++;
else if (data > 0)
positive++;
count++;
data = input.nextInt();
}
System.out.println("The number of positives is: " + positive);
System.out.println("The number of negatives is:" + negative);
System.out.println("The total is: " + sum);
System.out.println("The average is: " + sum / (double)count);
}
}