繁体   English   中英

从其他类调用静态方法时,如何更改对象的值?

[英]How would I change an object's value when calling a static method from a different class?

在此实践问题中,实例化了填充有0和1的方阵。 您可以翻转任意大小的矩形中的值(例如0变为1,1变为0),只要该矩形的最高角在矩阵中为[0,0]。 最终目标是确定必须翻转多少次才能使矩阵的所有值均为0。

如果您需要更长的解释,请访问http://usaco.org/index.php?page=viewproblem2&cpid=689 ,但这是基本概述。

这是我的代码:

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;
        }

    }

}

这是输入文件(名为cowtip.in):

3
001
111
111

我已经排除了当前的调试代码,但是问题是我的check()方法中的rowcol值是正确的值,但是每当我在main调用check()方法时,这些值都会恢复为默认值并没有给我正确答案,这反过来使循环无限。

有想法该怎么解决这个吗?

编辑:我想通了,但谢谢大家! 实际上,这非常简单( c = c.ckeck()而不是c.check() ),老实说,考虑到我花了大约两个小时来调试它,我感到非常沮丧。

c.check()替换为c = c.check();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM