嘿,我真的需要帮助我的java编程类的程序。我将介绍我到目前为止的说明和代码。任何帮助,将不胜感激!提前致谢!!说明:编写一个名为Box(Box.java)的程序,它将使用星号(*)打印/显示空心框形状。程序将读取2到24范围内的偶数,以指定框中的行数/列数。如果输入的值不正确,则显示错误并重新提示该号码。然后程序将显示适当大小的空心。提示:在循环中使用循环。基本上它应该是一个方框,所以如果你给它数字boxSize = 5输出是一个尺寸为5x5的盒子。轮廓由星号组成,但内部是空的
到目前为止,我的代码是什么
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");
}
基本上我的问题是我不知道在循环中放什么以及在哪里获得形状。如果数字是奇数或不在2到24之间,我也不知道如何再次使用它作为boxSize值,并且还需要显示错误消息,该值必须介于2和24之间,甚至等等。
你使用嵌套循环的方法基本上没问题。只是里面的东西不是你想要的....你想要的更像是这样的:
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
}
为了促进和提示我会使用qazxsw poi循环来重新显示提示。
这里。我把所有这些都放在一个方法中。请注意,有很多ifs。如果您已经在课程中达到该部分,则可以使用三元运算符进行优化。
do {} while(yourIfCondition)