2013-04-05 26 views
0

但是,我也打印出一個單詞的所有子串,我無法獲得最後的輸出。打印子串

import java.util.Scanner; 

public class printer { 
    public static void main(String[] args) { 
     Scanner scan = new Scanner(System.in); 
     System.out.println("Enter a word"); 
     String s = scan.nextLine(); 
     int i; 
     int j; 
     for (i=1; i<s.length(); i++) { 
      for (j=0; j+i<=s.length(); j++) { 
       String ss = s.substring(j, j+i); 
       System.out.println(ss); 
     } } 
    } 
} 

輸入

thunder 

輸出

t 
h 
u 
n 
d 
e 
r 
th 
hu 
un 
nd 
de 
er 
thu 
hun 
und 
nde 
der 
thun 
hund 
unde 
nder 
thunde 
hunder 
(missing thunder) 

當然,我只是把的System.out.println(S);在最後,但我希望它只是在完成for循環

+0

哦天哪,它是那麼容易...... – user2197917 2013-04-05 04:30:27

回答

8

您的循環條件外更改爲i<=s.length

6

更改支票在你第一次for循環迭代上i這樣: -

for (i = 1; i <= s.length(); i++) // "i" should be less than or equal to the length of "s" 
1

您需要取值爲i = s.length();

只是要外環爲for(i=1; i<=s.length(); i++)

0

讓ammendemends從

for (i=1; i<s.length(); i++) 

to 
for (i=1; i<=s.length(); i++)