Search code examples
javaswitch-statementbufferedreader

How can I display a text file inside a switch statement in java?


I am trying to open a text file within a switch statement but I am getting the error 'Illegal start of expression'. I am new to Java so as simple as possible explanation would be appreciated!

Here is my code, ignore the other switch cases:

import java.util.Scanner;
public class journeyPlanner {
public static void main (String[] args){
    Scanner in = new Scanner(System.in);
    System.out.println("  -- MAIN MENU -- \n 1: Display Journeys \n 2: Identify Suitable Journeys \n Q: Quit \n Pick:");
    String Choose = in.next();


    switch (Choose) {

        case "1" : BufferedReader in = new BufferedReader(new FileReader (<"Input.txt">));
                            break;

        case "2" : System.out.println("You answered: " + Choose + ". Please try again.");
                            break;

        case "Q" : System.out.println("You answered: " + Choose + ". That is correct!");
                            break;
            default:
            System.out.println("Please select a valid answer choice.");

    }
}

}


Solution

  • Lets break down the 3 things wrong here:

    • < and > surrounding the filename
    • duplicate variable declaration in
    • missing throws

    First off the compiler complains about the < and >. Fixing them will show problem number 2, fixing that will reveal problem number 3.

    All three can be resolved by changing the main to throwing an exception (or alternatively / better catching it):

    public static void main(String[] args) throws FileNotFoundException 
    

    and changing the BufferedReader line to:

    case "1" : BufferedReader in2 = new BufferedReader(new FileReader ("Input.txt")); break;
    

    Final recommendation: indent your code properly