Java 从单独的语句中提取字符串

Java 从单独的语句中提取字符串,java,Java,在我的代码中,我在if-else语句中创建了一个名为name的字符串。但是,我需要在单独的语句中使用相同的字符串。这个新语句创建一个名为的新文件(无论name中的字符串是什么) 我尝试在新语句中使用变量name时出错,因为它无法识别。我怎样才能解决这个问题 if (r == JFileChooser.APPROVE_OPTION) { String name = chooser.getSelectedFile().getName(); System.out.println(n

在我的代码中,我在if-else语句中创建了一个名为
name
的字符串。但是,我需要在单独的语句中使用相同的字符串。这个新语句创建一个名为的新文件(无论
name
中的字符串是什么)

我尝试在新语句中使用变量
name
时出错,因为它无法识别。我怎样才能解决这个问题

if (r == JFileChooser.APPROVE_OPTION) {
     String name = chooser.getSelectedFile().getName();
     System.out.println(name); //this is where I create string name
     name = name.replace(".asm", ".hack"); 
}
新声明

try{
    PrintWriter writer = new PrintWriter("file.hack", "UTF-8"); //instead of using "file.hack", I need the new file to be called name
    writer.println(stringBuffer);
    writer.close();
} catch (IOException e) {
   // do something
}

Scanner input = new Scanner(new File("file.hack"));
while (input.hasNextLine())
{
  System.out.println(input.nextLine());
}

首先定义变量,以便跨块访问变量范围

String name = null;
if (r == JFileChooser.APPROVE_OPTION) {
    name = chooser.getSelectedFile().getName();
}
try {
    if (name != null) {
        PrintWriter writer = new PrintWriter(name, "UTF-8");
        ...
    }
} catch 

或者先定义编写器,然后将
try
移动到
if

因此,即使用户未在文件选择器中批准,您也要读取文件?既然用户没有选择任何文件名,那么文件名应该是什么?请检查此链接:。这可能会对你有所帮助。事实上,你的问题历史表明你可能正在走向一个问题区。让我们尽量避免这种情况。请添加将
name
variable移到'if'块之外的解释。