0

This program lets the user input a number and checks if the number is prime. However, if want the program to exit when the user inputs the "q". I have tried several things (do while, if) but none of the methods seem to work. How is this caused and how can I solve it?

Below is the source code:

// Test for primes 2
import java.io.*;
class FindPrime2    {
public static void main(String args[])  
throws IOException  {

//      int num;
    boolean isPrime;
    String str;

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    System.out.println("\nFINDING PRIME NUMBERS v0.1");
    System.out.print("\nPlease enter a number: ");


    str = br.readLine();
    if(str == "q") System.exit(1);

    int num = Integer.valueOf(str);


    System.out.println("You have picked: " + num);

    if(num < 2) isPrime = false;
    else isPrime = true;

    for(int i=2; i <= num/i; i++)   {
        if((num % i) == 0)  {
            isPrime = false;
            break;
        }
    }

    if(isPrime) System.out.println(num +" is Prime.");
    else System.out.println(num + " is not Prime.");
}

}

1 Answer 1

6

You can't use ==on strings. You have to use .equals(); if you don't care about case sensitivity, you can use .equalsIgnoreCase ()

The == operator compares the REFERENCES while .equals () compares string CONTENTS

About ==:

The comparison operator == doesn't just work on booleans. What would expect:

 int a = 5;
 int b = 5;

 //What will this display?
 a == b ? System.out.print (” True”) : System.out.print (” false”); 

Use .equals() when:

*Explicitly checking for equal values

*When you want to check for equality of objects; but only if that object overrides and defines the .equals () method.

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you! It works using "if(str.equals("q"))System.exit(1);"
Yep. Just make sure you know why you have to use .equals () And don't forget to accept an answer.
AFAIK, == can only check for boolean values, am I right? Where do I accept an answer? I just clicked on "Answer was useful", was that it?
@sectas I added more information on the differences and uses of == and .equals ()
Thank you for clarifying. But what i meant with boolean value was it can either see whether the == expression is true or false, not read WHAT the input is. I hope that makes sense. But thanks again, I am only in ch5 of my 1200 page book ;)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.