i want to access the arraylist from one method to another method in same class without argument

Viewed 36

here i want to use the arraylist arrc in another method choosec. In the highlighted line in choosec method when use call in this way then it call the method addc() once again and i have to give input for it once again. I don't want this to happen. I just want the data of arrc.

    /*code starts here*/
public void addc()
  {
    ArrayList<Hashtable> arrc  = new ArrayList<Hashtable>();
    Hashtable<String, String> nr = new Hashtable<String, String>();
    Hashtable<String, Float> nc = new Hashtable<String, Float>();
    Hashtable<String, Integer> nl = new Hashtable<String, Integer>();
    Scanner sc = new Scanner(System.in);
    System.out.print("name:-");
    String cname = sc.nextLine();
    System.out.print("role:-");
    String role = sc.nextLine();
    System.out.print("ctc:-");
    int ctc = sc.nextInt();
    System.out.print("mincg:-");
    double mincg = sc.nextFloat();


    nr.put(cname, role);
    nl.put(cname, ctc);
    nc.put(cname, (float) mincg);

    arrc.add(nr);
    arrc.add(nl);
    arrc.add(nc);

   
}

public void choosec(company c)
{
    
        System.out.println("1). "+ arrc.get(0).keySet()); // wants to print out the key **cname** here but it shows an error on **arrc**.
    

}
1 Answers

If you declare a variable inside of a method, that variable will only be accesible inside of that method while it is running. Declaring a variable outside of the method will make it accesible anywhere inside the class, meaning it is available anywhere as opposed to just the method.

// declare arrc as a variable outside of addc()
public ArrayList<Hashtable> arrc;

public void addc() {
  // assign a value to arrc as it is null
  arrc  = new ArrayList<Hashtable>();
  Hashtable<String, String> nr = new Hashtable<String, String>();
  Hashtable<String, Float> nc = new Hashtable<String, Float>();
  Hashtable<String, Integer> nl = new Hashtable<String, Integer>();
  Scanner sc = new Scanner(System.in);
  System.out.print("name:-");
  String cname = sc.nextLine();
  System.out.print("role:-");
  String role = sc.nextLine();
  System.out.print("ctc:-");
  int ctc = sc.nextInt();
  System.out.print("mincg:-");
  double mincg = sc.nextFloat();

  nr.put(cname, role);
  nl.put(cname, ctc);
  nc.put(cname, (float) mincg);

  arrc.add(nr);
  arrc.add(nl);
  arrc.add(nc);
}

public void choosec() {
  // arrc is now a variable as it was declared in the class rather than the method
  System.out.println("1). "+ arrc.get(0).keySet()); 
}
Related