Algorithms 练习1.1.11

来源:互联网 发布:童年时光 知乎 编辑:程序博客网 时间:2024/06/05 08:03

题目为编写一段代码,打印一个二维布尔数组,*表示真, 空格表示假。含有行号和列号。

我写的代码如下,采用了3个函数,可以实现选择打出与逻辑和或逻辑。主要的问题每次输入,需要使用回车键确定输入,但是回车确定后,程序会读入\r\n字符。造成多次空循环。目前还未找到解决方法。如果有人愿意不吝赐教,不胜感激。

import edu.princeton.cs.algs4.StdIn;import edu.princeton.cs.algs4.StdOut;public class Test {    public static void booleanfunction(boolean[][] matrix, char which){        for(int i = 2; i < 4; i++){            for(int j = 2; j < 4; j++){                if(which == '&')                    matrix[i][j] = matrix[1][j] && matrix[i][1];                if(which == '|')                    matrix[i][j] = matrix[1][j] && matrix[i][1];            }        }    }    public static void function(char which){        boolean[][] matrix = new boolean[4][4];        matrix[1][2] = true;        matrix[1][3] = false;        matrix[2][1] = true;        matrix[3][1] = false;        for(int i = 0; i < 4; i++)            StdOut.print(i);        StdOut.println();        if((which == '&') || (which == '|')){            booleanfunction(matrix, which);            for(int i = 1; i < 4; i++){                for(int j = 0; j < 4; j++){                    if(j == 0)                        StdOut.print(i);                    else                        StdOut.print(matrix[i][j]?'*':' ');                }                StdOut.println();            }        }        else StdOut.println("Please input \'&\' or \'|\'!");    }    public static void main(String[] args) {        char which;        do{        StdOut.println("which boolean table?");        which = StdIn.readChar();        function(which);        } while((which != '&') || (which != '|'));    }}

运行后结果如下图:
输入&后的结果

原创粉丝点击