p32929 p32929 - 16 days ago 4
Java Question

calling an object's method defined in an ArrayList Java

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

}

}


Any solution? thanks in advance...
(StackOverflow is not letting me post this question cause it has less words than codes. So...........................................................................................................................................................................................................................................................................)

Answer
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.

Comments