Method to print through an arraylist not working right - java

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));
}
}

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

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.

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));

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));
}
}

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

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.

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.

Related

How to define a method with Integer parameter (path placeholding)?

Preface
I'd like to saying two things:
I don't know how to phrase this question in a few words. So I can't find what I'm looking for when searching (on stackoverflow). Essentially, I apologize if this is a duplicate.
I've only been programming Java consistently for a month or so. So I apologize if I asked an obvious question.
Question
I would like to have a method with a parameter that holds (path to) an integer.
How is such a method implemented in Java code?
Restrictions
The parameter should be generic.
So, when there are multiple of that integer variables, the correct one can be used as argument to the method, when it is called (at runtime).
My Idea as Pseudo-Code
Here's the idea of what I want (in pseudo-code). The idea basically consist of 3 parts:
the method with parameter
the variables holding integer values
the calls of the method with concrete values
(A) Method
.
Following is the definition of my method named hey with generic parameter named pathToAnyInteger of type genericPathToInt:
class main {
method hey(genericPathToInt pathToAnyInteger) {
System.out.println(pathToAnyInteger);
}
}
(B) Multiple Integer Variables
Following are the multiple integer variables (e.g. A and B; each holding an integer):
class A {
myInt = 2;
}
class B {
myInt = 8;
}
(C) Method-calls at runtime
Following is my main-method that gets executed when the program runs. So at runtime the (1) previously defined method hey is called using (2) each of the variables that are holding the different integer values:
class declare {
main() {
hey("hey " + A.myInt);
hey("hey " + B.myInt);
}
}
Expected output
//output
hey 2
hey 8
Personal Remark
Again, sorry if this is a duplicate, and sorry if this is a stupid question. If you need further clarification, I'd be willing to help. Any help is appreciated. And hey, if you're going to be unkind (mostly insults, but implied tone too) in your answer, don't answer, even if you have the solution. Your help isn't wanted. Thanks! :)
Java (since Java 8) contains elements of functional programing which allows for something similiar to what you are looking for. Your hey method could look like this:
void hey(Supplier<Integer> integerSupplier) {
System.out.printl("Hey" + integerSupplier.get());
}
This method declares a parameter that can be "a method call that will return an Integer".
You can call this method and pass it a so called lambda expression, like this:
hey(() -> myObject.getInt());
Or, in some cases, you can use a so called method referrence like :
Hey(myObject::getInt)
In this case both would mean "call the hey method and when it needs an integer, call getInt to retrieve it". The lambda expression would also allow you to reference a field directly, but having fields exposed is considered a bad practise.
If i understood your question correctly, you need to use inheritance to achive what you are looking for.
let's start with creating a hierarchy:
class SuperInteger {
int val;
//additional attributes that you would need.
public SuperInteger(int val) {
this.val = val;
}
public void printValue() {
System.out.println("The Value is :"+this.value);
}
}
class SubIntA extends SuperInteger {
//this inherits "val" and you can add additional unique attributes/behavior to it
public SubIntA(int val) {
super(val);
}
#override
public void printValue() {
System.out.println("A Value is :"+this.value);
}
}
class SubIntB extends SuperInteger {
//this inherits "val" and you can add additional unique attributes/behavior to it
public SubIntB(int val) {
super(val);
}
#override
public void printValue() {
System.out.println("B Value is :"+this.value);
}
}
Now you method Signature can be accepting and parameter of type SuperInteger and while calling the method, you can be passing SubIntA/SuperInteger/SubIntB because Java Implicitly Upcasts for you.
so:
public void testMethod(SuperInteger abc) {
a.val = 3;
a.printValue();
}
can be called from main using:
public static void main(String args[]){
testMethod(new SubIntA(0));
testMethod(new SubIntB(1));
testMethod(new SuperInteger(2));
}
getting an Output like:
A Value is :3
B Value is :3
The Value is :3
Integers in Java are primitive types, which are passed by value. So you don't really pass the "path" to the integer, you pass the actual value. Objects, on the other hand, are passed by reference.
Your pseudo-code would work in Java with a few modifications. The code assumes all classes are in the same package, otherwise you would need to make everything public (or another access modifier depending on the use case).
// First letter of a class name should be uppercase
class MainClass {
// the method takes one parameter of type integer, who we will call inputInteger
// (method-scoped only)
static void hey(int inputInteger) {
System.out.println("hey " + inputInteger);
}
}
class A {
// instance variable
int myInt = 2;
}
class B {
// instance variable
int myInt = 8;
}
class Declare {
public static void main() {
// Instantiate instances of A and B classes
A aObject = new A();
B bObject = new B();
// call the static method
MainClass.hey(aObject.myInt);
MainClass.hey(bObject.myInt);
}
}
//output
hey 2
hey 8
This code first defines the class MainClass, which contains your method hey. I made the method static in order to be able to just call it as MainClass.hey(). If it was not static, you would need to instantiate a MainClass object in the Declare class and then call the method on that object. For example:
...
MainClass mainClassObject = new MainClass();
mainClassObject.hey(aObject.myInt);
...

