[英]How can I initialize final static variable in a static class?
So I'm using Processing to draw a map from a data file. 所以我正在使用Processing从数据文件中绘制地图。 I want to stock some information of the first line inside a class.
我想在课程中存储第一行的一些信息。 In processing this class is an inner class of PApplet, so it has to be a static class (Otherwise i get an error: static fieldscan only be declared in static or top level type).
在处理此类时,它是PApplet的内部类,因此它必须是静态类(否则,我会得到一个错误:只能以静态或顶级类型声明静态字段)。
public static class PlacesInfo{
static final int totalCount;
static final float xMin;
static final float yMin;
static final float xMax;
static final float yMax;
static final int populationMax;
static final int densityMax;
//Set all static variables once
static{
String[] lines = loadStrings("population.tsv");
String info = lines[0].substring(2); //to delete some useless char
String[] infoInit = split(info, ','); //to parse the data of the first line
totalCount = int(infoInit[0]);
xMin = float(infoInit[1]);
xMax = float(infoInit[2]);
yMin = float(infoInit[3]);
yMax = float(infoInit[4]);
populationMax = int(infoInit[6]);
densityMax = int(infoInit[8]);
}
}
When I run this code, I get an error, because I can't use the loadStrings() function (which is non-static). 运行此代码时,出现错误,因为我无法使用loadStrings()函数(这是非静态的)。
So what I want is to have static final variables that I can initialize from the "population.tsv" file. 因此,我要拥有的静态最终变量可以从“ population.tsv”文件中初始化。 What are your ideas/advices?
您有什么想法/建议?
1) Make the method static, and you will be fine -- static code must be in order must be compiled in order. 1)将方法设为静态,这样就可以了-静态代码必须按顺序排列,必须按顺序进行编译。 Put the loadStrings function before the static code block.
将loadStrings函数放在静态代码块之前。
Please note : However - you might be better off simply creating a single, static , "init" method, which is called in your static code block . 请注意:但是-您最好只创建一个静态的“ init”方法,该方法在您的静态代码块中调用。 This will be nameable and unit-testable, unlike your current implementation.
与您当前的实现不同,这将是可命名和可单元测试的。
2) By the way : your float syntax is off, and must to be casted properly. 2)顺便说一句:您的float语法已关闭,必须正确转换。
int i = (int) 1.4f;
3) To initialize the static variables you can do the following : 3)要初始化静态变量,您可以执行以下操作:
You cannot run class method loadString
inside static context. 您不能在静态上下文中运行类方法
loadString
。 In order to run it from this context, you need to make your loadString
method static as well (or alternatively move it outside static context). 为了从此上下文中运行它,您还需要使
loadString
方法也成为静态方法(或将其移到静态上下文之外)。
I am speculating: 我在推测:
String[] lines = ( new PApplet() ) . String [] lines =(new PApplet())。 loadStrings("population.tsv");
loadStrings( “population.tsv”);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.