no.Idea
no.Idea

Reputation: 3

Trying to figure out how to System.exit with a character

I'm new at Java and coding and I'm trying to do a calculator where you type in the operation you want and then two numbers. The calculation is done inside a switch named "mth" but I cannot figure out how to exit my program using a character.

As you can see I have tried using,

if(op.equals("x")) System.exit(0);

but it seems that the program does not register it at all.

I have tried a number of things as using a boolean and playing around a bit but I can't get past this.

public static void main(String[] args) throws IOException {

    Locale.setDefault(new Locale("sv","SE"));
    Scanner op = new Scanner(System.in);

    System.out.println("Operation och två heltal (x för att avsluta)");

    while(op.hasNext()){

        if (op.equals("x")) {
        System.exit(0);
        }
        else{
        mth(op.next(), op.nextInt(), op.nextInt());
        }

    }


}

Upvotes: 0

Views: 224

Answers (3)

Ankur Singhal
Ankur Singhal

Reputation: 26077

It should be

if (op.next().equals("x")) {

instead of

if (op.equals("x")) {

op is the complete Scanner object, so need to take the value out using op.next() from the op object and then compare.

Upvotes: 1

Ahmed
Ahmed

Reputation: 184

op.equals("x") replaced with op.next().equals("x") or better "x".equals(op.next())

Upvotes: 0

LordAnomander
LordAnomander

Reputation: 1123

That is because you compare the Scanner with "x" and not the sign entered. You could use String input = op.next() and then if (input.equals("x")) System exit(0);

Edit: I think it is better to use an additional variable for this comparison as using op.next() twice might lead to unwanted results. By using an extra variable you can use mth(input, ...) afterwards.

Upvotes: 0

Related Questions