从二维数组中删除一列
问题描述:
我想写一个类,它将从2d数组中删除一列,但我一直遇到我不明白的错误。我想我误解的东西非常基本在这里,任何帮助,将不胜感激从二维数组中删除一列
public class CollumnSwitch
{
int[][] matrix;
int temp;
public static void coldel(int[][] args,int col)
{
for(int i =0;i<args.length;i++)
{
int[][] nargs = new int[args.length][args[i].length-1];
for(int j =0;j<args[i].length;j++)
{
if(j!=col)
{
int temp = args[i][j];
}
nargs[i][j]= temp;
}
}
}
public void printArgs()
{
for(int i =0;i<nargs.length;i++)
{
for(int j =0;j<nargs[i].length;j++)
{
System.out.print(nargs[i][j]);
}
System.out.println();
}
}
}
答
不能从静态上下文访问一个非静态变量,你需要改变int temp;
到static int temp;
或者你可以从你的方法删除static
宣言。
您在coldel
方法中声明了nargs
数组,因此无法从其他方法访问该数组。这意味着这不起作用:
for(int i =0;i<nargs.length;i++) //You try to access nargs which is not possible.
{
for(int j =0;j<nargs[i].length;j++)
...
也许你希望它是matrix
数组你有你的课吗?就像这样:
在coldel
:
matrix= new int[args.length][args[i].length-1];
和printArgs
for(int i =0;i<matrix.length;i++)
{
for(int j =0;j<matrix[i].length;j++)
...
这需要matrix
是静态也(同样,你也可以卸载static
从coldel
)
答
你可以这样试试:
static int[][] nargs;
public static void deleteColumn(int[][] args,int col)
{
if(args != null && args.length > 0 && args[0].length > col)
{
nargs = new int[args.length][args[0].length-1];
for(int i =0;i<args.length;i++)
{
int newColIdx = 0;
for(int j =0;j<args[i].length;j++)
{
if(j!=col)
{
nargs[i][newColIdx] = args[i][j];
newColIdx++;
}
}
}
}
}
public static void printArgs()
{
if(nargs != null)
{
for(int i =0;i<nargs.length;i++)
{
for(int j =0;j<nargs[i].length;j++)
{
System.out.print(nargs[i][j] + " ");
}
System.out.println();
}
}
}
答
由于使用范围之外的变量,您的困难已经出现。在java中,变量基本上只存在于声明它们的最直接的一对括号中。因此,举例来说:
public class Foo {
int classVar; // classVar is visible by all code within this class
public void bar() {
classVar = classVar + 1; // you can read and modify (almost) all variables within your scope
int methodVar = 0; // methodVar is visible to all code within this method
if(methodVar == classVar) {
int ifVar = methodVar * classVar; // ifVar is visible to code within this if statement - but not inside any else or else if blocks
for(int i = 0; i < 100; i++) {
int iterationVar = 0; // iterationVar is created and set to 0 100 times during this loop.
// i is only initialized once, but is not visible outside the for loop
}
// at this point, methodVar and classVar are within scope,
// but ifVar, i, and iterationVar are not
}
public void shoo() {
classVar++; // shoo can see classVar, but no variables that were declared in foo - methodVar, ifVar, iterationVar
}
}
您所遇到的问题是因为你宣布一个新的2-d阵列的for循环的每个迭代,写一列到它,扔那走之前,创建一个新的数组,并重复该过程。
你会得到什么错误? – MAV 2013-04-27 03:47:44
看起来像你有确定范围的问题;使用不存在的变量;并有一个你似乎没有使用的实例变量矩阵。 – Supericy 2013-04-27 03:56:46
主要的两个错误说,它无法找到我的Nargs数组的符号。而非静态变量temp不能从静态上下文中引用。 – 2013-04-27 03:57:42