最终变量可能已经分配

And*_*ndy 1 java eclipse

我正在编写一个程序,它有两个我希望使用的最终变量,我需要在实际运行类时设置它们,因为它们可能在每个实例中都不同.

我的初始化与我希望使用的任何其他类变量相同,我初始化名称和类型但不是值.

   public final String filename, filepath;
Run Code Online (Sandbox Code Playgroud)

在构造函数中,我将值设置如下

 public myClass(String value) {
     this.filename = value;
     this.filepath = anotherPartOfValue;
  }
Run Code Online (Sandbox Code Playgroud)

当我这样做时,我收到一条警告"最终字段[x]可能已被分配"

有没有办法避免这个警告,仍然保持最终状态并在构造函数中设置值?

我正在使用eclipse btw.


编辑:

这是给我错误的确切代码

import java.io.*;

public class Dirt {

private String[] tables;
private int numTables;
private final String filename, filepath;

public Dirt(String file) {
    this.tables = new String[0];
    this.numTables = 0;

    for (int i = file.length(); i < 0; i--) {
        if (file.charAt(i) == '/') {
            this.filename = file.substring(i);
            this.filepath = file.substring(1, i-1);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

}

Ted*_*opp 7

问题是您要在循环中分配最终变量.没有什么可以阻止循环多次循环并且if条件不止一次满足.(如果有两个'/'字符file会怎么样?或者没有?)

解决此问题的方法是在构造函数中使用临时字符串变量,然后将其分配给filenamefilepath结尾:

public Dirt(String file) {
    this.tables = new String[0];
    this.numTables = 0;
    String name = null;
    String path = null;

    for (int i = file.length(); i < 0; i--) {
        if (file.charAt(i) == '/') {
            name = file.substring(i);
            path = file.substring(1, i-1);
            // need a break here?
        }
    }
    this.filename = name;
    this.filepath = path;
}
Run Code Online (Sandbox Code Playgroud)

这很丑陋,但这是一种直截了当的方式,可以确定filename并且filepath肯定会被分配,并且肯定只被分配一次.