日期:2014-05-20  浏览次数:20683 次

有两道题大家帮忙!
1.Create a class named SumOfArgs that will print out the sum of all integer arguments found on the command line. Anything that is not an integer should be skipped (should not contribute to the sum). Your progam should print out only the sum (nothing else!). No error messages can be printed out (no matter what the command line args look like). Examples of what your class should do when run:

> java SumOfArgs 
0
> java SumOfArgs 10 9 8
27
> java SumOfArgs hello dave 1 2 3
6
> java SumOfArgs Hello World
0


2.Create a class named Substring that will expect the first command line argument to be a string, and the second two command line arguments to be integers, the first will be used as an index and the second as a length. The output should be the subtring of string starting at the index and of the specified length. Examples:

> java Substring Jello 1 3
ell
> java Substring "Hello World" 0 5
Hello
> java Substring OneTwoThree 5 1
o

主要是不知道怎么利用command line 传入的参数,拜托大家了
------解决方案--------------------
public void main(String[] args) 这个参数!
------解决方案--------------------
第一题

public static void main(String args[])
 {
int a = 0,sum =0;
    for(String s : args){
     try{
     a = Integer.parseInt(s);
     }catch(Exception ex){
    
     }
     sum = SumOfArgs(sum,a);
    }
    System.out.println(sum);
 }
 
 public static int SumOfArgs(int a,int b){
 return a+b;
 }


第二题

public static void main(String args[])
 {
System.out.println(args[0].substring(Integer.parseInt(args[1]),Integer.parseInt(args[1])+Integer.parseInt(args[2])));
 }


至于怎么用
老师在题目里已经给出了java SumOfArgs 10 9 8 这些就是命令了

在ECLIPSE这些IDE里面可以直接在Run Configurations或者Debug Configurations的Agruments里面输入参数就行了
------解决方案--------------------
第一题

引用:
第一题

public static void main(String args[])
 {
int a = 0,sum =0;
    for(String s : args){
     try{
     a = Integer.parseInt(s);
     }catch(Exception ex){
    
     }
     sum = SumOfArgs(sum,a);
    }
    System.out.println(sum);
 }
 
 public static int SumOfArgs(int a,int b){
 return a+b;
 }


第二题

public static void main(String args[])
 {
System.out.println(args[0].substring(Integer.parseInt(args[1]),Integer.parseInt(args[1])+Integer.parseInt(args[2])));
 }


至于怎么用
老师在题目里已经给出了java SumOfArgs 10 9 8 这些就是命令了

在ECLIPSE这些IDE里面可以直接在Run Configurations或者Debug Configurations的Agruments里面输入参数就行了


+1