循环结构,非常困惑

时间:2016-02-13 05:29:49

标签: java loops

  

你将取两个矩形边长(n * m)。然后,您将使用多个字符“O”在屏幕上打印矩形。

     

矩形在一侧为n'O',在另一侧为m'O'。因此,如果用户输入4(col)和3(row),则矩形应如下所示:

     

OOOO

     

OOOO

     

OOOO

     
      
  1. 声明2个变量:1表示行数,1表示col数。

  2.   
  3. 提示用户输入行数和col数。

  4.   
  5. 使用循环(提示:考虑嵌套循环)来显示矩形。

  6.         

    注意:您不必遵循特定的输入/输出格式,但在查看代码之前,我应该能够理解如何使用和理解您的程序

         

    注意:不要忘记输入验证!行或者col的有效值是什么?

         

    注意:您的程序是否有输入限制? (例如输入范围?)

到目前为止我所拥有的:

public static void main(String[]args){

    int row;
    int column;

    Scanner input = new Scanner(System.in);


    System.out.print("Please enter an integer (row) greater than 0 and less than 15: ");
    row = input.nextInt();

    System.out.print("Please enter an integer (column) greater than 0 and less than 15: ");
    column = input.nextInt();

http://i.stack.imgur.com/C6NJx.jpg

1 个答案:

答案 0 :(得分:1)

你应该尝试解决自己,因为学习经历的一部分正在挣扎,但如果它可能对你有所帮助,那么代码中会有一些评论。

        int row = 0;
        int column = 0;

        Scanner input = new Scanner(System.in);
        boolean nonValid = true; //if nonvalid is true the user input is wrong
        while (nonValid) { // keep asking user for input until it is according to your requirements
            System.out.print("Please enter an integer (row) greater than 0 and less than 15: ");
            row = input.nextInt();
            System.out.print("Please enter an integer (column) greater than 0 and less than 15: ");
            column = input.nextInt();
            if (row > 0 && row < 15 && column > 0 && column < 15) {//check user input here if it is good change nonValid to false to exit loop
                nonValid = false;
            } else {
                System.out.println("Bad Input try again!");
            }
        }
        for (int i = 0; i < row; i++) {//this loops rows
            for (int j = 0; j < column; j++) {//this loops columns
                System.out.print("O");//use print as you need each "O" next to each other in a row
            }//
            System.out.println("O");//after each row is printed use println(new line) to move to next line
        }