gpt4 book ai didi

java - 从小字符打印大字符

转载 作者:搜寻专家 更新时间:2023-10-31 20:04:19 25 4
gpt4 key购买 nike

我正在尝试获取一个程序来打印带有 x 的“X”。即:

xxx      xxx
xxx xxx
xxx xxx
xxxxxx
xxx xxx
xxx xxx
xxx xxx

这是我到目前为止所做的:

import java.util.Scanner;
public class CustomXfactor {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean quit = false;
int i=0, a=0, c=0;

System.out.printf("length must be between 16 and 120\n");

//Ask for desired length
System.out.printf("Please enter the length (0 to exit):\n");
int length = in.nextInt();
int spaces = (length-length+1), //Calculate spaces before the first leg
innerSpaces = (length-6); //Calculate the inner spaces -6
//because there is 6 Xs which are
//the form the legs

while(!quit){
//Print first half of the X
for (i=0;i<(length/2);i++){

//First XXX leg
System.out.printf("XXX");

//Space between the legs
for (a=length-6;a<innerSpaces;a++){
System.out.printf(" ");
}
//Second XXX leg
System.out.printf("XXX\n");

//SPACES
for (c=0;c<(spaces);c++){
System.out.printf(" ");
}
spaces++;
innerSpaces--;
}
quit = true; //Change boolean to break while loop
}//END of while loop
}//END of method main
}//END end of class CustomXfactor

我的数学问题在第 26 行。我没有让循环在 X 的腿之间打印正确的空格,然后在循环时拿走一个。

如您所见,这只是 X 的一半,但一旦我得到这一边,我就可以将其反转以生成其余部分。

如果能在我的数学方面得到一些帮助,我将不胜感激。

最佳答案

分而治之方法将使您的工作更容易理解并且更容易解决。想一想如何处理每行尾随空格以及"XXX" 单元字符串之间的空格的打印问题。我不想完全解决您的问题,但我认为您应该看看这段代码以了解您缺少什么。使用此代码,您可以在 String 数组中获得所需输出的一半。然后按顺序遍历它,然后以相反的顺序遍历它,将为您提供正确的输出。

public static void main(String[] args) {
String unit = "XXX"; // Unit String.
int width = 21; // You can get this input from user.
int betweenSpaces = width - 2 * unit.length(), trailingSpaces = 0;

String[] lines = new String[(width - 2 * unit.length()) / 2 + 1];

for (int i = 0; i < lines.length; i++) {
lines[i] = "";
lines[i] = helper(trailingSpaces, lines[i], unit)
+ helper(betweenSpaces, lines[i], unit);

betweenSpaces -= 2; // Decrement space count by 2.
trailingSpaces += 1; // Increment trailing space count by 1.
}

// Printing lines array.
for (String str : lines)
System.out.println(str);
for (int i = lines.length - 2; i >= 0; i--)
System.out.println(lines[i]);
}

public static String helper(int count, String ref, String unit) {
for (int j = 0; j < count; j++)
ref += " ";
return ref += unit; // 2nd unit string appended.
}

输出:

XXX               XXX
XXX XXX
XXX XXX
XXX XXX
XXX XXX
XXX XXX
XXX XXX
XXX XXX
XXX XXX
XXX XXX
XXX XXX
XXX XXX
XXX XXX
XXX XXX
XXX XXX

关于java - 从小字符打印大字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13331605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com