我的循环不会执行?

时间:2014-10-15 02:56:46

标签: java

import java.util.Scanner;

public class ManySubstrings {
    public static void main(String[] args) {
        String line;
        int sub, length;
        Scanner kb = new Scanner(System.in);
        System.out.print("Enter a string: ");
        line = kb.nextLine();
        System.out.print("Enter substring length: ");
        sub = kb.nextInt();
        length = line.length();

        for(int i=0; i< length;i=+sub){
            System.out.println(line.substring(i,sub));
            sub= + sub;
        }
    }
}

预期输出

 Enter a string: anthropomorphization
 Enter substring length: 3
 "ant"
 "nth" 
 "thr"
 "hro"
 "rop"
 "opo"
 "pom"
 "omo"
 "mor"
 "orp"
 "rph"
 "phi"
 "hiz"
 "iza"
 "zat"
 "ati"
 "tio"
 "ion"

我需要一个&#34; for&#34;循环遍历单词的长度,用户定义的子字符串长度,以获得单词的所有子串到最后

4 个答案:

答案 0 :(得分:1)

public static void main(String[] args) {
    String line;
    int sub, length;
    Scanner kb = new Scanner(System.in);
    System.out.print("Enter a string: ");
    line = kb.nextLine();
    System.out.print("Enter substring length: ");
    sub = kb.nextInt();
    length = line.length();

    for (int i = 0 ; i < length - (sub - 1) ; i++) { // no need to loop it to end of string length
        if (i + sub <= length)
            System.out.println(line.substring(i, i + sub));
    }
}

<强>输出

Enter a string: anthropomorphization
Enter substring length: 3
ant
nth
thr
hro
rop
opo
pom
omo
mor
orp
rph
phi
hiz
iza
zat
ati
tio
ion

答案 1 :(得分:0)

解决方案:

你差不多了,注意循环的配置方式。 你的解决方案试图在循环中过于聪明,而且过于复杂。

另请注意正确的格式设置如何使代码更易于阅读。

值得注意的是我们没有循环到字符串的完整末尾的条件。

重要:

我们在< line.length() -(sub - 1)处停止,因为我们将索引超过字符串的结尾并在我们继续前进时获得异常。

public static void main(final String[] args)
{
    final Scanner kb = new Scanner(System.in);
    System.out.print("Enter a string: ");
    final String line = kb.nextLine();
    System.out.print("Enter substring length: ");
    final int sub = kb.nextInt();

    for (int i = 0; i < line.length() - (sub-1); i++)
    {
        System.out.println(line.substring(i,i+sub));
    }

    // abcdefghijklmnopqrstuvwxyz
}

输出:

Enter a string: abcdefghijklmnopqrstuvwxyz
Enter substring length: 3
abc
bcd
cde
def
efg
fgh
ghi
hij
ijk
jkl
klm
lmn
mno
nop
opq
pqr
qrs
rst
stu
tuv
uvw
vwx
wxy
xyz

Enter a string: abcdefghijklmnopqrstuvwxyz
Enter substring length: 5
abcde
bcdef
cdefg
defgh
efghi
fghij
ghijk
hijkl
ijklm
jklmn
klmno
lmnop
mnopq
nopqr
opqrs
pqrst
qrstu
rstuv
stuvw
tuvwx
uvwxy
vwxyz

答案 2 :(得分:-1)

您可以将for更改为此:

for (int i = 0; i < length - sub + 1; i++){
    System.out.println(line.substring(i, i + sub));
}

这样做是从第一个字符迭代到第三个字符,始终substring - 从索引到索引+ sub

答案 3 :(得分:-1)

这段代码很复杂,并且是你的sub为每个循环加倍的原因

   sub= + sub;

使用++代替递增子

for(int i=0; i< length; i = sub){
    System.out.println(line.substring(i,sub));
    sub++;
}