mercredi 22 mars 2017

Why does the following code not work properly? (Java)

My goal is to receive user input and find out whether or not it's a prime number.

'Been slaving away at this for hours, and it almost works. However, when I enter 2 or 3, I don't get anything. The do-while loop just skips to the next iteration.

The for loop I created doesn't work for 2 or 3, so I created a separate if statement for that. The thing is, it doesn't work. And I've no clue as to why except that it probably doesn't execute.

import java.util.Scanner;

public class Lab4a {
    public static void main (String [] args) {
    Scanner scnr = new Scanner(System.in); //creates a Scanner that will receive user input
    boolean isPrime = false; //this, in the end, is where the "primeness" of the input is stored
    int num; //the variable which will store the user input
    boolean isOver = false; //is true once the "primeness" of the input has been decided

    do { //executes at least once
        System.out.println("Enter a positive integer or 0 to exit:"); //prompts the user for input
        num = scnr.nextInt(); //stores the input

        if (num == 0) { //if the number is zero, the loop terminates; if it's negative, the loop terminates as well
            System.exit(0);
        } else if (num < 0) {
            System.out.println("Please enter a positive integer.");
            System.exit(1);
        }

        for (int mult = 2; mult <= num/2; mult++) { //divides the user input by 2, tests for if anything remains; increments by one up to the half of the number. If a remain is encountered,
                                                    // isPrime becomes false and isOver true and the for loop is terminated. If not, the for loop will end with isPrime true and isOver false
            if (num % mult == 0) {
                isPrime = false;
                isOver = true;
                break;
            } else {
                isPrime = true;
                isOver = true;
            }

        }

        if (num == 2 || num == 3) { //the for test above does not work if the user input is 2 or 3, so a separate if statement tests for that
            isPrime = true;
        }
    } while (!isOver); //if isOver is true, the while loop ends



        if (isPrime == true) { //prints the appropriate answer
            System.out.println(num + " is prime.");
        } else {
            System.out.println(num + " isn't prime.");
        }
    }
}

I usually try to solve these problems myself, but I have, again, been slaving away at this for literally 4 hours and I still have another, similar program to write and a calculus quiz to prepare for tomorrow, in which I know exactly jack shit. I'm really desperate.

TL;DR: The program doesn't work properly when I input 2 or 3; probably because the if statement doesn't run. Beyond that, I know nothing.

Thanks for any help!

Aucun commentaire:

Enregistrer un commentaire