gpt4 book ai didi

java - 循环结构,很困惑

转载 作者:行者123 更新时间:2023-12-01 10:25:30 25 4
gpt4 key购买 nike

You will take int two length of the side of a rectangle (n * m). You will then use a number of the character ‘O’ to print a rectangle to the screen.

The rectangle will be n ‘O’ in one side and m ‘O’ in other side. So id the user enters 4(col) and 3(row), the rectangle should look like:

OOOO

OOOO

OOOO

  1. Declare 2 variables: 1 for the number of row, and 1 for the number of col.

  2. Prompt the user to input the number of row and the number of col.

  3. Use loops (Hint: consider nest loops) to display the rectangle.

Note : You do not have to follow a particular input/output format, but I should be able to understand how to use and understand your program before looking at the code

Note: Don’t forget input validation! What’s a valid value for a row or a col?

Note: Does your program has the input limitation? (e.g. the range of input?)

到目前为止我所拥有的:

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();

/image/C6NJx.jpg

最佳答案

您应该尝试解决自己的问题,因为学习经历的一部分很困难,但如果它可以帮助您学习,这里是带有一些注释的代码。

        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
}

关于java - 循环结构,很困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35376470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com