2014-03-02 127 views
0

我必須在命令行中循環一個字符串,例如(java Lab2「HELLO WORLD」),並使用循環打印出子字符串[HELLO]和[WORLD] 。這是我到目前爲止。通過命令行字符串循環打印輸出字

public static void main(String argv[]) 
{ 
    if (argv.length() == 0) 
    { 
     System.out.println("Type in string"); 
    } 

    String Input = argv[0]; 
    String sub; 

    for (int end = 0; end < Input.length(); end++) 
    { 
     end = Input.indexOf(' '); 
     sub = Input.substring(0, end); 
     System.out.println("sub = [" + sub + "]"); 


     if(end > 0) 
     { 
      int start = end +1; 
      end = Input.indexOf(' '); 
      sub = Input.substring(start,end); 
      System.out.println("sub = [" + sub + "]"); 
     } 
    } 
} 
} 

輸入中的第一個單詞將打印出正常。之後,我會得到一個無限循環,否則我會拋出一個索引數組超出範圍的異常。異常是指for循環中的if語句。

回答

0

這是一個辦法做到這一點:

if (argv.length == 0) // Length it not a method 
{ 
    System.out.println("Type in string"); 
    return; // the code should be stopped when it happens 
} 

String input = argv[0];// Avoid use this kind of name 

int idx; 
int lastIndex = 0; 

// indexOf returns the index of the space 
while ((idx = input.indexOf(' ', lastIndex)) != -1) 
{ 
    System.out.println("[" + input.substring(lastIndex, idx) + "]"); 
    lastIndex = idx + 1; 
} 

System.out.println("[" + input.substring(lastIndex, input.length()) + "]"); 

我用indexOf知道每一個空間的字符串中的指標..需要的最後一行,因爲它可以」 t找到最後的話。 一個解決它的方法是:

if (argv.length == 0) // Length it not a method 

{ 
    System.out.println("Type in string"); 
    return; // the code should be stopped when it happens 
} 

String input = argv[0] + " ";// Avoid use this kind of name 

int idx; 
int lastIndex = 0; 

// indexOf returns the index of the space 
while ((idx = input.indexOf(' ', lastIndex)) != -1) 
{ 
    System.out.println("[" + input.substring(lastIndex, idx) + "]"); 
    lastIndex = idx + 1; 
} 

我想你注意到+ " ";input

+0

有沒有辦法在循環中拋出if語句來打印出最後一個單詞? – user3047768

+0

什麼?我不明白 –

+0

嗯,當它到達'while'結尾的最後一個單詞時,最後一個單詞在'lastIndex'中指向'input.length()'。只需在 –

0

看起來你試圖自己分割字符串過於複雜。 大多數編程語言(如Java)都有一個split()函數,該函數會將一個字符串拆分成一個數組,該字符串將某個子字符串(在您的情況下爲" ")拆分爲一個字符串。然後,您可以使用foreach語句遍歷此數組。在Java中,的foreach就像做:

for (String current : String[] array) { } 

而且爲分體式,你需要做的:

String[] elements = Input.split(" "); 

這麼幹脆,你可以這樣做:

String[] elements = Input.split(" "); 

for (String sub : elements) { 
    System.out.println("sub = [" + sub + "]"); 
} 
+0

我要做這種方式。這是我必須完成的更多邏輯問題......如果我能夠實現的話,我一定會節省自己的時間和空間。 – user3047768

0

在行,

int start = end + 1;

如果(完> 0){

如果start爲6,則最終將在5這裏..然後 Input.sub串(6,5)肯定是不對的,因爲一開始指數應該總是少比這反之亦然這裏結束索引

+0

這有點幫助。我糾正了它......希望 – user3047768