【问题标题】:Compilation error: variable might not have been initialized [duplicate]编译错误:变量可能尚未初始化 [重复]
【发布时间】:2015-02-01 01:14:36
【问题描述】:

我正在尝试创建一个方法,为文件中的每个字符添加一个变量。如果文件是:

abcd
abc
ab

那么在函数运行后,它返回的变量将等于 9。

这是我目前的代码:

public static double getRow(String filename) {
   double size = 0;
   File f;
   Scanner infile;
   try{
      f = new File(filename);
      infile = new Scanner(f);
   }
   catch (IOException e){
       System.out.println("Error opening the file");
       //System.exit(0); not good
   }
   while(infile.hasNext()) {
       size++;
   }
   infile.close();
   return size;

}

但我不断收到infile 尚未初始化。我不确定如何获得我想要的解决方案。

【问题讨论】:

  • catch 块之后到 close(包括)的所有代码都应该在 try 块内。不要写这样的代码。
  • NB 扫描仪可能不会做你想做的事。只需读取带有BufferedReader 的行,然后将它们的长度相加。
  • 与我现在拥有的相比,我应该如何使用它?
  • 呃,我刚才说的方式?

标签: java compiler-errors


【解决方案1】:

因为您是在try 块中初始化infile,所以如果try 中出现任何问题,当您在catch 块之后尝试使用它时,infile 将永远不会被初始化。

您想要做的是让您在try 块中处理所有内容,包括循环和关闭infile

public static double getRow(String filename) {
    double size = 0;
    File f;
    Scanner infile;
    try {
        f = new File(filename);
        infile = new Scanner(f);
        while(infile.hasNext()) {
            size++;
        }
        infile.close();
    }
    catch (IOException e) {
        System.out.println("Error opening the file");
        //System.exit(0); not good
    }
    return size;
}

【讨论】:

  • 您知道将文件中所有字符相加的方法吗?
  • 如EJP所说,看看BufferedBeader,或者直接搜索java read file character by character,你会发现很多例子。喜欢这个:stackoverflow.com/questions/811851/…,但还有很多其他的。
  • 逐个字符读取是行不通的。它将计算行终止符,无论它们是什么。
【解决方案2】:

我刚试过这个;错误是“变量 infile 可能尚未初始化”,这是因为如果 new File 行中有异常,则不会。

有几种解决方案,但最好的办法是确保您不要尝试使用 infile,如果您不能保证它已被初始化,例如将代码放在上面的 try 块中.

这是我的版本:

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

class Foo {
    public static double getRow(String filename) {
        double size = 0;
        File f;
        Scanner infile ;
        try{
            f = new File(filename);
            infile = new Scanner(f);
            while(infile.hasNext()) {
                size++;
            }
            infile.close();
            return size;

        }
        catch (IOException e){
            System.out.println("Error opening the file");
            //System.exit(0); not good
        }
        return -1;
    }               

    public static void main(String[] argv){
        System.out.printf("ResultsL %d\n",
                          getRow("foo.txt"));

        return ;
    }
}

理想情况下,您还可以将 public static intint size=0; 一起设为 int size=0;,因为您正在计算一些东西,这是一个离散值,而不是真实值。

【讨论】:

  • VG 但为什么要公开?和静态的?为什么是会员?
猜你喜欢
  • 1970-01-01
  • 2013-05-14
  • 1970-01-01
  • 1970-01-01
  • 2016-07-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多