嘿,我真的需要帮助我的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之间,甚至等等。 / p>
答案 0 :(得分:0)
使用嵌套循环的方法基本上没问题。只是里面的东西不是你想要的......你想要的更像是这样:
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
}
对于proming和reprompting我将使用do {} while(yourIfCondition)
循环来重新显示提示。
答案 1 :(得分:0)
下面。我把所有这些都放在一个方法中。请注意,有很多ifs。如果您已经在课程中达到该部分,则可以使用三元运算符进行优化。
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);
}