0

I am working on a program that continues to ask the user to input a flight code i.e FR201. The program would then read the flight code and return the airline and the flight number.. but i'm having trouble getting it to work correctly and am just getting "invalid input". Here is what I have tried, any help is appreciated!

import java.util.Scanner;
public class flightcode{
public static void main(String[]args)
{
    String s2;
    do{

    Scanner s1 = new Scanner(System.in);
    System.out.println("Enter a number");

     s2 = s1.nextLine();
    int num = s2.length()-2;
    int s3=0;


    if(s2.substring(0,1)=="EI")
    {
     s3 = 1;
    }

    else if(s2.substring(0,1)=="FR")
    {
    s3 = 2;
    }
    else if(s2.substring(0,1)=="AF")
    {
     s3 = 3;
    }
    else if(s2.substring(0,1)=="AA")
    {
     s3 = 4;
    }
    else if(s2.substring(0,1)=="IB")
    {
     s3 = 5;
    }



    switch (s3)

    {

        case 1: System.out.println("Airline: Aer Lingus - Flight number:" + s2.substring(2)); break;
        case 2: System.out.println("Airline: Ryanair - Flight number:" + s2.substring(2)); break;
        case 3: System.out.println("Airline: Air France - Flight number:" + s2.substring(2)); break;
        case 4: System.out.println("Airline: American Airlines - Flight number:" + s2.substring(2)); break;
        case 5: System.out.println("Airline: Iberia - Flight number:" + s2.substring(2)); break;
        default: System.out.println("Invalid input"); break;

    }
    }
        while(s2!= "END");


    }
}
  • 1
    `substring(0,1) = ""+charAt(0)`. It cannot return "EI". Plus, you should use the `equals()` or `equalsIgnoreCase()` function to compare Strings. – progyammer Nov 05 '16 at 12:47
  • I don't quite understand what you mean by substring(0,1) =""+charAt(0), thanks for your help though. – Alex Mccane Nov 05 '16 at 14:14
  • `substring(0,1)` returns the first character of the string in string form. So it's similar to `charAt(0)`, save the value returned by substring is `string` unlike `charAt()` – progyammer Nov 05 '16 at 14:19

1 Answers1

0

The problem is not in the switch. Read this: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int)

I recommend that you use assertions for things that should never happen. Such as the code going through the else of your if chain.

Javier
  • 2,752
  • 15
  • 30