[英]How do I avoid making methods and variables static in this code?
我正在为我的 java class 解决过去的考试,我正在努力解决其中一个问题。 我一直得到错误的结果,我认为这是因为所有类和实例变量都是 static。如何避免使它们成为 static? 此外,这个问题基本上希望您找到 args[1] 中给定位置的相同字母,如果它们靠近给定位置,则将它们转换为“S”(Args 是“K,K,K,YK,Y,M ,MK,Y,Y,Y 2,1 S" 如果你需要)
public class MatrixRefill {
public static String[][] matrix;
public static int rows;
public static int cols;
public static String enemy;
public static String target;
public static void main(String[] args) {
target = args[2];
rows = Integer.parseInt(args[1].substring(0,1));
cols = Integer.parseInt(args[1].substring(2));
matrix = matrixCreator(args[0]);
enemy = matrix[rows][cols];
recursive(rows, cols, target);
printer(matrix);
}
public static String[][] matrixCreator(String mx) {
int ro = 0;
int co = 0;
for (int i = 0; i < mx.length(); i++) {
if (mx.substring(i,i+1).equals(","))
co++;
if (mx.substring(i,i+1).equals("-"))
ro++;
}
String[][] matriks = new String[ro+1][co/3+1];
ro = 0;
co = 0;
for (int j = 0; j < mx.length(); j++) {
if (mx.substring(j,j+1).equals(","))
co++;
else if (mx.substring(j,j+1).equals("-")) {
ro++;
co = 0;
}
else
matriks[ro][co] = mx.substring(j,j+1);
}
return matriks;
}
public static void recursive(int row, int col, String target) {
if (valid(row,col)) {
recursive(row+1,col, target);
recursive(row,col+1, target);
recursive(row,col-1, target);
recursive(row-1,col, target);
matrix[row][col] = target;
}
}
public static boolean valid(int row, int col) {
boolean result = false;
if (row >= 0 && row < matrix.length && col >= 0 && col < matrix[row].length)
if (matrix[row][col] == enemy)
result = true;
return result;
}
public static void printer(String[][] owo) {
for(int i = 0; i < owo.length; i++) {
for(int j = 0; j < owo[i].length; j++) {
System.out.print(owo[i][j]);
if(j < owo[i].length - 1)
System.out.print(" ");
}
System.out.println();
}
}
}
从您的方法和实例字段中删除 static 关键字。 但是要从main
中调用它们,您需要创建一个包含 class 的instance
(在本例中是包含main
方法的实例)并使用它来调用其他方法。 我有时做的是创建一个实例方法(即非静态的)并调用它来启动进程。 然后我会把主要的所有东西都放在那个方法里。 这是一个例子。
public static void main(String[] args) {
MatrixRefill mr = new MatrixRefill();
mr.start();
}
public void start() {
target = args[2];
rows = Integer.parseInt(args[1].substring(0,1));
cols = Integer.parseInt(args[1].substring(2));
matrix = matrixCreator(args[0]);
enemy = matrix[rows][cols];
recursive(rows, cols, target);
printer(matrix);
}
// rest of code here
}
通过将main
中的内容放在start
方法中,您可以调用其他实例方法并访问实例字段,而无需使用对 class 的引用来限定它们(即在本例中以mr.
为前缀)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.