首页 文章

非法启动表达式字符串

提问于
浏览
1

我正在尝试制作一个程序来反转文件中的文本行 . 我还在学习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 回答

  • 0

    问题:

    • 您使用 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<String>

    List<String> lines = new ArrayList<String>();
    while (in.hasNextLine()) {
        lines.add(in.nextLine());
    }
    

    然后你需要使用 size() 而不是 length ,并使用 get 而不是数组索引器来访问值 - 但它将是更清晰的代码IMO .

  • 3

    这是一个范围问题 . lines 应该在while循环之外声明 . 通过将 lines 放在while循环中,它仅在该循环内可用 . 如果将其移到外面, lines 的范围将在main方法中 .

    变量的范围是可以访问变量的程序部分 .

    以下是伯克利课程中关于变量和范围的讲义 . 如果你有时间,请给它一个阅读 . http://www.cs.berkeley.edu/~jrs/4/lec/08

  • 0

    访问修饰符( publicprivateprotected )仅适用于类成员(方法或字段) .

    如果要访问受 {} 限制的范围之外的变量,则表示您在错误的范围内定义了变量 . 例如,如果您在内部定义了循环和变量 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
    

相关问题