Prime number program Boolean not working properly [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Below is the code for a java programming class I am writing. I cannot figure out why it always prints it is a prime number (true) reguardless of the int I input. Thank you in advance. Jared
import java.util.*;
public class PrimeNumbersExample
{
public static void main(String[] args)
{
int myInt = 0;
Scanner kb = new Scanner(System.in);
System.out.println("Please enter a number: ");
myInt = kb.nextInt();
boolean isPrime = true;
{
for (int i = 2; i < myInt; i++) // exclude 1 and the variable num from the diviso
if (myInt % i == 0)
isPrime = false;
}
if (isPrime=true)
System.out.println("It is a Prime number.");
else if (isPrime=false)
System.out.println("the number is NOT PRIME");
}
}

You are not doing the comparison correctly. You just have to say if(isPrime) instead of if(isPrime=true) because isPrime is already a boolean.
System.out.println(isPrime ? "Prime" : "Non-Prime");
Even if you want to do a comparison you should be using == instead of just =.
if (isPrime == true) {
System.out.println("It is a Prime number.");
} else {
System.out.println("the number is NOT PRIME");
}
Additionally, you can use a break statement inside your if to make it stop once the number is identified as Non-Prime.
for (int i = 2; i < myInt; i++) {
if (myInt % i == 0) {
isPrime = false;
break;
}
}
Here is the corrected code snippet:
public static void main(String[] args)
{
int myInt = 0;
Scanner kb = new Scanner(System.in);
System.out.println("Please enter a number: ");
myInt = kb.nextInt();
boolean isPrime = true;
for (int i = 2; i < myInt; i++) { // exclude 1 and the variable num from the diviso
if (myInt % i == 0) {
isPrime = false;
break;
}
}
System.out.println(isPrime ? "Prime" : "Non-Prime");
}

In the line, if (isPrime=true) what you are going to do is to check whether the isPrime is true, but what the exactly happening is it assign the value true to isPrime and evaluate to true inside the if condition. So what you exactly should do is if (isPrime==true). The corrected code is as follows,
import java.util.*;
public class PrimeNumbersExample
{
public static void main(String[] args)
{
int myInt = 0;
Scanner kb = new Scanner(System.in);
System.out.println("Please enter a number: ");
myInt = kb.nextInt();
boolean isPrime = true;
{
for (int i = 2; i < myInt; i++) // exclude 1 and the variable num from the diviso
if (myInt % i == 0)
isPrime = false;
}
if (isPrime==true)
System.out.println("It is a Prime number.");
else if (isPrime==false)
System.out.println("the number is NOT PRIME");
}
}
*Note - also you can directly use isPrime variable inside the if condition since it is Boolean

The statement if (isPrime=true) is actually just assigning the value true to the isPrime variable which will always return true. That's why the first condition is always executed
You can just simply do it like this :
if (isPrime) {
System.out.println("It is a Prime number.");
} else {
System.out.println("the number is NOT PRIME");
}
Also, always put braces for readability

Try this one.
public class MyPrimeNumCheck {
public boolean isPrimeNumber(int number){
for(int i=2; i<=number/2; i++){
if(number % i == 0){
return false;
}
}
return true;
}
public static void main(String a[]){
MyPrimeNumCheck mpc = new MyPrimeNumCheck();
System.out.println("Is 17 prime number? "+mpc.isPrimeNumber(17));
System.out.println("Is 19 prime number? "+mpc.isPrimeNumber(19));
System.out.println("Is 15 prime number? "+mpc.isPrimeNumber(15));
}
}

Related

Prime Numbers in Java (return next prime when false)

public class PrimeNumbers {
public static void main(String[] args) {
int num = 6;
boolean isPrime = true;
for (int i = 2; i <= num - i; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
int nextPrime = num++;
{
while (isPrime = false) {
}
if (isPrime)
System.out.println("Is a prime number");
else
System.out.println("Is not a prime number" + "the next prime number is" + nextPrime(num));
}
}
}
I have tried to code in Java in order to find the next prime number while the previously returned is false, but I am really confused about how to proceed with "while" code. This is what I have tried until now:
You can create two functions: one (say, isPrime) to check if the number is prime or not and the second (say, nextPrime) to find the next prime. The logic in the second function will be quite straight forward: keep incrementing the number by 1 until isPrime returns true.
Note that you need to check only up to the square root of the number in order to determine if it is prime. Check https://en.wikipedia.org/wiki/Primality_test to learn more about it.
Demo:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = scanner.nextInt();
if (isPrime(n)) {
System.out.println("It is a prime number");
} else {
System.out.println("It is not a prime number. The next prime number is " + nextPrime(n));
}
}
static boolean isPrime(int n) {
if (n == 1 || n == 0) {
return false;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
static int nextPrime(int n) {
while (!isPrime(n)) {
n++;
}
return n;
}
}
A sample run:
Enter an integer: 10
It is not a prime number. The next prime number is 11
Another sample run:
Enter an integer: 11
It is a prime nmber
How about this snippet?
public static void main(String[] args) {
int number= 14; // will print the second SOUT statement with 17
if (isPrime(number)) {
System.out.println(number+ " is a prime number");
} else {
System.out.println(number+ " is not a prime number, " +
"the next prime number is " + nextPrime(number));
}
}
/**
* Check if the number is a prime number
* For 0 or 1 you can return false, for the rest if is divisible by each number
* You might want to throw an exception for the negative input
*/
static boolean isPrime(int number) {
if (number==0 || number==1) {
return false;
}
for (int i=2; i<=number/2; i++) {
if (number%i==0) {
return false;
}
}
return true;
}
/**
* Iterate the number by one until you find a prime number using the while cycle
*/
static int nextPrime(int number) {
int prime;
while (true) {
boolean isPrime = isPrime(++number);
if (isPrime) {
prime = number;
break;
}
}
return prime;
}
In order to find a prime number, you basically need a nested loop. So I'd recomend having your for loop INSIDE the while loop. OR you can have a do-while loop on the outside that keeps looping until you found a prime number.
Your code should look like this:
public class PrimeNumbers {
public static boolean check_prime(int num){
for (int i = 2; i <= num-i ; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args){
int num = 6;
boolean isPrime= true;
if(!check_prime(6)){
int nextPrime = num;
do{
nextPrime++;
if (check_prime(nextPrime)) {
isPrime = true;
break;
}else{
isPrime = false;
}
}while(!isPrime);
}
if (isPrime)
System.out.println("Is a prime number");
else
System.out.println("Is not a prime number" +"the next prime number is" + nextPrime);
}}}

Suggestions to improve code about primes?

I wrote a code about primes and would hear your opinion or any suggestions how i can improve my code. I'm a beginner in Java.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean a;
System.out.println("Please enter a number: ");
int zahl = s.nextInt();
if(zahl <= 0) {
System.out.println("Please enter a positive number without zero.");
return;
}
a = true;
for (int i = 2; i < zahl; i++) {
if (zahl % i == 0) {
a = false;
}
}
if (a == true) {
System.out.println("Is Prim");
}
if (a==false){
System.out.println("Not a prim");
}
}
The easiest thing to do is the following
Instead of
for (int i = 2; i < zahl; i++) {
if (zahl % i == 0) {
a = false;
}
}
change the for loop the
for (int i = 2; i < Math.sqrt(zahl); i++)
If no numbers up to the square root divide zahl, then no numbers beyond the square root will divide it either (they would have been the result of earlier divisions).
Also, for outputing the answer you could do:
System.out.println(zahl + " is " + ((a) ? "prime"
: "not prime"));
That's using the ternary operator ?:
some hints :
You do
System.out.println("Please enter a positive number without zero.");
return;
the println suggests the user can enter a new value, but no, in that case better to say the number was invalid so you exit
When you do a = false; it is useless to continue, no chance for a to be back true
It is useless to try to divide by more than sqrt the number
It is necessary to try to divide by 2 but not by an other even number, so add 2 to i rather than 1
If if (a == true) false it is useless to check if (a==false)
Your code is good. I have made three small improvements:
The input asks at once (and not only after a bad input) for a
positive int.
The input is repeated until correct.
The for loop runs only up to sqrt(zahl) which is sufficient.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean a;
int zahl = 0;
while (zahl <= 0) {
System.out.println("Please enter a positive int without zero.");
zahl = s.nextInt();
}
a = true;
for (int i = 2; i <= Math.sqrt(zahl); i++) {
if (zahl % i == 0) {
a = false;
break;
}
}
if (a == true) {
System.out.println("Is Prim");
} else {
System.out.println("Not a prim");
}
}

