1
import java.io.*;
import java.util.*;

class Read
{
    public static void main(String args[])
    {
        try {
        Scanner scan = new Scanner(new java.io.File("textfile.txt"));
        } catch (FileNotFoundException e){
        }        
        while(scan.hasNext()){
        String line = scan.nextLine();
        String[] elements = line.split(",");
        }
    }
}

为什么我会得到

error: cannot find symbol
        while(scan.hasNext()){
              ^
  symbol:   variable scan

?

4

5 回答 5

4

问题在于范围。您可以在块之外声明对象,并在其中实例化它。Scannertry...catch

当然,您也可能希望将所有依赖于Scanner实例化的 I/O 操作放入其中try...catch,否则您以后会遇到问题。

例子:

public static void main(String[] args) {
    Scanner scan = null;
    try {
        scan = new Scanner(new File("textfile.txt"));
        // other I/O operations here including anything that uses scan
    } catch (FileNotFoundException e) {
        System.out.println("helpful error message", e);
    }
 }
于 2012-12-03T03:50:59.373 回答
0

scan应该在try-catch块外声明,或者你可以把while循环放在try-catch块中

于 2012-12-03T03:52:06.147 回答
0

更改了 where 循环的位置。

import java.io.*;
import java.util.*;

class Read
{
    public static void main(String args[])
    {
        try {
        Scanner scan = new Scanner(new java.io.File("textfile.txt"));
         while(scan.hasNext()){
          String line = scan.nextLine();
          String[] elements = line.split(",");
         }
        } catch (FileNotFoundException e){
           e.printStackTrace();
        }        
    }
}
于 2012-12-03T03:54:34.590 回答
-1

试试这个代码

import java.io.*;
import java.util.*;

class Read
{
public static void main(String args[])
{
    Scanner scan=null;
    try 
    {
       scan = new Scanner(new java.io.File("textfile.txt"));
       while(scan!=null)
       {
        String line = scan.nextLine();
        String[] elements = line.split(",");
       }
    } catch (FileNotFoundException e){ }        
}
}
于 2012-12-03T03:53:30.520 回答
-1
class Read
{
    private static final String TEXT_FILE = "textfile.txt";

    public static void main(String args[])
    {
        // BAD
        try {
          Scanner scan = new Scanner(new java.io.File("textfile.txt"));
        } 
        catch (FileNotFoundException e) {
          ; // Eating exceptions - a bad habit :(
        }        
        while(scan.hasNext()){
          String line = scan.nextLine();
          String[] elements = line.split(",");
        }
    }
}

相比之下 ...

class Read
{
    public static void main(String args[])
    {
        // Good
        try {
          Scanner scan = new Scanner(new java.io.File(TEXT_FILE));
          while(scan.hasNext()){
            String line = scan.nextLine();
            String[] elements = line.split(",");
          }
        } 
          catch (FileNotFoundException e){
            System.out.println ("Error parsing " + TEXT_FILE + ": " + e.getMessage());
        }        
    }
}
于 2012-12-03T03:54:58.263 回答