我尝试在 try-catch block 之后声明 s.next()
但它不起作用!仅当 s
位于 try block 内时,才会有下拉菜单。
我不想将解析输入、采取适当的操作全部放入 try block 中,因为它们不会抛出 FNFE 和 IOE。我在这里能做什么?
public static void main(String[] args)
{
// TODO Auto-generated method stub
//Open file; file name specified in args (command line)
try{
FileReader freader = new FileReader(args[0]);
Scanner s = new Scanner(freader);
}catch(FileNotFoundException e){
System.err.println("Error: File not found. Exiting program...");
e.printStackTrace();
System.exit(-1);
}catch(IOException e){
System.err.println ("Error: IO exception. Exiting...");
e.printStackTrace();
System.exit(-1);
}
// if i try to declare s.next() here it would not work
最佳答案
我认为你的意思是你想使用 s.next() 但它不起作用。
为此,请将 s 声明为 try/catch block 外部的变量,并在那里将其设置为 null。然后将其分配到您现在分配的位置,但不带声明。如果我的假设是正确的,那么您的问题是 s 不再是 try/catch 之外的 Activity 变量,因为它是在该 block 内声明的。
FileReader freader = null;
Scanner s = null;
try { freader = new FileReader(args[0]); // risk null pointer exception here
s = new Scanner(freader);
}
catch { // etc.
关于java - 扫描仪变量在 try-catch block 之外不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13505091/