Java eclipse在令牌上给出错误
我正在写一个关于2d数组的基本程序,只是定义和初始化Java eclipse在令牌上给出错误,java,arrays,eclipse,Java,Arrays,Eclipse,我正在写一个关于2d数组的基本程序,只是定义和初始化 1 package testing; 2 3 public class Array2 { 4 int [][] twoDim = new int[4][]; 5 twoDim[0] = new int[]{1,2,3}; 6 System.out.println(twoDim[0][1]) ; 7 } 但是我在第3行的分号处得到错误,它说: Syntax error on token ";", { ex
1 package testing;
2
3 public class Array2 {
4 int [][] twoDim = new int[4][];
5 twoDim[0] = new int[]{1,2,3};
6 System.out.println(twoDim[0][1]) ;
7 }
但是我在第3行的分号处得到错误,它说:
Syntax error on token ";", { expected after this token
出什么问题了?您需要将代码放在可以执行的地方
System.out.println
是一条执行语句。您可能希望使用main方法
public class Array2 {
public static void main(String[] args){
int [][] twoDim = new int[4][];
twoDim[0] = new int[]{1,2,3};
System.out.println(twoDim[0][1]) ;
}
}
注意:您可以使用方法、构造函数、静态初始值设定项、类声明等的组合来使其正确执行。主要方法似乎最适合您正在尝试的操作
回答您在“如何使数组成为类变量”评论中的问题 您可以将
twoDim
设置为类变量。我将使用构造函数来设置数组中的值。在main方法中,必须创建类的实例,以便访问其成员。还要注意,在创建类的实例时会调用构造函数。例如:
public class Array2 {
public int [][] twoDim = new int[4][];
public Array2(){ // Constructor for Array2 class
twoDim[0] = new int[]{1,2,3}; // Set the values
}
public static void main(String[] args){
Array2 array2Instance = new Array2(); // Create an instance, calls constructor
System.out.println(array2Instance.twoDim[0][1]); // Access the instance's array
}
}
请注意,您必须将twoDim
变量设置为public
,以便在类之外访问它—例如在main方法中。您不能写入
public class Array2 {
public static void main(String[] args){
int [][] twoDim = new int[4][];
twoDim[0] = new int[]{1,2,3};
System.out.println(twoDim[0][1]) ;
}
}
System.out.println(twoDim[0][1]);
在java中的方法或块之外
这或许应该能起到作用
public static void main(String arr[])
{
int [][] twoDim = new int[4][];
twoDim[0] = new int[]{1,2,3};
System.out.println(twoDim[0][1]) ;
}
或者类似的事情
int [][] twoDim = new int[4][];
public void display()
{
twoDim[0] = new int[]{1,2,3};
System.out.println(twoDim[0][1]) ;
}
public static void main(String arr[])
{
new Array2().display();
}
可以在方法或代码块内初始化数组
System.out.println(twoDim[0][1]) ;
此语句应该位于某个块或方法中。你不能让它像那样躺在课堂上。把它放在某个块或方法中
如果我不写System.out.println(..),错误仍然存在
以这种方式定义数组后,不能初始化数组的元素。你需要把声明
twoDim[0] = new int[]{1,2,3};
内部块/方法/构造函数
任何数组都是如此
乙二醇
您是对的,但这是否意味着数组不能像定义int变量那样在本地定义。@Trinity数组是在main方法内部本地定义的。你是在问它是否可以是一个类变量吗?是的,我是在问它是否可以是一个类变量吗?只是一个提示-以后尽量不要在旁边包含数字。使人们在帮助您时更难将代码复制并粘贴到IDE中。