Java 乘弦
比如说我想做一些“塔”,看起来像这样:Java 乘弦,java,string,for-loop,Java,String,For Loop,比如说我想做一些“塔”,看起来像这样: ********* ********* ********* ******* ********* ******* ********* ******* *************** ********* ******* *************** ********* ******* *************** ********* ******* *************** ********* ******* *************** ****
*********
*********
********* *******
********* *******
********* ******* ***************
********* ******* ***************
********* ******* ***************
********* ******* ***************
********* ******* ***************
********* ******* ***************
********* ******* ***************
如果我要求用户为塔楼的宽度输入三个不同的数字,并且一个随机整数将构成长度,那么我如何制作一个for循环,将用户为宽度输入的数字乘以“*”?这就是我到目前为止所做的:
for(int i = 0; i < randInt1; i++){
// I would like to do something like
// System.out.print("*") * width1
// and do this for all three towers so that they
// print next to each other separated by a space
}
for(int i=0;i
另一种解决方案是为每条线路的每个塔连接星形或白色空间。请注意generateString()
,它会在相关塔的宽度处返回一个字符串
public static void main(String[] args) {
// hardcoded settings (example)
// in your case you'll read it from the user
Integer[] widths = {5, 4, 6};
Integer[] heights = {5, 4, 6};
// subtract max-1 from the heights
int max = Collections.max(Arrays.asList(heights)) - 1;
for (int i=0; i<heights.length; i++)
heights[i] -= max;
// print the towers
for (int i=0; i<max; i++){
String line = "";
for (int j=0; j<widths.length; j++) {
if (heights[j] > 0)
line += generateString("*", widths[j]) + " ";
else
line += generateString(" ", widths[j]) + " ";
heights[j] += 1;
}
System.out.println(line);
}
}
private static String generateString(String str, int times) {
return String.format("%1$" + times + "s", str).replace(" ", str);
}
publicstaticvoidmain(字符串[]args){
//硬编码设置(示例)
//在您的情况下,您将从用户处读取它
整数[]宽度={5,4,6};
整数[]高度={5,4,6};
//从高度中减去max-1
int max=Collections.max(Arrays.asList(heights))-1;
for(inti=0;i用下面的代码块替换for循环应该可以工作
int highest = Math.max(randInt1, Math.max(randInt2, randInt3));
for(int i = highest; i > 0; i--){
printColumn(width1, randInt1, i);
System.out.print(" ");
printColumn(width2, randInt2, i);
System.out.print(" ");
printColumn(width3, randInt3, i);
System.out.println();
}
以及添加一个助手方法
private static void printColumn(int columnWidth, int columnHeight, int currentHeight) {
for(int j = columnWidth;j > 0;j--) {
if(columnHeight - currentHeight >= 0) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
}
您无法“乘”*“s。您可能需要逐行打印您的塔,并使用空格对齐每列。为了方便回答者或其他有类似问题的人,请添加一个特定的问题陈述-“它不工作”可以假设,但它如何不起作用?什么错误消息或错误行为是特征?你所说的“长度”是什么意思?它是每列的“高度”吗?@BingLu是的,它意味着高度。如果你重构内部for循环以避免代码重复-你会得到我的投票;)更好-这就是方法!)