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
答案 0 :(得分:4)
问题在于范围。您可以在Scanner
块之外声明 try...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);
}
}
答案 1 :(得分:0)
您的scan
应在try-catch
区块之外宣布,或者您可以将while
循环放入try-catch
区块
答案 2 :(得分: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();
}
}
}
答案 3 :(得分:-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){ }
}
}
答案 4 :(得分:-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());
}
}
}