问题描述
我想创建一个项目列表,不同势每个i和j变量。我的code是:
I am trying to create an item list, diffrent for each i and j variable. My code is:
if (i == 0) {
if (j == 0) {
final CharSequence[] items = {"4:45", "5:00"}
} else if (j == 1) {
final CharSequence[] items = {"4:43", "4:58"}
} else if (j == 2) {
final CharSequence[] items = {"4:41", "4:56"}
} else {
final CharSequence[] items = {"4:38", "4:53"}
}
...
new AlertDialog.Builder(this)
.setTitle("Hours")
.setItems(items,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i) {
// getStation(i);
}
})
.show();
}
我在该行得到一个错误 .setItems(项目,
:
items cannot be resolved
我觉得编译器认为,的CharSequence []项目
可能不被初始化或东西...我怎样才能让这个程序运行?
I think that the compiler thinks that the CharSequence[] items
may not be initialised or something...How can I make this programme run?
推荐答案
现在的问题是变量范围。
The problem is variable scoping.
if (someCondition) {
final int i = 666;
} else {
final int i = 42;
}
int j = i + 1; // compile-time error
在这里,我们有两个局部变量我
谁超出范围,他们正在申报和初始化之后。如果Ĵ
需要的值我
,然后我
会必须在一个更大的范围内声明。
Here we have two local variables i
who goes out of scope immediately after they're declared and initialized. If j
needs the value of i
, then i
would have to be declared in a larger scope.
final int i;
if (someCondition) {
i = 666;
} else {
i = 42;
}
int j = i + 1; // compiles fine!
(应当指出,这正是那种场景下三元运算优异,即)
(It should be mentioned that this is exactly the kind of scenarios where the ternary operator excels, i.e.)
final int i = (someCondition) ? 666 : 42;
在您的具体情况,不幸的是,数组初始化的速记只能在声明初始化。那就是:
In your specific case, unfortunately the array initializer shorthand can only be used to initialize upon declaration. That is:
int[] arr1 = { 1, 2, 3 }; // compiles fine!
int[] arr2;
arr2 = { 4, 5, 6 }; // doesn't compile!
您可以拉出的项目申报
之外如果
并写出详细的code为每案例(见约阿希姆·绍尔的答案),但更简洁code是使用数组的数组,而不是。
You can pull out the declaration of items
outside the if
and write the verbose code for each case (see Joachim Sauer's answer), but a more concise code is to use array-of-arrays instead.
final CharSequence[][] allItems = {
{ "4:45", "5:00" },
{ "4:43", "4:58" },
{ "4:41", "4:56" },
{ "4:38", "4:53" }
};
final CharSequence[] items = allItems[j];
此方法效果很好在这种情况下,但在更一般的情况下,你需要使用地图
或类似的东西。
This technique works well in this case, but in the more general case you want to use a Map
or something similar.
请注意:这不是明确的在原来的code,但这个工作如果Ĵ
可以是 0
, 1
, 2
或 3
。如果你想在最后的选项将在Ĵ
比其他任何值 0
, 1
, 2
,那么你必须检查是否存在并将其设置为 3
在此之前code。
Note: It's not explicit in the original code, but this works if j
can either be 0
, 1
, 2
, or 3
. If you want the last option to apply when j
is any value other than 0
, 1
, 2
, then you have to check for that and set it to 3
before this code.
这篇关于变量不能得到解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!