Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get else if statement to work in Java

Ok I am trying to make this simple thing but it won't work. I am a beginner in Java and would like some help. Every time I run the code below I get the output That is not a valid option. What am I doing wrong?

 package test;

 import java.util.Scanner;

 public class options {
     public void options() {
         Scanner scnr = new Scanner(System.in);
         String slctn;

         System.out.println("What would you like to do?");
         System.out.println("a) Travel the expedition");
         System.out.println("b) Learn more about the expedition");

         slctn = scnr.nextLine();
         if (slctn == "a"){
             travel exeTravel = new travel();
             exeTravel.travel();
         }else if (slctn=="b"){
             learn exeLearn = new learn();
             exeLearn.learn();
         }else{
             System.out.println("That is not a valid option");
         }
     } 
 }
like image 554
Theo Vasiloudes Avatar asked Dec 12 '22 03:12

Theo Vasiloudes


1 Answers

Well, first off, == is a fundamental operator in the language. The result type of the expression is a boolean. For comparing boolean types, it compares the operands for the same truth value. For comparing reference types, it compares the operands for the same reference value (i.e., refer to the same object or are both null). For numeric types, it compares the operands for the same integer value or equivalent floating point values. See the Java Language Specification.

In contrast, equals() is an instance method which is fundamentally defined by the java.lang.Object class. This method, by convention, indicates whether the receiver object is "equal to" the passed in object. The base implementation of this method in the Object class checks for reference equality. Other classes, including those you write, may override this method to perform more specialized equivalence testing. See the Java Language Specification.

The typical "gotcha" for most people is in using == to compare two strings when they really should be using the String class's equals() method. From above, you know that the operator will only return "true" when both of the references refer to the same actual object. But, with strings, most uses want to know whether or not the value of the two strings are the same -- since two different String objects may both have the same (or different) values.

     slctn = scnr.nextLine();
     if (slctn.equals("a")){
         travel exeTravel = new travel();
         exeTravel.travel();
     }else if (slctn.equals("b")){
         learn exeLearn = new learn();
         exeLearn.learn();
     }else{
         System.out.println("That is not a valid option");
     }
like image 141
Subhrajyoti Majumder Avatar answered Feb 22 '23 04:02

Subhrajyoti Majumder