Error:Variable might not have been initialised [duplicate]

This question already has answers here:
Java: Error: variable might not have been initialized
(2 answers)
Closed 4 years ago.
I don't know what is wrong with this code and why it is giving the error:
Variable isPrime might not have been initialized
This is the complete code:
import java.util.Scanner;
public class PrimeNumberTest {
//Program to test for prime numbers
public static void main(String[] args) {
Scanner prime = new Scanner(System.in);
int number;
boolean isPrime;
System.out.print("Please enter number: ");
number = prime.nextInt();
if (number < 2)
isPrime = false;
else{
for (int i = 2; i < number / 2; i++)
if (number % i == 0){
isPrime = false;
break;
}
}
if (isPrime)
System.out.println("Your number is a prime number");
else
System.out.println("Your number is not a prime number");
}
}
boolean isPrime = false;
Just initialize isPrime boolean.

Trying to find the next prime number, not sure whats wrong. Java

im fairly new to Java and just cant figure out why my program is not working. Anything anyone can do to help would be appreciated!
public class LabOne {
public static void main(String[] args) {
System.out.println("Please input a number: \n");
int inputReceive = 44;
int nextPrime = inputReceive;
int n = 5;
boolean isprime=true;
do {
if(inputReceive <= 1)
isprime = false;
else if(inputReceive <= 3){
System.out.printf("%d \n",isprime);
return;
}else if( inputReceive % 2 == 0 || inputReceive % 3 == 0)
isprime = false;
while ((n*n)<inputReceive){
if (inputReceive % n == 0 || inputReceive % (n + 2) == 0)
isprime = false;
n = n+6;
isprime = true;
}
nextPrime++;
}while(isprime = false);
System.out.printf("Next prime number is %d",nextPrime);
}
}
output given would be 45 and thats not correct.
A few problems:
while(isprime = false);
That's assignment, not equality testing. Since you're assigning false, this won't loop.
n = n+6;
isprime = true;
You do this unconditionally.
Expansion to follow.
Ignoring things already pointed out, you perform all of your checks on inputRecieve and never update it. You only unconditionally update nextPrime and moreover never check its primeness. Here is how I would do it:
public static boolean isPrime(int x){
boolean result = true;
for(int i = 2; i<=Math.sqrt(x); i++){
if((x % i) == 0){
result = false;
}
}
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please insert a number:");
int inputRecieve = sc.nextInt();
boolean notPrime = true;
while(notPrime){
if(isPrime(++inputRecieve))
notPrime = false;
}
System.out.println("Next prime number is: " + inputRecieve);
}

