使用嵌套循环和JOptionPane创建一个框

时间:2016-02-09 13:56:14

标签: java loops nested joptionpane

我需要打印一个在第一个数字和第二个数字示例中相同的方框:第一个数字= 3秒数字= 3并且它看起来像这样

    ***
    ***
    ***

这是我的代码

import javax.swing.JOptionPane;

public class box{

    public static void main(String[]args){
        int a,b;
        a=Integer.parseInt(JOptionPane.showInputDialog(null, "Enter first number"));
        b=Integer.parseInt(JOptionPane.showInputDialog(null, "Enter second number"));

        if(a==b){
            for(int x=a; x<=b; x++){
                a++;
                for(int y=0; y<=x; y++){
                    System.out.print("*");
                }
                System.out.println();
            }
        }
        else if(a==b){


        }
        else{
            System.exit(0);
        }

    }

}

但我一直只得到这个

****

1 个答案:

答案 0 :(得分:0)

 for(int x=a; x<=b; x++){ ... }

由于此时ab相等,因此您只运行此循环一次。您必须正确使用这两个循环:

for (int i = 0; i < a; i++) { // you start with zero and as many rows as entered
    for (int j = 0; j < b; j++) { // same for columns
         System.out.print("*");
    }
    System.out.println(); // start a new line
}

如果行数和列数不相同,此循环也将起作用。所以你不必使用任何支票。

相关问题