简体   繁体   中英

How to take single input in java

I'm trying to take input by using code int rs=Integer.parseInt(args[0]); but it throw exception ArrayOutOfBondException . Please help me code is below.I need to take input only one time in commandline argument

package techgig;
import java.util.*;

public class Techgig {


 public static int ta[]={1,12,5,111,200,1000,10,9,6,7,4};


public static void main(String[] args) {
  Vector v = new Vector();    
    // TODO code application logic here
    System.out.println("Amount Mark has:");
    System.out.println("=============================");//here is the code
    int rs=Integer.parseInt(args[0]);
   // int rs=50;
    System.out.print("===============================");
  //int a=0;
    int count=0;
    int min=0,temp,totalamount=0;
  System.out.print("\nToys Available:{");

 for(int a=0;a<ta.length;a++)
 {
     if(a!=0)
     {
         System.out.print(",");
     }
     System.out.print(ta[a]);

 }
 System.out.print("}\n");
 System.out.println("Buy Maximum toys with maximum left");

  for(int i=0;i<ta.length;i++)
  {

  // System.out.print("\t"+ ta[i]);
       for( int j=i+1;j<ta.length;j++)
      {
          if(ta[j]<ta[i])
          {
              temp=ta[j];
              ta[j]=ta[i];
              ta[i]=temp;
          }
         // System.out.print("\t"+ ta[i]);
      }

  }

  for(int k=0;k<ta.length;k++)
  {

      totalamount=min;
     // System.out.print("\t"+ ta[k]);
      min=min+ta[k];
      if(min >rs)
      {
          break;

      }
      count=count+1;
      v.add(ta[k]);
  }

  int sav=0;
  sav=rs-totalamount;
  //System.out.println("Amount Mark has:"+rs);
  System.out.println("Output:{"+v.size()+","+sav+"}");
  System.out.println("Explanation");      
  System.out.println("Maximum number of toys="+v.size()+""+v);
  System.out.println("Saving="+sav);
}
}

You need to pass command line arguments while running java program.

If you don't pass any command line arguments then args will be empty array, that is with length 0 . And accessing 0 th element from empty array will throw ArrayIndexOutOfBoundsException .

Let the name of the class having your main method is MyClass.java Then you must run your program from command line like

java MyClass 12

Where 12 is the command line argument which you are passing to your program(you may try with different argument)


在此处输入图片说明

Note: When you will not pass any argument but access the args in your program then you will see this exception originating

If you want to use args[0] you need to pass command line arguments to the program. If you're running your program from an IDE, you will get the exception that you get.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM