Exception- in thread “main” java.lang.ArrayIndexOutOfBoundsException

后端 未结 2 1177
野趣味
野趣味 2021-01-29 06:38
public class Sum {

public static void main(String args[])
{
    int x,y,s; 
    x=Integer.parseInt(args[0]); 
    y=Integer.parseInt(args[1]);
    s=x+y;
   System.out.         


        
2条回答
  •  再見小時候
    2021-01-29 07:04

    You need to pass the command-line arguments:

    java Sum 0 1
    

    It's also recommended to check length in this case:

    int x,y,s;
    if(args.length>=2){
      x=Integer.parseInt(args[0]);
      y=Integer.parseInt(args[1]);
      s=x+y;
      System.out.println("sum  "  +s);
    }
    

    And considering the intent of the program, you might want to loop the args[] array directly, and sum all numbers instead of just the first 2:

    int total = 0;
    for (int i = 0; i < args.length; i++) {
      total = total + Integer.parseInt(args[i]);
    }
    System.out.println("Total: " + total);
    

    Command-line: java Sum 1 2 3 4 5 results in Total: 15

提交回复
热议问题