2014-03-02 190 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