chain functions

I have two classes
Class1:
public class Class1 {
public static void main(String[] args) {
Class2 classObject = new Class2();
classObject.add(2, 3);
classObject.print();
}
}
And Class2:
public class Class2 {
public int add(int a, int b) {
int n = a + b;
return n;
}
public void print() {
System.out.println(add(2,3));
}
}
I want to use the print method to print out what is being returned in the add method.The add method gets its information from the classObject as seen in Class1.
I know there are different ways to go about doing this, but i'm quite sure that there is a way to do it the way i want to, i just can't figure out how.
In Class2 in the print method when i called the add method i put arbitrary numbers there. What i want to do is somehow bring the numbers from from classObject.add(int,int) and print the the returning integer n.
If what you want to demonstrate is showing an object with state, maybe you mean something like this:
public class Class2 {
int n;
public void add(int a, int b) {
n = a + b;
return n;
}
public void print() {
System.out.println(n);
}
}
This way Object1 never knows the internals of Object2, and it's really a pretty good abstraction.
You can simply change the signature of the print method as below. Method like print are processing methods which needs the input which you can pass as method arguments.
public void print( int a) {
System.out.println(a);
}
Now you need to make a simple call like below.
classObject.print(classObject.add(2,3));
You should not be calling add method from inside the print method. As per the name it seams print is a general purpose method. You should pass input as method arguments and it should be responsible to print the input.
If you wish your print method to just print addition then You can pass the two numbers as input parameters to method print and also change the method name as below. You need to call the method add from inside the print (modified version). In this case you should hide the method add and make it private.
public void printTheAddition(int n, int m){
System.out.println(add(n,m));
}
In this case just call printTheAddition method with two input arguments.

Determining static method with a global LinkedList variable

I'm having a really hard time deciding when to make my methods static or not. I was told to make a global LinkedList variable:
public static LinkedList list = new LinkedList();
Now, I wrote a method called read() to read in words from a text file. Then I wrote another method preprocessWord(word) to check if these words begin with a constant to change them to lower-case. If they have these conditions, then I add them to the LinkedList list:
public void read(){
....
while((nextLine = inFile.readLine())!= null){
tokens = nextLine.trim().split("\\s+");
for(int i = 0; i < tokens.length; i++){
word = tokens[i];
word = preprocessWord(word);
list.append(word);}
}
}
...
}//read
However, when I try to call read() from the main method;
public static void main(String[] args) {
read();
System.out.println(list);
}//main
The error is I cannot make a static reference to a non-static method read(), so I tried to change my methods read() and preprocessedWord() to static methods, but then words aren't updated in preprocessedWord() like they are suppose to. I really don't get where to use static and to where not, could someone please explain where I'm going wrong in my thinking?
in laymen's terms, when you define a method non-static, it can only be invoked on an instance of this class. In your case however you would need to run something like this
public static void main(String[] args) {
new YourClassName().read();
System.out.println(list);
}
Doing so however, would mean that in your read method, you would have to access the static list as
YourClassName.list.append(word)
The other approach would be to make read static as well, so in this case your method signature should be
public static void read()
Cuz your read method is not static. Dont use satic field unless you need to eg. for sharing reference between all objects of the same class. Make your list non-static or even local and pass as argument to subsequent methods calls

Can a method be called by an object inside of the same class?

