java非法的表达式_非法启动表达式字符串

本文解答了一位Java新手在尝试编写文件反转程序时遇到的问题。主要问题包括非法使用public修饰符、变量作用域不当及未正确初始化变量等。文中提供了修正后的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

非法启动表达式字符串

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

e15298c6a3b4591803e154ab0c3b3e2e.png

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 .

e15298c6a3b4591803e154ab0c3b3e2e.png

2 years ago

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

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

e15298c6a3b4591803e154ab0c3b3e2e.png

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值