Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
        }
    }

}
like image 435
Kabeltv Avatar asked Mar 05 '13 16:03

Kabeltv


3 Answers

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.

like image 132
Pradeep Simha Avatar answered Nov 19 '22 19:11

Pradeep Simha


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.

like image 28
Sean Landsman Avatar answered Nov 19 '22 17:11

Sean Landsman


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.

like image 4
kaysush Avatar answered Nov 19 '22 18:11

kaysush