What I'm trying to understand is why I'm receiving an error when I try to call a method by an object whilst residing in the same class.
My syntax looks correct. I understand the local variables inside of the method are uninitialized, and wanted to see if the compiler would be able to pick this up.
My issue however is, I receive a stupid error from the compiler, when I try to invoke the method on an object of the same class, within the class, as such.
class Wool {
public static void main (String [] args) {
int add() {
int x;
int a = x + 3;
return a;
}
Wool w = new Wool ();
System.out.print("something here " + w.add());
} // end main
} // end class
There error that I receive from the compiler is:
c Wool.java
Wool.java:5: ';' expected
int add() {
^
I can do the above fine, if the object of type Wool is instantiated in another class, and the object has no issue in invoking the method, to show me the compilation error that the local variables need a value in that method.
I just don't understand why I can't do it in one class. And if it is possible, please could you educate me.
Help would be immensely grateful.
Thank you.
You can't define a method inside another one. You must declare the add method outside of the main method.
Change your code to
class Wool {
int add() {
int x = 0; // give a value to avoid another error
int a = x + 3;
return a;
}
public static void main (String [] args) {
Wool w = new Wool ();
System.out.print("something here " + w.add());
} // end main
} // end class
You are declaring a method inside main(). You can not do that.
Methods must be declared inside classes, not inside other methods.
Because add() is not defined as a class method, but you define it as "local" method within main, which is not allowed in java. You must change it to
class Woo{
void add(){
....
}
public static void main(String[] args){
new Woo().add();
...
}
}
You have a method directly inside a method:
main(){
add() {
}
}
that's illegal in java.
Put your method add in the body of your class but not in the body of your method main. Or better : leave Java alone :)
You can't declare a method inside a method.
Try this:
public static void main (String[] arts) {
//
}
int add() {
//
}

overriding a variable in java

public class Foo {
public int a = 3;
public void addFive(){
a += 5; System.out.print("f ");
}
}
public class Bar extends Foo {
public int a = 8;
public void addFive(){
this.a += 5;
System.out.print("b " );
}
}
public class Test {
public static void main(String args[]){
Foo f = new Bar();
f.addFive();
System.out.println(f.a);
}
}
I am getting output b 3 .why it is not giving b13 as output.Can anyone please explain.
Assuming class Foo is declared as below
class Foo
{
public int a = 3;
public void addFive()
{
a += 5;
System.out.print("f ");
}
}
Variables have no concept of overriding. They are just masked.
It is printing 3 because, when you use a superclass reference to access a variable, it accesses the variable declared in superclass only. Remember that superclass doesn't know anything about subclass.
class Foo {
public void addFive() {
a += 5; System.out.print("f ");
}
}
you don't have 'a' variable defined, so this example doesn't even compile.
correct code:
class Foo {
public int a;
public void addFive() {
a += 5; System.out.print("f ");
}
}
and see link https://stackoverflow.com/a/2464254/1025312
I assume that you meant to declare an integer field a in class Foo.
The answer to your question has to do with concepts of 'overriding' and 'hiding', as others have pointed out. Another way to explain it is that for member variables, there is no such thing as 'dynamic dispatch'. What that means is that, if you access a member of a certain object, the system checks at run time which member you mean, by looking at the class hierarchy.
So, when calling the method f.addFive, at run time, the system will see that your object is actually a Bar and not a Foo, and so take the addFive function that you defined in the Bar class.
That does not happen for member variables: you access f.a in your print statement, and at compile time it is decided that right there you want to access the field a declared in class Foo there -- and so, that is what will happen at run time.
Now, the reason that there is no dynamic dispatch for member variable access is performance: it would be very expensive to go through the whole 'see what object this really is' logic every time you just want to add some value to a member variable.
Declaring public int a = 8 in Foo class instead of Bar class it should work... printing B 3.
But I suppose you are talking about a question included in the Java certification exam, so you have to correct the code of the Foo class adding public int a = 3.
You cannot override a variable in Java, but declaring in as public (or protected) in the super-class you can use it also in all inherited classes.
In this case the right output is B 13 because in the test class you are using a Bar object as a Foo object, so the value of a is 3 and not 8.

Categories