How to reject inputs that are non digit characters?

My professor assigned to write a prime number "finder". Where the number you input will display if it's a prime or even number, then display the next prime number. He wants us to give an error message when the wrong input is keyed in. I figured the negative integer portion is simple, but I cannot figure out the character input. Or if the character is not a digit. How would i block non numeric inputs?
Also, the system is supposed to exit at three CONSECUTIVE erroneous inputs. How would I reset the counter? The way i have written the program, if the user makes two errors but the next ones are acceptable, then make another error. (thus not being consecutive.) the program closes.
This is my first programing course so I'm not to savvy in it. Any help would be greatly appreciated.
Also, i have to use scanner, and the two methods.
/**
*
* #param n
* #return
*/
public static boolean isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static int nextPrime(int n) {
n++;
isPrime(n);
while (isPrime(n) == false) {
n++;
isPrime(n);
}
int prime = n;
return prime;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int answer = 2;
int counter = 1;
boolean playAgain = false;
Scanner input = new Scanner(System.in);
Scanner reader = new Scanner(System.in);
Scanner in = new Scanner(System.in);
do {
//ask for input
System.out.print("\nEnter the integer value-> ");
//input answer
int n = input.nextInt();
{
//decide is negative
while ( n < 0){
//count counter
counter++;
//give error message
System.out.println("\nInvalid Input! Stike!");
//ask for input
System.out.print("\nEnter the integer value-> ");
//input answer
n = input.nextInt();
//decide is character
// if ( n != '.'){
//count counter
// counter++;
//give error message
// System.out.println("\nInvalid Input! Strike!");
// }
//decide if count three errors
if (counter == 3){
//display three errors message
System.out.println("Three Strikes! You're Out!");
//close program
System.exit(0);
}
}
//decide if prime
if (isPrime(n)) {
//display prime answer
System.out.println(n + " Is Prime");
//decide if even
} else {
//display even answer
System.out.println(n + " Is Even");
}
//counter input
n++;
//while input is false
while (isPrime(n) == false) {
n++;
}
//display next prime
System.out.println(n + " Next prime");
{
//ask if you want to continue
System.out.println("\nPlay Again?\n\nEnter 1)Yes or 2)No ");
//input answer
answer = in.nextInt();
//if answer is 1)yes
if (answer == 1) {
playAgain = true;
//display play again and next input
System.out.println("\nPlay Again!");
}
//if answer is no
if (answer == 2) {
playAgain = false;
System.out.println("\nGoodbye!");
//close program
System.exit(0);
}
}
}
} while (playAgain != false);
}
}
import java.util.Scanner;
public class SOQ5B
{
public static boolean isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static int nextPrime(int n) {
n++;
isPrime(n);
while (isPrime(n) == false) {
n++;
isPrime(n);
}
int prime = n;
return prime;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int answer;
int counter = 0;
int n;
boolean playAgain = true;
boolean isNum;
boolean isNum2;
boolean continuePermitted = true;
Scanner input = new Scanner(System.in);
String s;
do {
//ask for input
System.out.print("\nEnter the integer value-> ");
s = input.nextLine();
isNum = true;
for(int i = 0; i < s.length(); i++)
{
if(!(s.charAt(i) >= '0' && s.charAt(i) <= '9'))
{
isNum = false;
}
}
if(isNum)
{
counter = 0;
n = Integer.parseInt(s);
//decide if prime
if (isPrime(n)) {
//display prime answer
System.out.println(n + " Is Prime");
//decide if even
}
else {
//display even answer
System.out.println(n + " Is Even");
}
//counter input
n++;
//while input is false
while (isPrime(n) == false) {
n++;
}
//display next prime
System.out.println(n + " Next prime");
do
{
continuePermitted = true;
//ask if you want to continue
System.out.println("\nPlay Again?\n\nEnter 1)Yes or 2)No ");
//input answer
s = input.nextLine();
isNum2 = true;
for(int i = 0; i < s.length(); i++)
{
if(!(s.charAt(i) >= '0' && s.charAt(i) <= '9'))
{
isNum2 = false;
}
}
if(isNum2)
{
answer = Integer.parseInt(s);
//if answer is 1)yes
if (answer == 1) {
playAgain = true;
//display play again and next input
System.out.println("\nPlay Again!");
}
//if answer is no
if (answer == 2) {
playAgain = false;
System.out.println("\nGoodbye!");
//close program
System.exit(0);
}
}
else
{
System.out.println("Incorrect response.");
continuePermitted = false;
//if answering the yes or no question incorrectly is part of the 3 strikes
//then uncomment the following lines of code
/*
counter++;
}
if(counter >= 3)
{
System.out.println("3 strikes you out");
System.exit(0);
*/
}
}while(!continuePermitted);
}
else
{
System.out.print("\nIncorrect input. Number must be a positive integer.\n");
counter++;
}
if(counter>=3)
{
System.out.println("3 strikes and you're out!");
System.exit(0);
}
} while (playAgain != false);
}
}
In the future, I recommend you research your questions on the internet before bringing the question here. There were several other places that could've easily answered your question.
Now as for your actual question, notice how I changed your code at the line that says s = input.nextLine()? What I did there is checked to see if each digit in the string was any number between and including 0-9. Not only was I able to check if they were all numbers, but I was also able to see if they were all positive too as you would have to put a - in order for it to be negative. Along with that, you also have a boolean that only works when the input is a positive number. If not, it checks 3 times to make sure your program doesn't mess up. Furthermore, I even commented out another section that allows the 3 strikes to include if answering the yes no question counts as a strike. If there any other questions, just ask and I will edit my answer.
You are trying to take input using Scanner class with
int n = input.nextInt();
If you enter a character in place of number here you will get java.util.InputMismatchException
What you can do is something like
try {
int n = input.nextInt();
} catch (InputMismatchException e) {
//handle the error scenario where the input is a character
System.out.println("Enter Valid Input");
}

Categories

Resources