java – 在if-else子句之外无法识别的对象
发布时间:2020-12-15 04:08:39 所属栏目:Java 来源:网络整理
导读:在if-else分支中,我声明了两个具有相同名称的不同PrintStream对象.但是,当我稍后使用PrintStream对象时,编译器会说它“找不到符号”.为什么不看到我创建的对象?该对象使用它声明的if-else分支.这是代码: System.out.println("Welcome. Would you like to c
在if-else分支中,我声明了两个具有相同名称的不同PrintStream对象.但是,当我稍后使用PrintStream对象时,编译器会说它“找不到符号”.为什么不看到我创建的对象?该对象使用它声明的if-else分支.这是代码:
System.out.println("Welcome. Would you like to continue a previous adventure,or begin anew?n(type: new or old)"); status = scan.nextLine(); if(status.equals("new")) { System.out.println("What do you call yourself?"); name = scan.nextLine(); System.out.println("And what shall be the title of your saga,after you are gone?"); game = scan.nextLine(); System.out.println("Very well. Prepare yourself,for this is the beginning of your end...n...n...nAre you ready?"); status = scan.nextLine(); System.out.println("Not that it matters. Let us begin."); status = scan.nextLine(); File file = new File(game + ".txt"); PrintStream print = new PrintStream(file); print.println(name); old = false; } else { System.out.println("So you're still alive? What was the title of your tale?"); game = scan.nextLine(); File file = new File(game + ".txt"); Scanner gscan = new Scanner(file); String save = ""; while (gscan.hasNextLine()) { save += gscan.nextLine(); save += "n"; } System.out.println(save); PrintStream print = new PrintStream(file); print.println(save); old = true; name = scan.nextLine(); } if(old) { } print.println("beans"); 解决方法
您需要在if语句之外声明变量,然后在两个分支中分配它,如下所示:
PrintStream print; if (status.equals("new")) { ... print = new PrintStream(file); } else { ... print = new PrintStream(file); } 更好的是,您可以在if中设置文件,然后在条件之后创建PrintStream: if (status.equals("new")) { ... } else { ... } File file = new File(game + ".txt"); PrintStream print = new PrintStream(file); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容