Java 想让我的环跑开又跑回吗

Java 想让我的环跑开又跑回吗,java,for-loop,Java,For Loop,我想要得到的是: Welk woord wil je Af/Opbouwen? MARSEPEIN MARSEPEIN MARSEPEI MARSEPE MARSEP MARSE MARS MAR MA M MA MAR MARS MARSE MARSEP MARSEPE MARSEPEI MARSEPEIN 我现在得到的是: welk woord wil je op en af? marsepein marsepein marsepei marsepe marsep marse mars m

我想要得到的是:

Welk woord wil je Af/Opbouwen?
MARSEPEIN
MARSEPEIN
MARSEPEI
MARSEPE
MARSEP
MARSE
MARS
MAR
MA
M
MA
MAR
MARS
MARSE
MARSEP
MARSEPE
MARSEPEI
MARSEPEIN
我现在得到的是:

welk woord wil je op en af?
marsepein
marsepein
marsepei
marsepe
marsep
marse
mars
mar
ma
m

m
ma
mar
mars
marse
marsep
marsepe
marsepei
marsepein
但是我的程序的问题是重定向之间有空间。有没有其他/更好的方法可以做到这一点

我的代码:

System.out.println("welk woord wil je op en af?");
String woord = s.next();

for (int i = woord.length(); i >= 0; i--) {
    System.out.println(woord.substring(0, i));


    if (i == 0) {
        for (int j = 0; j <= woord.length(); j++) {
            System.out.println(woord.substring(0, j));
        }
    }
}
System.out.println(“welk-woord-wil-je-op-en-af?”);
字符串woord=s.next();
对于(int i=woord.length();i>=0;i--){
System.out.println(woord.substring(0,i));
如果(i==0){

对于(int j=0;j从长度到1的循环:

for (int i = woord.length(); i >= 1; i--) {
    System.out.println(woord.substring(0, i));
}
然后从2向上循环到长度:

for (int i = 2; i <= woord.length(); i++) {
    System.out.println(woord.substring(0, i));
}
for(int i=2;i
System.out.println(“welk woord wil je op en af?”);
字符串woord=s.next();
对于(int i=woord.length();i>0;i--){
System.out.println(woord.substring(0,i));
如果(i==1){
对于(int j=2;j 0
检查
i==1

并初始化
j=2

更改for循环中的条件

for (int i = woord.length(); i > 0; i--) {
        System.out.println(woord.substring(0, i));

        if (i == ) {
            for (int j = 2; j <= woord.length(); j++) {
                System.out.println(woord.substring(0, j));
            }
        }
}
for(int i=woord.length();i>0;i--){
System.out.println(woord.substring(0,i));
如果(i==){

对于(intj=2;j,实际上不需要两个循环

以下是一个可能的解决方案:

for (int i = 0; i < 2*woord.length() - 1; i++) {
        int endIndex = i < woord.length() ? woord.length() - i : i - woord.length() + 2;
        System.out.println(woord.substring(0, endIndex));            
    }
for(int i=0;i<2*woord.length()-1;i++){
int-endIndex=i

循环始终运行
2*length-1
次。在第一阶段,它通过执行
woord.length()-i
沿字符串长度向左移动,并且一旦到达第一个字符,即
i
,它向右移动。由于您不希望出现空字符串,并且第一个字符打印两次,代码的
+2
部分跳过了这些系统输出。

2个独立的循环比嵌套这些循环更易于阅读和推理谢谢,这似乎有点困难哈维尔,不要被
三元运算符吓倒
它只执行以下操作:
if(i
for (int i = 0; i < 2*woord.length() - 1; i++) {
        int endIndex = i < woord.length() ? woord.length() - i : i - woord.length() + 2;
        System.out.println(woord.substring(0, endIndex));            
    }