如何在java中用星号制作盒子?嵌套循环?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18750340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 10:44:11  来源:igfitidea点击:

How to make box out of asterisks in java? nested loops?

javaloopsfor-loopif-statementnested-loops

提问by Connie Clark

Hey I really need help with a program for my java programming class. I'll put in the instructions and the code I have thus far. Any help would be appreciated! Thanks in advance!! Instructions: Write a program called Box (Box.java) that will print/displays a hollow box shape using asterisks (*). The program will read in an even number in the range 2 to 24 to specify the number of rows/columns in the box. Display an error and re-prompt for the number if an incorrect value was entered. The program will then display a hollow of the appropriate size. Hint: Use loops within loops. basically it should make a square box, so if you give it the number boxSize = 5 the output is a box with dimensions 5x5. the outline is made of asterisks but the inside is empty

嘿,我真的需要帮助来为我的 Java 编程课编写一个程序。我将输入到目前为止的说明和代码。任何帮助,将不胜感激!提前致谢!!说明: 编写一个名为 Box (Box.java) 的程序,该程序将使用星号 (*) 打印/显示空心盒形状。程序将读取 2 到 24 范围内的偶数以指定框中的行/列数。如果输入的值不正确,则显示错误并重新提示输入数字。然后程序将显示一个适当大小的空心。提示:在循环中使用循环。基本上它应该是一个方形盒子,所以如果你给它数字 boxSize = 5 输出是一个尺寸为 5x5 的盒子。轮廓由星号组成,但内部是空的

heres what I have code wise so far

继承人到目前为止我的代码明智

import java.util.Scanner;

public class Box
{

    public static void main(String[]args)
    {
        //numrows and numcols are equal however the spacing is differnt
        Scanner input = new Scanner(System.in);
        System.out.print("Enter an even number (2-24):  ");
            int boxSize = input.nextInt();

        int numRows = boxSize;
        int numCols = numRows;
        // This program demonstrates compound decisions with the logical and operator &&
        //asks if the number is less than or equal to 24 and greater than or equal to 2 and that the remainder is 0 
        //when divided by 2, checks if its an even number like it should be

        if(boxSize >= 2 && boxSize <= 24 && boxSize%2 == 0)
        {   
            //nested loops are used to print out the asterisk in the correct pattern
            for(int r = 0; r<numRows; r++)
            {
                    System.out.println("*");
                for(int c = 0; c<numCols; c++)      
                {   
                            System.out.print("*");    
                }
                    }
        }
    }

            //This program demonstrates compound decisions with the logical or ( || ) operator
        //checks if any of the following are true
        //if one or more is true then that means that it is an incorrect number
        //then reprompts the user to put in a new number then checks again
        if(boxSize<2||boxSize>24||boxSize% 2 != 0)
        {
            System.out.println("Value must be an even number from 2-24");
        }

Basically my problem is I don't know what to put in the loops and where to get the shape. I also don't know how to make it REPROMPT for a boxSize value again if the number is odd or not between 2 and 24 and it also needs to display the error message that value must be between 2 ans 24, and even ect.

基本上我的问题是我不知道在循环中放什么以及从哪里获得形状。如果数字在 2 和 24 之间为奇数或不为奇数,我也不知道如何再次为 boxSize 值设置 REPROMPT 并且它还需要显示值必须在 2 和 24 之间的错误消息,甚至等等。

回答by subsub

Your approach with nested loops is basically fine. Just the stuff inside is not quite what you are looking for.... What you want is more like this:

您使用嵌套循环的方法基本上没问题。只是里面的东西不是你想要的......你想要的更像是这样:

for(int r = 0; r<numRows; r++) {
    for(int c = 0; c<numCols; c++) {
        // print a "*" ONLY IF on border, and " " otherwise 
    }
    // here you finished printing the "*"/" ", so print just a newline
}

for promting and reprompting I would use a do {} while(yourIfCondition)loop, to reshow the prompt.

为了提示和重新提示,我会使用do {} while(yourIfCondition)循环来重新显示提示。

回答by TheRealChx101

Here. I put all of it in one method. Notice there's so many ifs. You can optimize by using the ternary operator if you have reached that part in your course.

这里。我把所有这些都放在一种方法中。注意有很多如果。如果您在课程中达到了该部分,则可以使用三元运算符进行优化。

public static void main(String...args){
        int boxSize = 0;
        Scanner input = new Scanner(System.in);

        do {
            System.out.print("Enter box size [-1 to quit] >> ");
            boxSize = input.nextInt();

            if(boxSize == -1){
                System.exit(0);
            }

            /* check if number is valid */
            if(boxSize < 2 || boxSize > 24 || boxSize % 2 != 0){
                System.err.println("--Error: please enter a valid number");
                continue; // prompt again
            }

            // draw the box
            for (int col = 0; col < boxSize; col++) {
                for (int row = 0; row < boxSize; row++) {
                    /* First or last row ? */
                    if (row == 0 || row == boxSize - 1) {
                        System.out.print("*");
                        if (row == boxSize - 1) {
                            System.out.println(); // border reached start a new line
                        }
                    } else { /* Last or first column ? */
                        if (col == boxSize - 1 || col == 0) {
                            System.out.print("*");
                            if (row == boxSize - 1) {
                                System.out.println();
                            }
                        } else {
                            System.out.print(" ");
                            if (row == boxSize - 1) {
                                System.out.println();
                            }
                        }
                    }
                }
            }

        }while (true);
    }