-3

我想通过命令行Java中传递一个字符串,但它只返回即args[0]返回参数

下面的第一个值是我做了什么

public class CommandLine 
{ 
    public static void main(String[] args) 
    { 
     int i; 
     i = args[0].length(); //throws error here if args.length(); 
     System.out.println(i); //checking length, return with args[0] only 
     while(i>0) 
     { 
      System.out.println(args[0]); 
      i++; 
     } 
    } 
} 

我应该怎么做才能改善这种状况并使之发挥作用?

+0

嗯,你的循环特别说'ARGS [0]',所以我想它是做什么的,你告诉它。但是'while(i> 0)'和'i ++'听起来不太合适...... – John3136

+0

是的,我很清楚这一点,我只是因为'args.length() ;'让我听起来很愚蠢,并没有奏效。 –

回答

2

这里有一些事情需要处理

  1. 在你的逻辑命令行arugment长度采取错误的方式。

  2. 循环条件并不适合您的要求,而且它是一个无限循环或永无止境的循环,它会降低代码的性能。切勿在代码中使用无限循环。

3.您每次打印相同的索引,即每次循环内的args [0]。

代码:

public static void main(String[] args) 
    { 
     int i=0; 
     int len = args.length; //use length only in this case; 
     System.out.println(len); // this will return it properly now 
     while(i<len) 
     { 
      System.out.println(args[i]); 
      i++; 
     } 
    }