【问题标题】:FileWriter usage error with switch case in JavaJava 中的开关盒的 FileWriter 使用错误
【发布时间】:2014-08-09 15:28:11
【问题描述】:

我正在尝试根据情况写入不同的文件。但是,在某些情况下使用 FileWriter 时我仍然无法意识到一些事情,更改“wrtr”的名称会出错

所以,如果有人可以帮助我,我将不胜感激!

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;
    }
}

【问题讨论】:

    标签: java switch-statement filepath filewriter


    【解决方案1】:

    switch 语句之外声明您的FileWriter,如下所示:

    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;
        }
    }
    

    您现在的方式是在同一范围内声明三个具有相同名称的变量。这会让编译器不高兴。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-30
      • 1970-01-01
      • 2021-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-18
      相关资源
      最近更新 更多