[英]How would I change an object's value when calling a static method from a different class?
In this practice problem, a square matrix filled with 0s and 1s is instantiated. 在此实践问题中,实例化了填充有0和1的方阵。 You can flip over values (ex: 0 becomes 1 and 1 becomes 0) in a rectangle of any size, as long as the topmost corner of the rectangle is [0, 0] in the matrix.
您可以翻转任意大小的矩形中的值(例如0变为1,1变为0),只要该矩形的最高角在矩阵中为[0,0]。 The end goal is to find how many times you must flip values over to get all the values of the matrix as 0.
最终目标是确定必须翻转多少次才能使矩阵的所有值均为0。
If you want a longer explanation, go to http://usaco.org/index.php?page=viewproblem2&cpid=689 , but that's the basic outline. 如果您需要更长的解释,请访问http://usaco.org/index.php?page=viewproblem2&cpid=689 ,但这是基本概述。
This is my code: 这是我的代码:
import java.io.*;
import java.util.*;
public class CowTip {
static int[][] mat;
public static void main( String[] args) throws IOException, InterruptedException{
Scanner scan = new Scanner(new File("cowtip.in"));
int n = scan.nextInt();
scan.nextLine();
mat = new int[n][n];
for (int x = 0; x < n; x++) {
String str = scan.nextLine();
for (int y = 0; y < n; y++) {
mat[x][y] = Integer.parseInt(str.substring(y,y+1));
}
}
Checker c = new Checker(n-1, n-1);
int count = 0;
while (true) {
c.check();
for (int x = 0; x <= c.row; x++) {
for (int y = 0; y <= c.col; y++) {
if (mat[x][y] == 0) {
mat[x][y] = 1;
}
else if (mat[x][y] == 1) {
mat[x][y] = 0;
}
}
}
count++;
c.check();
if (c.row == -1 && c.col == -1) {
break;
}
}
System.out.println(count);
}
static class Checker {
int row;
int col;
public Checker(int r, int c) {
row = r;
col = c;
}
public Checker check() {
Checker check = new Checker(-1, -1);
for (int x = mat.length-1; x >= 0; x--) {
for (int y = mat[x].length-1; y >= 0; y--) {
if (mat[x][y] == 1) {
check = new Checker(x, y);
break;
}
}
if (check.row != -1 && check.col != -1) {
break;
}
}
return check;
}
}
}
and this is the input file (named cowtip.in) : 这是输入文件(名为cowtip.in):
3
001
111
111
I've excluded my current debugging code, but the problem is that the row
and col
values inside my check()
method are the correct values, but whenever I call the check()
method in my main
, the values reverts back to the default and doesn't give me the correct answer, which in turn makes the loop infinite. 我已经排除了当前的调试代码,但是问题是我的
check()
方法中的row
和col
值是正确的值,但是每当我在main
调用check()
方法时,这些值都会恢复为默认值并没有给我正确答案,这反过来使循环无限。
Any ideas on how to fix this? 有想法该怎么解决这个吗?
EDIT: I've figured it out, but thanks guys! 编辑:我想通了,但谢谢大家! It was actually extremely simple (
c = c.ckeck()
instead of c.check()
) and honestly, I was pretty frustrated considering I spent around two hours trying to debug this... 实际上,这非常简单(
c = c.ckeck()
而不是c.check()
),老实说,考虑到我花了大约两个小时来调试它,我感到非常沮丧。
将c.check()
替换为c = c.check();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.