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));
}
}
}
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.
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 String
s are the same object, whereas the second checks that they're the same value, which is what you need here.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With