我正在上我的第一个 Java 类(class),我正在尝试使用星号绘制一个半箭头。我应该使用嵌套循环,其中内部循环绘制 *s,外部循环迭代次数等于箭头底部的高度。我已经学习了 if-else、while 循环和 for 循环。
到目前为止,我已经能够为
的输入值正确绘制箭头
箭头底部高度:5
箭头底部宽度:2
箭头宽度:4
当我尝试添加一个 while 循环作为外层循环时,程序超时。我很茫然。
我需要使用的下一个输入是 2、3、4。我的代码获取右基的高度 (2),但不是宽度。
我需要的最后一个输入是 3, 3, 7。我的代码根本没有得到正确的结果。这是我目前所拥有的。
我应该使用什么样的循环来获得正确的宽度?
Scanner scnr = new Scanner(System.in);
int arrowBaseHeight = 0;
int arrowBaseWidth = 0;
int arrowHeadWidth = 0;
int i = 0;
System.out.println("Enter arrow base height: ");
arrowBaseHeight = scnr.nextInt();
System.out.println("Enter arrow base width: ");
arrowBaseWidth = scnr.nextInt();
System.out.println("Enter arrow head width: ");
arrowHeadWidth = scnr.nextInt();
for (i = 1; i <= arrowBaseHeight; ++i) {
// Draw arrow base (height = 3, width = 2)
System.out.println("**");
}
// Draw arrow head (width = 4)
System.out.println("****");
System.out.println("***");
System.out.println("**");
System.out.println("*");
输出箭头的外观示例:
**
**
**
**
****
***
**
*
最佳答案
对于这个问题,您可能希望使用 for 循环,因为您知道它应该重复的确切次数。你知道这一点是因为用户输入了箭头每个部分的大小。
Scanner scnr = new Scanner(System.in);
int arrowBaseHeight = 0;
int arrowBaseWidth = 0;
int arrowHeadWidth = 0;
int i = 0;
System.out.println("Enter arrow base height: ");
arrowBaseHeight = scnr.nextInt();
System.out.println("Enter arrow base width: ");
arrowBaseWidth = scnr.nextInt();
System.out.println("Enter arrow head width: ");
arrowHeadWidth = scnr.nextInt();
//Your code above | Below is the modified code
String ast = ""; //String ast will contain how many asterisk we want for the base width;
for (int x = 1; x <= arrowBaseWidth; x++) //Loop forms the base width of the arrow
{
ast += "*"; //This adds as many asterisks as we need to make the base width. SO if they enter 4, we get 4 *;
}
for (i = 1; i < arrowBaseHeight; ++i)
{
System.out.println(ast); //Prints out the base width, which is now a String object
}
int tempHeadWidth = arrowHeadWidth; //Added this tempHeadWidth variable since we will be modifying it directly and
//we don't want to modify the original data and variable (it will cause problems if we do.
for (int y = 1; y <= arrowHeadWidth; y++)
{
for(int z = tempHeadWidth; z > 0; z--) //This loop prints the amount of asterisks we need per line in the arrowHead
{
System.out.print("*");
}
// Once the loop above is finished, the rest of the code will execute in the main for-loop and then scheck if it will run again.
tempHeadWidth -= 1; //So we are lowering the tempHeadWidth by one so the next time it enters
//the nested (2nd) for loop it will be one asterisk smaller
System.out.println(); //This makes a new line to keep adding more stars for the next row
}
此方法允许用户为箭头输入任意大小(当然,同时保持在 int 的值边界内)
关于java - 如何在 java 中绘制带星号的半箭头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39395849/