Reputation: 8768
package GC;
import java.util.Scanner;
public class main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Calculate exam grade needed(e) or final grade received(f)?");
String x = input.nextLine();
if (x == "e"){
double q1, q2, f, e;
Scanner inputa = new Scanner(System.in);
Scanner inputb = new Scanner(System.in);
Scanner inputc = new Scanner(System.in);
System.out.print("Quarter 1: ");
q1 = inputa.nextInt();
System.out.print("Quarter 2: ");
q2 = inputb.nextInt();
System.out.print("Final grade wanted: ");
f = inputc.nextInt();
e = 5*(f-0.4*(q1)-0.4*(q2));
if(e == (int)e){
System.out.println((int)e);
}
else{
e = 0.01*((int)(e*100));
System.out.println(e);
}
}
else if (x == "f"){
}
else{
System.out.println("ERROR");
}
}
}
Even if I input e at the beginning, it always goes to the else statement. I may have done something wrong with getting a String from user input or with my if parameters. What am I missing?
Upvotes: 0
Views: 846
Reputation: 178481
if (x == "e"){
You should compare String
objects with equals()
and not operator==
. You should also be aware of equalsIgnoreCase()
, which checks for equality of String
s, while ignoring which case each character is - it might be useful sometimes.
operator==
checks for identity - if the two objects are actually the same object [the variables referencing the same object], while equals()
is checking for equality - if their content is the same.
change
if (x == "e"){
to
if ("e".equals(x)) {
and do the same for else if (x == "f"){
Upvotes: 3
Reputation: 2234
You need to use the "equals" compare method. X is a string and there is no overloading operator for "==" on it to compare values.
Always take a look at the javadocs for an object if you're unsure.
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html
if(x.equals("e")){
}
Upvotes: 1
Reputation: 36156
try (maybe you are getting a blank space:
String x = input.nextLine().toString().trim()
or
x.equals("e")
Upvotes: 0