java 编译找不到符号,java中编译错误:找不到符号。

本文档解决了一个关于Java编程的问题,其中涉及在一个类的方法中访问在构造函数中创建的Scanner对象。错误提示表明`input`变量在方法`makeSmallerLists()`中未被找到。解决方案是将Scanner实例声明为类的成员,而不是局部变量,以便在类的整个生命周期内都能访问。通过这样做,可以确保在多个方法中都能使用同一Scanner对象读取文件。
摘要由CSDN通过智能技术生成

I have this code that is taking a text file and turning it into a string and then separating parts of the string into different elements of an arraylist.

import java.util.Scanner;

import java.io.*;

import java.util.ArrayList;

public class Grocery{

public Grocery(){

File inFile = new File ("lists.txt");

Scanner input = new Scanner (inFile);

String grocery;

{

grocery = input.nextLine();

}

}

public void makeSmallerLists(){

String listLine;

String line;

ArrayList smallList = new ArrayList();

while(input.hasNextLine()){

line = input.nextLine;

if(line.equals("")){

smallList.add(listLine);

} else{

listLine = listLine + "\n" + line;

}

}

}

}

However when I try to compile this it gives me two errors:

javac Message.java Message.java:31: cannot find symbol symbol :

variable input location: class Message while(input.hasNextLine()){

^ Message.java:32: cannot find symbol symbol : variable input location: class Message line = input.nextLine;

^

How do I fix this? I really don't know what's wrong.

I fixed that and now my error says

$ javac Message.java

Message.java:34: cannot find symbol

symbol : variable nextLine

location: class java.util.Scanner

line = input.nextLine;

^

^

Now what is wrong?

解决方案

Scanner input = new Scanner (inFile);

input is local to the constructor, you cannot access outside of it, and you are trying to access in makeSmallerLists() method. Make it as a instance member, So that it available through out the class other than static context.

public class Grocery{

Scanner input;

and in constructor

public Grocery(){

File inFile = new File ("lists.txt");

input = new Scanner (inFile);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值