该程序的目标是使用一根字符串并使用与您在电子管上经常看到的字母类似的字母创建一个金字塔形状。程序首先询问用户要转换的字符串,然后询问用户是否要忽略空格,如果决定忽略空格,则当程序减去/添加字符时,空格将被忽略。我已经编码了大约一周,但尚未学会如何正确创建类。任何关于如何使用更高级的编码来改进我的代码的建议将不胜感激。
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
String fls = "FALSE";
String tr = "TRUE";
Scanner stringWord = new Scanner(System.in);
System.out.print("Enter the string you wish to convert: ");
String example = stringWord.nextLine();
Scanner whiteSpaceOrNo = new Scanner(System.in);
System.out.print("\nTrue or false, you want to ignore whitespace: ");
String whiteSpace = whiteSpaceOrNo.nextLine();
System.out.print("\n");
if(whiteSpace.toUpperCase().equals(fls))
{
for(int i = 0; i < example.length()+1; i++)
{
if(i < example.length())
{
System.out.println(example.substring(0, i + 1));
}
else
{
for(int f = example.length(); f > 0; f--)
{
System.out.println(example.substring(0, f-1));
}
}
}
}
else if (whiteSpace.toUpperCase().equals(tr))
{
for(int d = 0; d < example.length(); d++)
{
if(example.charAt(d) != ' ')
{
System.out.println(example.substring(0, d+1));
}
if(d == example.length() - 1)
{
for(int x = example.length() - 1; x >= 0; x--)
{
if(example.charAt(x) != ' ')
{
System.out.println(example.substring(0, x+1));
}
}
}
}
}
else
{
System.out.println("Incorrect response, restart program");
}
}
}
最佳答案
改进建议:
- 用户界面
- 将用户查询和输出放入循环中,以便用户不必每次都重新启动应用
- 当简单的 Y 或 N(或是或否)就可以时,不要要求用户输入 true 或 false。所以你的查询将是:“忽略空格(是/否)?”
- 为了获得加分,请使用 GUI。
- 代码异味/问题
- 不需要嵌套循环。这可以在以
i < example.length()
结尾的 i-loops 之后被带出并运行。 (在第一部分中,不忽略空格)。 - “忽略空格”是指您正在构建的整个金字塔,还是只是没有末尾有空格字符的行?如果是后者,您需要修复您的用户查询;如果是前者,您需要修复代码
- 不需要嵌套循环。这可以在以
- 关注点分离
- 将实际构建/写入金字塔字符串的部分删除到一个或两个单独的方法调用中。收集用户的输入是将其字符串转换为另一个输出字符串的一个单独的关注点。
- 最后为自己创建另一个类并将该/那些方法调用放入其中。
关于java - 我对java完全陌生,想知道是否有任何方法可以改进这个程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59959524/