Kabeltv
Kabeltv

Reputation: 61

Scanner isn't scanning my input

i'm trying to read a line and then go into a if-statement. But after it have red the first input it just terminates. I have no idea what's wrong, and I can't figure it out

import java.util.Scanner;

public class mainen {

    public static void main(String[] args) {
        Formler form = new Formler();
        Scanner Sscan = new Scanner(System.in);
        Scanner Dscan = new Scanner(System.in);
        String input;
        System.out.println("Formler: Molmassa");
        input = Sscan.nextLine();

        if(input == "molmassa" || input == "Molmassa"){
            double m;
            double M;
            System.out.println("Massa: "); m = Dscan.nextDouble();
            System.out.println("Molmassa: "); M = Dscan.nextDouble();
            System.out.println(form.getMolmassa(m, M));
        }
    }

}

Upvotes: 6

Views: 205

Answers (4)

Pradeep Simha
Pradeep Simha

Reputation: 18123

Change your if statement to:

if(input.equalsIgnoreCase("molmassa") ) {  }

Then it should work as you expect. Remember always compare strings using equals() or equalsIgnoreCase() method. == compares object references not the actual values.

Upvotes: 9

kaysush
kaysush

Reputation: 4836

The problem is in you if condition change it to

if(input.equalsIgnoreCase("molmassa) )

and every thing should work fine.

One more thing you don't need to have separate Scanner to take String and double input you can use one Scanner object for both the inputs.

Upvotes: 4

Sean Landsman
Sean Landsman

Reputation: 7179

You need to replace the equals checks:

 if(input == "molmassa" || input == "Molmassa"){

with the following;

 if(input.equals("molmassa") || input.equals("Molmassa")){

The first checks if the Strings are the same object, whereas the second checks that they're the same value, which is what you need here.

Upvotes: 4

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41200

if(input == "molmassa" || input == "Molmassa"){}

You should equal String object with equals method or equalsIgnoreCase method.

if(input.equalsIgnoreCase("Molmassa")){}

== is used for primitive equaling check.

Upvotes: 3

Related Questions