p32929 p32929 - 1 year ago 47
Java Question

Calling an object's method defined in List

I'm trying to call addContact method from main method using ArrayList called phone but its not working.

Here's the code:

import java.util.ArrayList;
import java.util.Scanner;

class A {

String name;
int num;
Scanner sc = new Scanner(System.in);

public A(String name, int num) {
this.name= name;
this.num= num;
}

public void addContact() {
sc.nextLine();
System.out.println("Enter name:");
name = sc.nextLine();
System.out.println("Enter number:");
num = sc.nextInt();
}
}

public class Main {
static void menu() {
System.out.println("1. add");
System.out.println("2. break");
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

ArrayList <A> phone;

while(true) {
menu();
int c = sc.nextInt();
if(c==1) {
phone.add().addContact();
//I'm trying to call addContact()
} else if(c==2) {
break;
}
}
}
}


Why I can't just call
phone.add().addContact()
?

Answer Source
import java.util.ArrayList;
import java.util.Scanner;

class A {
String name;
int num;
Scanner sc = new Scanner(System.in);

public A(String name, int num) {
    this.name= name;
    this.num= num;
}

}

public class Main {
static void menu()  
{
    System.out.println("1. add");
    System.out.println("2. break");

}

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    ArrayList <A> phone = new Arraylist<A>();

    while(true)
    {
        menu();
        int c = sc.nextInt();
        if(c==1)
        {
            System.out.println("Enter name:");
            String name = sc.nextLine();
            System.out.println("Enter number:");
            int num = sc.nextInt(); 
            phone.add(new A(name,num));

        }
        else if(c==2)
        {
            break;
        }
    }

}

}

Just removed you addContact and placed in in the while. Now i create a new Instance of A and add it to the list. This should work now. Please post more precise Questions in the future.