Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 阿达玛模式问题_Java_Recursion - Fatal编程技术网

Java 阿达玛模式问题

Java 阿达玛模式问题,java,recursion,Java,Recursion,我正在编写一个使用递归显示哈达玛模式的程序 一个1乘1的阿达玛图案是一个单一的黑色正方形。通常,通过以2×2网格的形式对齐N×N图案的4个副本,然后反转右下N×N副本中所有正方形的颜色,可以获得2N×2N阿达玛图案 我想拍一张和你一样的照片 我的代码是: import java.awt.*; import javax.swing.*; @SuppressWarnings("serial") public class Hadamard extends JPanel{ @SuppressWa

我正在编写一个使用递归显示哈达玛模式的程序

一个1乘1的阿达玛图案是一个单一的黑色正方形。通常,通过以2×2网格的形式对齐N×N图案的4个副本,然后反转右下N×N副本中所有正方形的颜色,可以获得2N×2N阿达玛图案

我想拍一张和你一样的照片

我的代码是:

import java.awt.*;

import javax.swing.*;

@SuppressWarnings("serial")
public class Hadamard extends JPanel{


@SuppressWarnings("unused")
private void hadamard(Graphics g, int n, int x, int y, int width, int height){

    if(n == 0){

        g.fillRect(x/2, y/2, width, height);
        return;
    }
    else{

        hadamard(g, n-1, x, y, width/2, height/2);

        hadamard(g, n-1, x + width, y,  width/2, height/2);

        hadamard(g, n-1, x, y + height, width/2, height/2);

        g.setColor(Color.WHITE);
        hadamard(g, n-1, x + width, y + height, width/2, height/2);
        g.setColor(Color.BLACK);


    }
}

protected void paintComponent(Graphics g){
    super.paintComponent(g);

    hadamard(g, 2, getWidth() / 2, getHeight() / 2, getWidth() / 2, getHeight() / 2);

}

public static void main(String[] args) {

    Hadamard panel = new Hadamard();
    JFrame app = new JFrame();

    app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    app.add(panel);
    app.setSize(516, 538);
    app.setVisible(true);

}
}

我没有正确地改变右下角正方形的颜色。在过去的几个小时里,我一直在做这一步,我希望有人能给我一个正确的方法,因为我不知道

先谢谢你。 Nath

您的代码并没有反转右下象限,它只是将其强制为白色

我想说的是,最好的解决方案是在递归方法中添加一个额外的参数(我们称之为
b
),其值可以是
true
false
。然后可以递归为:

    hadamard(g, n-1, x, y, width/2, height/2, b);
    hadamard(g, n-1, x + width, y,  width/2, height/2, b);
    hadamard(g, n-1, x, y + height, width/2, height/2, b);
    hadamard(g, n-1, x + width, y + height, width/2, height/2, !b);

然后,当您进入
fillRect
调用时,根据
b

的值选择白色或黑色,谢谢您的回复,奥利。@Oli按照您的建议,我更改了代码:`private void hadamard(图形g,int n,int x,int y,int width,int height,boolean b){if(n==0){if(b==true)g.setColor(Color.BLACK);else g.setColor(Color.WHITE);g.fillRect(x/2,y/2,宽度,高度);return;}else{hadamard(g,n-1,x,y,width/2,height/2,true);hadamard(g,n-1,x,y,width/2,height/2,true);hadamard(g,n-1,x,y+height/2,true)(g,n-1,x+宽度,y+高度,宽度/2,高度/2,假);}`@纳特:那还是不行。你在对递归调用的
b
值进行硬编码!@Oli我怎样才能将我的代码格式化为可读格式?我用过
code
,但代码不像块类型。@纳特:如果你在写注释,你可以将代码放在反勾之间。但我建议你编辑你的问题,以包含你的内容你的新代码。