我的任务是分配打印矩形。用户将输入要打印的长度,宽度和符号。由此将输出矩形。这部分任务完成了。我的下一个任务是从负值打印一个矩形,该矩形只打印矩形的轮廓(内部区域为空白)。我在创建在这种情况下使用的算法时遇到了困难。
任何帮助都将不胜感激。
干杯。
import java.util.Scanner;
public class Rectangle
{
public static void main(String[] args)
{
boolean loopExecuted;
String userContinue = "NO";
// Loop to ask to do another rectangle
do
{
// Variables
int length;
int width;
String symbol;
char symbolz;
int xLength;
int yWidth;
// Name Scanner
Scanner input = new Scanner(System.in);
// What program will do
System.out.println("This program will print a rectangle with the symbol of your choice. If you enter a positve integer the rectangle"
+ "will be filled, if you enter a negative integer, it will print the outline of the rectangle.\n");
// Ask for user input and check for validity
do
{
System.out.println("Please enter the length of the rectangle that is less than or equal to -10 and less than or equal to 10.");
length = input.nextInt();
}
while (length < -10 || length > 10 || length == 0);
do
{
System.out.println("Please enter the width of the rectangle that is less than or equal to -10 and less than or equal to 10.");
width = input.nextInt();
}
while (width < -10 || width > 10 || width == 0);
System.out.println("Please enter the symbol to be used for the rectangle");
symbol = input.next();
symbolz = symbol.charAt(0);
System.out.println("You have entered the following values for length, width, and symbol: " + length + " ," + width + " ," + symbolz +"\n");
// Algorithm to print filled in rectangle.
for (yWidth = 1; yWidth <= width; yWidth++) {
for (xLength = 1; xLength <= length; xLength++) {
System.out.print(symbolz);
}
System.out.println(" ");
}
// Algorithm to print outline of rectangle
//TODO
for(yWidth = 1; yWidth >= width; yWidth--){
for (xLength = 1; xLength >= length; xLength--){
System.out.print(symbolz);
}
System.out.println(" ");
}
// Repeat the program
loopExecuted = false;
do
{
if (!loopExecuted)
{
System.out.println("\n\nWould you like to continue? Please either Yes or No");
}
else
{
System.out.println("Please enter a valid response (Yes / No)");
}
userContinue = input.next();
userContinue = userContinue.toUpperCase();
loopExecuted = true;
}
while (!"YES".equals(userContinue) && !"NO".equals(userContinue));
// Case Insensitive
userContinue = userContinue.toUpperCase();
}
while (userContinue.equals("YES"));
}
}
答案 0 :(得分:2)
我会回答你的问题,但首先我会提出一个建议:使用功能!打破你的一大主要功能。将代码分解为更小的函数有助于使其更易于理解和维护(尤其是查找内容)。你使用评论的任何地方都是一个很好的功能。例如,getInput(),printFilledRectangle(int width,int height,char symbol)等。
现在提问:
考虑打印未填充矩形的规则。在我看来,有三个:
1)如果这是第一行,则打印符号n次(其中n =宽度) 2)如果这是最后一行,则打印符号n次 3)否则打印一个符号,打印n-2个空格,然后打印另一个符号
所以现在将这些规则合并到非填充循环中。希望有所帮助。
编辑:
好的 - 我可以帮你开始
for (row = 0; row < height; row++)
if (row == 0 || row == height - 1) // first or last row
// print your symbol n times, where n = width
else // otherwise, this is an "internal" row
// print 1 symbol, n-2 spaces, then 1 symbol again