[英]Using ArrayList to fill TextView
这里似乎提出了许多类似的问题,但它们似乎没有回答或解决我的问题。
我创建了一个 ArrayList 并填充了随机数,这些随机数需要在 LinearLayout 的 Textviews 中显示。
Random rand = new Random();
List<Integer> list1 = new ArrayList<Integer>();
List<Integer> list2 = new ArrayList<Integer>();
for (int i=1; i<2; i++) {
for (int mbs=1; mbs <= 4; mbs++) {
int randNum1 = rand.nextInt(37 - 1) + 1;
list1.add(randNum1);
Collections.shuffle(list1);
for (int j = 1; j<=2; j++){
int randNum2 = rand.nextInt(16 - 1)+1;
list2.add(randNum2);
Collections.shuffle(list2);
}
}
}
}
我用过(这只是 TextViews 之一)
TextView tv1l1 = findViewById(R.id.tv1l1);
然后想将 list1 或 list2 中的随机数放入其中
tv1l1.setText(list1(0));
我收到错误消息说无法解析 list1。
我原以为我想做的事情很容易,但由于某种原因我无法得到它,有什么帮助吗?
tv1l1.setText(list1(0));
需要在定义List<Integer> list1 = new ArrayList<Integer>();
的相同方法中调用 . 否则,您需要将list1
定义为 class 级别变量。
里面的语句list1(0)
tv1l1.setText(list1(0));
被视为 function 调用,其中 function 名称 list1 传递“0”作为参数。 由于不存在名为list1(int)的function,所以错误是正确的。
你应该使用的是tv1l1.setText(list1.get(0));
也就是说,从 list1 变量中获取第一个元素(索引 = 0),上面声明为List<Integer> list1
检查变量范围的定义,
成员变量(类级别范围)
这些变量必须在 class 内(任何函数外)声明。 它们可以在 class 的任何地方直接访问。
public class Test
{
// All variables defined directly inside a class
// are member variables
int a;
private String b
void method1() {....}
int method2() {....}
char c;
}
局部变量(方法级别范围)
在方法内声明的变量具有方法级别 scope,不能在方法外访问。 注意:方法执行结束后局部变量不存在。
public class Test
{
void method1()
{
// Local variable (Method level scope)
int x;
}
}
循环变量(块作用域)在方法中的一对括号“{”和“}”内声明的变量只有带括号的 scope。
public class Test
{
public static void main(String args[])
{
{
// The variable x has scope within
// brackets
int x = 10;
System.out.println(x);
}
// Uncommenting below line would produce
// error since variable x is out of scope.
// System.out.println(x);
}
}
Java中关于变量scope的一些要点:
通常,一组大括号 { } 定义了一个 scope。
在 Java 中,我们通常可以访问一个变量,只要它与我们正在编写的代码在同一组括号内或在定义变量的大括号内的任何大括号内定义。
所有成员方法都可以使用在任何方法之外的 class 中定义的任何变量。
当方法与成员具有相同的局部变量时,该关键字可用于引用当前 class 变量。
对于循环终止后要读取的变量,它必须在循环体之前声明。
更多了解 go 通过链接https://www.geeksforgeeks.org/variable-scope-in-java/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.