如何在 java 中使用嵌套 for 循环在每个字符后输出带有限制的连字符



我在每个字符后输出连字符(包括下面代码中显示的三个点(时只有一个小问题

示例输入

2 (option #)
disappear (phrase)

预期产出:

d-i-s-a-p-p-e-a-r-.-.-.
d-i-s-a-p-p-e-a-.-.-.
d-i-s-a-p-p-e-.-.-.
d-i-s-a-p-p-.-.-.
d-i-s-a-p-.-.-.
d-i-s-a-.-.-.
d-i-s-.-.-.
d-i-.-.-.
d-.-.-.
.-.-.
.-.
.

它在每个字符后输出"-",不包括最后一个点

我得到了"-"显示在非常单词字符之后,但也无法弄清楚在点之后显示,就像它有效一样,但必须少一个连字符:

我的实际输出:

d-i-s-a-p-p-e-a-r-.-.-.-
d-i-s-a-p-p-e-a-.-.-.-
d-i-s-a-p-p-e-.-.-.-
d-i-s-a-p-p-.-.-.-
d-i-s-a-p-.-.-.-
d-i-s-a-.-.-.-
d-i-s-.-.-.-
d-i-.-.-.-
d-.-.-.-
.-.-.-
.-.-
.-

我已经完成了部分,我只需要少一个连字符,它也会自动满足在最后一个点之后不显示连字符的要求。

法典:

else if (option == 2){
for (int x = 0; x < phrase.length(); x++){
for (int y = 0; y < phrase.length() - x; y++){
char n = phrase.charAt(y);
System.out.print(n+"-");
}
for (int a = 0; a < 3; a++){
System.out.print("."+"-");
}
System.out.println("");
}
for (int j = 0; j < 3; j++){
for (int i = 0; i < 3 - j; i++){
System.out.print("."+"-");
}
System.out.println("");
}
}

删除最后一个-的一种方法是仅在不是最后一次迭代时打印-。您可以通过选中loopVariable != loopBound - 1来检查它是否不是最后一次迭代。

所以你的代码将是:

for (int x = 0; x < phrase.length(); x++){
for (int y = 0; y < phrase.length() - x; y++){
char n = phrase.charAt(y);
System.out.print(n+"-");
}
// You could just print the literal "--.-." instead
for (int a = 0; a < 3; a++){
System.out.print(".");
if (a != 2) { // Notice here!
System.out.print("-");
}
}
System.out.println();
}
for (int j = 0; j < 3; j++){
for (int i = 0; i < 3 - j; i++){
System.out.print(".");
if (i != 2 - j) { // and here
System.out.print("-");
}
}
System.out.println();
}

以下是我会怎么做:

// pretend that the phrase is 3 characters longer than it actually is...
// because of the three dots at the end
for (int x = 0; x < phrase.length() + 3; x++){
for (int y = 0; y < phrase.length() + 3 - x; y++){
char n;
// Should we print the phrase or the dots?
if (y < phrase.length() - x) {
n = phrase.charAt(y);
} else {
n = '.';
}
System.out.print(n);
if (y != phrase.length() + 2 - x) { // same trick of checking if it is last iteration
System.out.print("-");
}
}
System.out.println();
}

最新更新