Search code examples
javaswitch-statementfilepathfilewriter

FileWriter usage error with switch case in Java


I'm trying to write into different files according to the case. However there are still something that I could not realise yet while using FileWriter in cases, it gives error to change the name of the "wrtr"

So, I would be appreciated if someone can help me!

package test;

import java.io.FileWriter;

public class FileWrt {

static String aaa = new String("store/aaa.txt");
static String bbb = new String("store/bbb.txt");
static String ccc = new String("store/ccc.txt");

public void foo(String text) {
   String path = new String(text);

   switch (path) {
    case aaa:
        FileWriter wrtr = new FileWriter(aaa);
        break;
    case bbb:
        FileWriter wrtr = new FileWriter(bbb);
        break;
    case ccc:
        FileWriter wrtr = new FileWriter(ccc);
        break;
    }
}

Solution

  • Declare your FileWriter outside of the switch statement as follows:

    public void foo(String text) {
       String path = new String(text);
       FileWriter wrtr = null;
    
       switch (path) {
        case aaa:
            wrtr = new FileWriter(aaa);
            break;
        case bbb:
            wrtr = new FileWriter(bbb);
            break;
        case ccc:
            wrtr = new FileWriter(ccc);
            break;
        }
    }
    

    The way you have it now, you're declaring three variables with the same name in the same scope. That makes the compiler unhappy.