java - 静态字符串怪异行为 Diamond Star Pattern 问题
问题描述
我正在尝试解决这个问题,给出数字 5,我们显示:
*
*****
*********
*****
*
等等。所以你给它一个数字,它会像上面那样为你格式化。我尝试使用下面的代码解决它,但我看不到代码中的问题所在。
public class Exe01 {
public static String space = "";//global space var
public static String ast = "";//global * var
public static String adjustAst(int numOfAst) {
Exe01.ast = "";
for (int i = numOfAst; i > 0; i--) {
Exe01.ast+="*";
}
return Exe01.ast;
}
public static String adjustSpaces(int numOfSpaces) {
Exe01.space = "";
for (int i = numOfSpaces; i > 0; i--) {
Exe01.space = Exe01.space + " ";
}
return Exe01.space;
}
public static void showAst(int num) {
if (num <= 0 || num % 2 == 0)
System.out.println("arg to the function need to be positive and odd");
else if (num == 1)
System.out.println("*");
else {
int mid = (int) (num / 2);
int numberOfSpaces = num - 1;
for (int i = 0; i < num; i++) {
int k = 0;
if (i < mid) {
k = k * 2 + 1;
System.out.println(Exe01.adjustSpaces(numberOfSpaces) + Exe01.adjustAst(k));
numberOfSpaces = numberOfSpaces - 2;
} else if (i == mid) {
numberOfSpaces = 0;
k = k * 2 + 1;
System.out.println(Exe01.adjustSpaces(numberOfSpaces) + Exe01.adjustAst(k));
numberOfSpaces = numberOfSpaces + 2;
} else {
k = k - 4;
System.out.println(Exe01.adjustSpaces(numberOfSpaces) + Exe01.adjustAst(k));
numberOfSpaces = numberOfSpaces + 2;
}
}
}
}
public static void main(String args[]) {
Exe01.showAst(5);
}
}
在编译时它给了我这个:
*
*
*
解决方案
推荐阅读
- python - The Tutorials in Qiskit: Option Pricing with qGANs
- javascript - Gatsby and react-intl - How to make current language key available as global context?
- docker - 所有 docker 镜像都需要基础镜像吗?
- r - aggregate daily values to monthly for each pixel in a polygon using google earth engine
- python - Correct Way to Fine-Tune/Train HuggingFace's Model from scratch (PyTorch)
- javascript - 在 Google Colab 上,来自 Javascript 的 localhost 访问失败
- java - Refactor my Java code to replace attribute access to getters and setters
- azure-web-app-service - 为静态 Web 应用程序购买域名
- sql-server - Azure 链接表需要防火墙规则?
- ajax - 如何使用 AJAX 调用 AWS Lambda 函数?