非法启动表达式字符串
我正在尝试制作一个程序来反转文件中的文本行 . 我还在学习java,我是新手 . 我的程序出错了,因为我在循环中创建了一个变量并尝试在外部访问它 . 我在声明字符串变量之前尝试添加前缀“public”,但是当我尝试编译它时,它指向“public”并且表示非法启动表达式 . 有人可以告诉我为什么这是错误的,或者如何解决它 .
import java.io.*;
import java.util.*;
public class FileReverser
{
public static void main(String[] args)
throws FileNotFoundException
{
Scanner console = new Scanner(System.in);
System.out.print("File to Reverse: ");
String inputFileName = console.next();
System.out.print("Output File: ");
String outputFileName = console.next();
FileReader reader = new FileReader(inputFileName);
Scanner in = new Scanner(reader);
PrintWriter out = new PrintWriter(outputFileName);
int number = 0;
while (in.hasNextLine())
{
String line = in.nextLine();
public String[] lines;
lines[number] = line;
number++;
}
int subtract = 0;
for (int i;i>lines.length;i++)
{
out.println(lines[(lines.length-subtract)]);
subtract++;
}
out.close();
}
}
回答(3)
2 years ago
问题:
您使用 public 修饰符声明了 lines ,它仅用于实例/静态变量,而不是局部变量 .
你永远不会初始化 lines
你试图在其范围之外使用 lines (目前是 while 循环)
你试图在不初始化的情况下使用 i ,这里:
for (int i;i>lines.length;i++)
你的 if 条件是错误的方式;你想在 i 小于 lines.length 时继续
subtract 最初为0,因此访问 lines[lines.length - subtract] 会抛出异常(因为它超出了数组的范围)
您可以使用以下代码修复这些问题:
// See note later
String[] lines = new String[1000];
while (in.hasNextLine()) {
String line = in.nextLine();
lines[number] = line;
number++;
}
// Get rid of subtract entirely... and only start off at "number"
// rather than lines.length, as there'll be a bunch of null elements
for (int i = number - 1; i >= 0; i--) {
out.println(lines[i]);
}
现在,这将适用于多达1000行 - 但是有这种限制是很痛苦的 . 最好只使用 List :
List lines = new ArrayList();
while (in.hasNextLine()) {
lines.add(in.nextLine());
}
然后你需要使用 size() 而不是 length ,并使用 get 而不是数组索引器来访问值 - 但它将是更清晰的代码IMO .
2 years ago
这是一个范围问题 . lines 应该在while循环之外声明 . 通过将 lines 放在while循环中,它仅在该循环内可用 . 如果将其移到外面, lines 的范围将在main方法中 .
变量的范围是可以访问变量的程序部分 .
2 years ago
访问修饰符( public , private , protected )仅适用于类成员(方法或字段) .
如果要访问受 { 和 } 限制的范围之外的变量,则表示您在错误的范围内定义了变量 . 例如,如果您在内部定义了循环和变量 x ,然后想在循环外使用它:
for (int i = 0; i < 10; i++) {
.....
int x = 6;
.....
}
int y = x; // compilation error
...你真的想在循环之前定义这个变量:
int x = 0;
for (int i = 0; i < 10; i++) {
.....
x = 6;
.....
}
int y = x; // not variable is available here