Hugh Notman
Hugh Notman

Reputation: 31

Method to print through an arraylist not working right

Okay, I'm a newbie and I need some advice about organization in my code. I've been getting an error that says my arraylist cannot resolved.

What I'm doing is I'm extending an abstract class (I don't know if thats relevant) and I've created an array list in my main and filled it with things and then I've got my method to print out the contents of that array list.

If anyone can help me, please do. Thanks

Here's my code:

public static void main(String[] args) {
        ArrayList <String> Strings = new ArrayList <String>(); 
        Strings.add("Hi");
        Strings.add("How are you");
        Strings.add("Huh");

    }


    public void showFirstString(){ 
        for (int i = 0; i < Strings.size(); i++){
            System.out.println(Strings(i));
        }
    }

Upvotes: 0

Views: 1369

Answers (7)

Alex Sartan
Alex Sartan

Reputation: 195

First of all, as others have pointed out, you will need to use the Strings.get(i) method to access the value stored inside a given list element.

Secondly, as Matthias explains, the variable Strings is out of scope and therefore cannot be accessed from the showFirstString() method.

Beyond that, the problem is that your main() method, which is static, cannot interact with the instance method showFirstString() and vice versa.

Static methods live at the class level and do not require an instance of that class to be created. For example:

String.valueOf(1);

Instance methods on the other hand, as the name implies, require an instance of that class to be created before they can be called. In other words, they are called on the object (instance of the class) rather than the class itself.

String greeting = "hi there";
greeting.toUpperCase();

This provides further details: Java: when to use static methods

Without knowing your specific situation, you have two options...

Make both your Strings list as static (class level) field and showFirstString() method static.

public class ListPrinterApp {
  static ArrayList<String> Strings = new ArrayList <String>();

  public static void main(String[] args) {
    Strings.add("Hi");
    Strings.add("How are you");
    Strings.add("Huh");

    showFirstString();
  }

  static void showFirstString(){
    for (int i = 0; i < Strings.size(); i++){
      System.out.println(Strings.get(i));
    }
  }
}

Move code that deals with the list into a separate class, which is then called from your application's static main method. This is likely a better option.

public class ListPrinter {
  ArrayList<String> Strings = new ArrayList<String>();

  public ListPrinter() {
    Strings.add("Hi");
    Strings.add("How are you");
    Strings.add("Huh");
  }

  public void showFirstString() {
    for (int i = 0; i < Strings.size(); i++) {
      System.out.println(Strings.get(i));
    }
  }
}

public class ListPrinterApp {

  public static void main(String[] args) {
    ListPrinter printer = new ListPrinter();
    printer.showFirstString();
  }
}

(I put the the Strings.add() calls into the constructor of ListPrinter as an example. Presumably, you would not want to hardcode those values, in which case you should add an add() method to your ListPrinter class through which you can populate the list.)

A few additional points not directly related to your question:

  • Take a look at the naming conventions for variables in Java. Specifically:

    If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word.

  • Consider using the interface List instead of the concrete implementation of ArrayList when declaring your variable (left side of the equals sign). More info here.

Upvotes: 0

JanLeeYu
JanLeeYu

Reputation: 1001

Please avoid using the word String as a variable name because java already used it as a keyword. Just replace it with another name. Here is what you should do because you are using ArrayList:

public static void main(String[] args) {
        ArrayList <String> list= new ArrayList <String>(); 
        list.add("Hi");
        list.add("How are you");
        list.add("Huh");
        showFirstString(list);
}
public static void showFirstString(ArrayList list){ 
    for (int i = 0; i < list.size(); i++){
            System.out.println(list.get(i));
    }
}

And make sure to import the ArrayList library. read more about its docu here

Upvotes: 3

Matt
Matt

Reputation: 1484

There are answers that address what OP should do to improve but I feel the important part in his question my arraylist cannot resolved. is not discussed. My answer adds to that part.

When compilers complain XXX cannot be resolved, it means that the compiler is encountering the variable's name for the first time and has no idea of what the stuff with that name is. In your case, the compiler does not know what is Strings in showFirstString(), and because it does not know what is Strings, it stops compiling and complains to you instead of keep going with knowing nothing about it, which could potentially be dangerous.

The reason the compiler could not know what was Strings in showFirstString() is known as the scope of variables. Basically, there are lots of blocks in Java as in:

    public void myMethod() 
    { /* method body block is here* }

or even like,

    public class myClass
    {
            /* here starts the class body */

            public static void myMethod() 
            { /* method body block is here* }
    }

And the thing is that the variables are known only within a block where it's declared. So for example, if your codes looks like this:

    public class myClass
    {
            int foo;    // it is known to everywhere within this class block

            public static void myMethod() 
            {
                // boo is known only within this method
                int boo = foo + 1;    // fine, it knows what foo is

            }

            public static void myMethod2() 
            {
                // bar is known only within this method
                int bar = boo + 1;    // cause errors: it does not know what boo is

            }
    }

Now you should understand why your programme was not able to know what is Strings. But passing around data within your codes is a common stuff that is often required to do. To achieve this, we pass parameters to methods. A parameter is a data specified within () that follows the name of the method.

For example:

    public class myClass
    {
            int foo;    // it is known to everywhere within this class block

            public static void myMethod() 
            {
                // boo is known only within this method
                int boo = foo + 1;    // fine, it knows what foo is
                myMethod2(boo);        // value of boo is passed to myMethod2
            }

            public static void myMethod2(int k)    // value of k will be boo
            {
                // bar is known only within this method
                int bar = k + 1;    // cause errors: it does not know what boo is

            }
    }

With parameters like above, you can use boo in myMethod2(). The final thing is that with the codes above, your codes will compile but will do nothing when you run it, because you did not start any of the methods. When a programme runs, it looks for the main method and any other methods that you want to invoke should be called in methods, or by other methods that are in main.

    public class myClass
    {
            int foo;    // it is known to everywhere within this class block

            public static void main(String[] args) 
            {
                // start myMethod
                myMethod();
            }

            public static void myMethod() 
            {
                // boo is known only within this method
                int boo = foo + 1;    // fine, it knows what foo is
                myMethod2(boo);        // value of boo is passed to myMethod2
            }

            public static void myMethod2(int k)    // value of k will be boo
            {
                // bar is known only within this method
                int bar = k + 1;    // cause errors: it does not know what boo is

            }
    }

I hope you get the idea. Also note that to get the items in an ArrayList, you need to use ArrayList.get(int index), as others noted.

Upvotes: 0

kui.z
kui.z

Reputation: 74

First of all, your naming convention is not very good. Second,List collection circular elements is list.get(index),is not list(index)

Upvotes: 0

Imesha Sudasingha
Imesha Sudasingha

Reputation: 3570

If you want to get elements from an array list, you have to use list.get(index) method as follows. It's because you cannot access elements as in arrays when it comes to array lists.

public void showFirstString(){ 
    for (int i = 0; i < Strings.size(); i++){
        System.out.println(Strings.get(i));
    }
}

Upvotes: 0

Natecat
Natecat

Reputation: 2172

You never call showFirstString() and in addition, Strings isn't a global variable, so you will get an error on the first line of that method. To fix this, put showFirstString(Strings) in your main method and change your method signature to public void showFirstString(Arraylist Strings). In addition, arraylists are accessed using list.get(index) so change the line in your loop to System.out.println(Strings.get(i));

Upvotes: 0

Logan
Logan

Reputation: 946

You need to use the .get(index) method, where index is the element you want to access. For example:

System.out.println(Strings.get(i));

You would also want to call that method in main.

Upvotes: 0

Related Questions