1

Right now, when I get "Would you like to continue", if I press y (or Y), the program will just reprint the previous typed in value with the same question afterwards. How can I solve this? Thank you.

class PrimeNumber {
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        int value = 0;
        char choice = 0;

        do {
            System.out.println("Enter integer ");
            value = console.nextInt();

            for (int i = 2; i < value; i++) {
                if (value % i == 0) { // checks if value is evenly divisible by any number
                    System.out.println(value + " is not a prime number ");
                } else {
                    System.out.println(value + " is a prime number ");
                }
                System.out.print("Would you like to continue y/n ");
                choice = console.next().charAt(0);
            }
        } while (choice == 'y' || choice == 'Y');
    }
}
flakes
  • 12,841
  • 5
  • 28
  • 69
Zerenity
  • 107
  • 6
  • 1
    Always indent your code properly. You should now see some larger errors. – flakes Feb 27 '20 at 21:01
  • I had to compile the code before I figured out that one. – NomadMaker Feb 27 '20 at 21:12
  • There is also a problem with the prime number check. – NomadMaker Feb 27 '20 at 21:13
  • Sorry flakes, Im new to java and Im really bad at structuring my code. ill try to practice on that! – Zerenity Feb 27 '20 at 21:19
  • I think the math of the prime factor is fine, its just that it keeps duplicating since its part of the for loop somehow. so if i enter 5, the message of "5 is a prime number" is gonna appear 3 times. i dont know how to fix it – Zerenity Feb 27 '20 at 21:20
  • With your algorithm, the only way to show a number is prime is to go through the loop and not have a match. This isn't a very efficient version, but it's easy to understand. – NomadMaker Feb 27 '20 at 21:58
  • yeah I know, im just trying to get used to the loop system by, possibly, overdoing certain steps, but its for practice i guess – Zerenity Feb 27 '20 at 22:34

4 Answers4

2

You need to address the following things in your code:

  1. You need to check only up to the square root of the number. Check Primality test.
  2. You should break the loop as soon as it is found that the number is not prime.
  3. You need to use console.nextLine() instead of console.nextInt() or console.next(). Check Scanner is skipping nextLine() after using next() or nextFoo()? for more details.

Code incorporating the comments mentioned above:

import java.util.Scanner;

public class PrimeNumber {
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        int value = 0, i;
        char choice = 0;
        boolean valid;
        do {
            valid = true;
            System.out.print("Enter integer: ");
            try {
                value = Integer.parseInt(console.nextLine());
                for (i = 2; i <= Math.sqrt(value); i++) {
                    if (value % i == 0) { // checks if value is evenly divisible by any number
                        System.out.println(value + " is not a prime number ");
                        break;
                    }
                }
                if (i > Math.sqrt(value)) {
                    System.out.println(value + " is a prime number ");
                }
                System.out.print("Would you like to continue y/n: ");
                choice = console.nextLine().charAt(0);
            } catch (NumberFormatException e) {
                System.out.println("This is an invalid input. Try again.");
                valid = false;
            }
        } while (!valid || choice == 'y' || choice == 'Y');
    }
}

A sample run:

Enter integer: a
This is an invalid input. Try again.
Enter integer: 2
2 is a prime number 
Would you like to continue y/n: y
Enter integer: 91
91 is not a prime number 
Would you like to continue y/n: n
Arvind Kumar Avinash
  • 50,121
  • 5
  • 26
  • 72
1
class PrimeNumber {
public static void main(String[] args) {
    Scanner console = new Scanner(System.in);
    int value = 0;
    char choice = 0;

    do {
        System.out.println("Enter integer ");
        value = console.nextInt();

        for (int i = 2; i < value; i++) {
            if (value % i == 0) { // checks if value is evenly divisible by any number
                System.out.println(value + " is not a prime number ");
                break;
            } if(i==value-1){
                System.out.println(value + " is a prime number ");
            }
             }
            System.out.print("Would you like to continue y/n ");
            choice = console.next().charAt(0);

    } while (choice == 'y' || choice == 'Y');
}
}
Adnan
  • 496
  • 2
  • 9
  • a minus one? why minus 1 :O i dont understand. – Zerenity Feb 27 '20 at 22:28
  • 2
    bcoz , last iteration for I will be value -1 , and since all the values from 2 to the number is checked , thus the number is prime , run this code you will understand better it's logic , – Adnan Feb 27 '20 at 22:47
0

You are asking the user to answer y or n while still inside the for loop. Try debugging your app to see how it behaves while you're executing it.

Sir Beethoven
  • 313
  • 1
  • 8
  • right right, i i tried to change the location of one of my curly braces, tried every spot, nothing helps. maybe i have a wrong loop type somewhere – Zerenity Feb 27 '20 at 21:24
  • 1
    It works fine once it's in the right place. Think of the flow of control of the program. The for loop calculates the prime, and the do/while loop is to redo the entire "get an integer/check for prime" part of the code. So the while loop is outside of the for loop. You might look at it from the outside-in. That is, the do/while loop contains the user-interface (asking the user to input a number, and if they want to continue. The for loop is inside of this, calculating the prime after the user has given a number. – NomadMaker Feb 27 '20 at 21:48
  • 1
    When I get confused on which brace is closing the other, I start from the top, just clicking the open-braces, and seeing where the IDE (e.g. Eclipse, Netbeans, InteliJ) will highlight the matching brace which is closing the one I clicked. Also, @flakes is right, indentation is the right way to go, it will make your reading much easier. – Sir Beethoven Feb 27 '20 at 22:09
  • @Zerenity if any of the answers solved your problem, please accept it as the solution. And when you get enough points to be allowed to up-vote, remember to up-vote the ones which were useful as well. – Sir Beethoven Feb 27 '20 at 22:33
  • got it, finally got it sorted out :D – Zerenity Feb 27 '20 at 23:15
0

I went through your program and fixed it, including the prime number loop. I made three changes:

  1. I moved the end of the do-while loop so that it doesn't repeat things.
  2. I fixed the prime number loop. To do this I added a boolean "isPrime" which is set to false whenever a number is found to be non-prime.
  3. I changed the ending condition to entering a value of 0 or less. I did this because when I tested it, I kept accidentally entering my next number where it asked me if I wanted to continue.

    import java.util.Scanner;

    class PrimeNumber{ public static void main(String[] args) { Scanner console = new Scanner(System.in);

        int value = 0;
        boolean isPrime = true;     // This needs to be set to true before the for loop
    
        do{
            System.out.println("Enter integer ");            
            value = console.nextInt();
    
            // End the program if a value is less than or equal to zero
            if (value <= 0) {
                System.out.println("bye bye");
                break;
            }
    
            isPrime = true;
            for(int i = 2; i < value; i++){
    
                if(value % i == 0){ // checks if value is evenly divisible by any number
                    System.out.println(value + " is not a prime number ");
    
                    // No sense in continuing this if it's not prime
                    isPrime = false;
                    break;
                }
            }
    
            // If the loop goes all the way through, then value is prime
            if (isPrime) {
                System.out.println(value + " is a prime number ");
            }
    
            System.out.println("value = " + value);
        } while (value > 0);
    
        console.close();
    }
    

    }

One thing that may help you is to get an IDE such as BlueJ. One thing that it does well is to show you the blocks of code.

NomadMaker
  • 378
  • 1
  • 4
  • 8
  • Thanks, but now my "would you like to continue" thingy is gone which was part of my exercise question :C is BlueJ like an extension, or is it an editor. right now im using jgrasp. is bluej a better choice? – Zerenity Feb 27 '20 at 22:27