i can't undrestand why it displays null? - java

//Main :
package DevAyo;
import java.util.Scanner;
public class Main {
private static Scanner scanner =new Scanner(System.in);
private static Album Alb =new Album("Kamikaze");
public static void main(String[] args) {
boolean quit = true;
while (quit){
System.out.println("Choose actions : ");
System.out.println("\t\t 1.Add new Songs to Album :");
System.out.println("\t\t 2.printSongs");
System.out.println("\t\t 3.Quit");
System.out.println("choose Action : ");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice){
case 1:
AddSong();
break;
case 2:
Alb.printSongs();
break;
case 3:
quit=false;
break;
}
}
}
public static void AddSong(){
// System.out.println("Insert Album Name: ");
// String albumName =scanner.nextLine();
System.out.println("Pleas Enter Number of Songs :");
int Number = scanner.nextInt();
for (int i=0;i<Number;i++){
System.out.println("Enter Song Name "+(i+1)+": ");
String name=scanner.nextLine();
scanner.nextLine();
System.out.println("Enter Singer of Song "+(i+1)+": ");
String SingerName =scanner.nextLine();
System.out.println("Enter Song "+(i+1)+" released Day: ");
String ReleasedDay = scanner.nextLine();
System.out.println("Enter Length of the Song"+(i+1)+": ");
int SongLength=scanner.nextInt();
Songs song = Songs.creatSong(name,SingerName,ReleasedDay,SongLength);
if(Alb.addSOngs(song))
System.out.println("Songs added ! ");
else
System.out.println("Error ! ");
}
}`enter code here`
}
//Album Class
package DevAyo;
import java.util.ArrayList;
import java.util.Scanner;
public class Album {
public String AlbumName;
private static Scanner scanner = new Scanner(System.in);
ArrayList<Songs> ListofSongs;
public Album(String albumName) {
AlbumName = albumName;
this.ListofSongs=new ArrayList<Songs>();
}
public boolean addSOngs(Songs song){
if(findSong(song.getSongName())>=0){
System.out.println("Songs aLready Exisit ! ");
return false;
}
ListofSongs.add(song);
return true;
}
private int findSong(String songName){
for(int i=0; i<ListofSongs.size();i++){
Songs song = ListofSongs.get(i);
if(song.getSongName().equals(songName)){
return i;
}
}
return -1;
}
public void printSongs(){
for(int i=0;i<this.ListofSongs.size();i++){
System.out.println("Song Name: "+ this.ListofSongs.get(i).getSongName()+"\n"
+"Singer: "+this.ListofSongs.get(i).getSongSinger()+"\n"+"Song Released Day: "+this.ListofSongs.get(i).getSongDay()+
"\n"+"Song Length: "+this.ListofSongs.get(i).songLength+" min");
}
}
}
//Songs Class
package DevAyo;
public class Songs {
public static String songName;
public static String songSinger;
public static String songDay;
public static int songLength;
public Songs(String songName, String songSinger, String songDay, int songLength) {
this.songName = songName;
this.songSinger = songSinger;
this.songDay = songDay;
this.songLength = songLength;
}
public String getSongName() {
return this.songName;
}
public String getSongSinger() {
return this.songSinger;
}
public String getSongDay() {
return this.songDay;
}
public int getSongLength() {
return this.songLength;
}
public static Songs creatSong(String name, String singerName, String releasedDay, int songLength){
return new Songs(songName,songSinger,songDay,songLength);
}
}
i just tried so many was i can't undrestand why it displlays null , i 've created the constructor in both classes and still dosen't seem to work, honestly i've searched the internet about the problem but it's says that i should add constructor i've add them but nothing happpen anyway hope the code is clear , hope you guys can help thanks .

After a Scanner.nextInt(); leaves an empty line so the next time you call Scanner.nextLine(); it will give you that empty line.
If you want to avoid this, you could do one of this 2 options:
Parse
Always use Scanner.nextLine() and cast to the type of variable you want.
Example: int a = Integer.parseInt(scanner.nextLine());
Read that empty line
always you use the nextInt() immediately call nextLine()
Example:
int a = scanner.nextInt();
scanner.nextLine()

Related

Error with Checking availability of Getters and Setters in Java

this is my first time posting on StackOverflow so I am still getting used to the format. I apologize in advance. Over here, I have 2 classes FruitBasket and FruitBasketUtility. I've included the getters and setters method in the Fruitbasket.Java. Everything compiled fine but I got an error:
Fail 1 -- test11addToBasketMethodToAddOneFruitBasketObject::
Check the availability (or) the signature of addToBasket/getFruitBasketList in the FruitBasketUtility class or Setters and Getters in FruitBasket class
Main.Java
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
//For reading input from user
Scanner in = new Scanner(System.in);
//Creating object of FruitBasketUtility
FruitBasketUtility fruitBasketUtility = new FruitBasketUtility();
int choice;
do{
//Displaying the menu
System.out.println("Select an option:");
System.out.println("1. Add Fruit to Basket");
System.out.println("2. Calculate Bill");
System.out.println("3.Exit");
//Reading the choice
choice = in.nextInt();
in.nextLine();
switch(choice){
case 1:
//Reading fruit details from user
System.out.println("Enter the fruit name");
String fruitName = in.next();
in.nextLine();
System.out.println("Enter weight in Kgs");
int weightInKgs = in.nextInt();
in.nextLine();
System.out.println("Enter price per Kg");
int pricePerKg = in.nextInt();
in.nextLine();
FruitBasket fruit = new FruitBasket(fruitName, weightInKgs, pricePerKg);
//Adding fruit to basket
fruitBasketUtility.addToBasket(fruit);
break;
case 2:
//Calculating and showing the bill
ArrayList<FruitBasket> basket = fruitBasketUtility.getFruitBasketList();
if(basket.size() > 0){
System.out.println("The estimated bill amount is Rs " + fruitBasketUtility.calculateBill((basket.stream())));
}
else{
System.out.println("Your basket is empty. Please add fruits.");
}
break;
case 3:
System.out.println("Thank you for using the application.");
break;
default:
System.out.println("Invalid option. Please try again.");
break;
}
}while(choice != 3);
}
}
FruitBasket.Java
public class FruitBasket {
//Member variables
String fruitName;
int weightInKgs;
int pricePerKg;
//Getters and setters
public void setFruitName(String fruitName){
this.fruitName =fruitName;
}
public void setWeightInKgs(int weightInKgs){
this.weightInKgs =weightInKgs;
}
public void setPricePerKg(int pricePerKg){
this.pricePerKg =pricePerKg;
}
public String getFruitName(){
return fruitName;
}
public int getWeightInKgs(){
return weightInKgs;
}
public int getPricePerKg(){
return pricePerKg;
}
//An empty constructor
public FruitBasket(){
fruitName = "";
weightInKgs = 0;
pricePerKg = 0;
}
//Three argument constructor
public FruitBasket(String fruitName, int weightInKgs, int pricePerKg){
this.fruitName = fruitName;
this.weightInKgs = weightInKgs;
this.pricePerKg = pricePerKg;
}
}
FruitBasketUtility.Java
import java.util.ArrayList;
import java.util.stream.Stream;
public class FruitBasketUtility {
//Member variables
ArrayList<FruitBasket> fruitBasketList;
//Getters and setters
public void setFruitBasketList(ArrayList<FruitBasket> fruitBasketList){
this.fruitBasketList = fruitBasketList;
}
public ArrayList<FruitBasket> getFruitBasketList(){
return fruitBasketList;
}
//Constructor
public FruitBasketUtility(){
fruitBasketList = new ArrayList<>();
}
//Add to basket
public void addToBasket(FruitBasket fObj){
fruitBasketList.add(fObj);
}
//Calculte the bill using stream of FruitBasket
public int calculateBill(Stream<FruitBasket> fruitBasketStream){
return fruitBasketStream.mapToInt(x -> x.getPricePerKg() * x.getWeightInKgs()).sum();
}
}

create arrayList including attribute from superclass and subclass

please help me
I have to create a 4 function using switch method. And I have a problem with function 3(show list of video and song)
For more details, I suppose I should create a class likes MultimediaManagerment. After that, I create an Arraylist in it and add all the attributes to this for printing the song like:
listOfMultimedia.add(songlist)
listOfMultimedia.add(videoList)
But the problem is the attribute "name" &"duration" are in the superclass Mutimedia while the attribute "singer" is in subclass Song. For that reason, from class MultimediaManagerment I can not add all the attribute to my arrayList.
Any ideas guys?
import java.util.*;
abstract class Multimedia{
String name;
double duration;
Scanner sc= new Scanner(System.in);
Multimedia(){
name=null;
duration=0;
};
void createMultimedia(){
System.out.print("\nEnter name: ");
name = sc.nextLine();
System.out.print("\nEnter duration: ");
duration=sc.nextDouble();
}
};
//Function Create Video
class Video extends Multimedia{
Video(){};
public void createVideo(){
System.out.println("----Enter video information----");
super.createMultimedia();
}
public String toString() {
return name + " " + duration ;
}
}
//Function Create Song
class Song extends Multimedia{
String singer;
Song(){
singer=null;
}
public void createSong(){
System.out.println("----Enter song information----");
System.out.print("Enter singer: " );
singer =sc.nextLine();
super.createMultimedia();
}
public String toString() {
return singer + " " + name + " " + duration ;
}
}
//Function show data
class MultimediaManagement extends Multimedia{
List<Multimedia> listOfMultimedia = new ArrayList<Multimedia>();
MultimediaManagement(){
listOfMultimedia=null;
}
void addMultimedia(Multimedia multimedia){
Multimedia ob = new Song(name, duration, singer); //ERROR
}
}
public class Assign801 {
public static void menu(){
Scanner sc= new Scanner(System.in);
int func;
Video video = new Video();
Song song = new Song();
do
{
System.out.println("Please choose function:\n1. Add a new Video\n2. Add a new Song\n3. Show all multimedia\n4.Exit");
func = sc.nextInt();
} while (func < 0 || func >4);
switch (func) {
case 1:
video.createVideo();
menu();
break;
case 2:
song.createSong();
menu();
break;
case 3: // show list of video & song
case 4: break;
}
}
public static void main(String[] args) {
menu();
}
}

How to print elements from linked list

I've got a linked list class with a controller class and a test class which is the main class. The code runs and accepts user input, however when I click to display all team members entered it is empty.
Where have I gone wrong? How do I get all the team members to entered to be displayed?
public class TeamMember {
private LinkedList<TeamMember> teamMembers;
public LinkedList<TeamMember> getTeamMembers() {
return teamMembers;
}
public void setTeamMembers(LinkedList<TeamMember> teamMembers) {
this.teamMembers = teamMembers;
}
private Scanner scan = new Scanner(System.in);
public TeamMember(String name) {
this.teamMembers = new LinkedList<>();
}
}
package com.view;
import com.controller.TeamMemberController;
import com.model.TeamMember;
import java.util.InputMismatchException;
import java.util.Scanner;
public class TeamMemberTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
TeamMemberController teamMemberController = new TeamMemberController();
int userInput;
do {
System.out.println("1. Add a new team member");
System.out.println("2. Find and display a team member");
System.out.println("3. Remove a team member");
System.out.println("4. Display all team members");
System.out.println("0. Quit");
//Validate user input
try {
userInput = scan.nextInt();
scan.nextLine();
} catch (InputMismatchException e) {
//if anything other than an integer is entered.
//The "scan.nextLine" fix above will not be triggered.
//It has to appear in the catch as well.
scan.nextLine();
userInput = 5;
}
switch (userInput) {
case 0:
userInput = teamMemberController.quit();
break;
case 1:
System.out.println("**********\n" + teamMemberController.addTeamMember());
break;
case 2:
System.out.println("**********\n" + teamMemberController.findTeamMember());
break;
case 3:
System.out.println("**********\n" + teamMemberController.removeTeamMember());
break;
case 4:
teamMemberController.displayAllTeamMembers();
break;
default:
System.out.println("*** Please Make another selection ***");
System.out.println("");
break;
}
} while (userInput != 0);
}
}
package com.controller;
import com.model.TeamMember;
import java.util.LinkedList;
import java.util.Scanner;
public class TeamMemberController {
private TeamMember teamMember;
public TeamMemberController() {
String name = null;
this.teamMember = new TeamMember(name);
}
Scanner scan = new Scanner(System.in);
public String addTeamMember() {
System.out.println("To go back press 0");
String name = null;
boolean keepLooping = true;
//get team member linked list
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
//user enters name
while (keepLooping) {
System.out.println("Enter team member name");
//project names MUST be UNIQUE
name = scan.nextLine();
if (name.equals("0")) {
return "team member not added";
}
if (!this.checkIfTeamMemberNameExists(name)) {
keepLooping = false;
} else {
System.out.println("Team Member already exists");
System.out.println("");
}
}
//add team member to collection
teamMembers.add(new TeamMember(name));
teamMember.setTeamMembers(teamMembers);
//returns true when a team member has been successfully added
return "Name: " + name + "\n--Added--";
}
public String findTeamMember() {
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
//if the company has no team members no need to continue
if (teamMembers.isEmpty()) {
return "Sorry no team members";
}
//get here company must have team members
System.out.println("Enter team member name");
String name = scan.nextLine();
for (TeamMember t : teamMembers) {
if (t.getTeamMembers().equals(name)) {
return "Name: " + t.getTeamMembers();
}
}
return "Team member not found";
}
public String removeTeamMember() {
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
System.out.println("Enter name of team member to remove");
System.out.println("Enter 0 to exit");
String projectToRemove = scan.nextLine();
boolean removed = false;
if (projectToRemove.equals("0")) {
return "No project removed";
}
//check existing team member names against the user input one
for (TeamMember t : teamMembers) {
if (t.getTeamMembers().equals(removeTeamMember())) {
teamMembers.remove(t);
removed = true;
}
}
if (removed) {
teamMember.setTeamMembers(teamMembers);
} else
return "No team member found";
return removeTeamMember() + " has successfully been removed";
}
public void displayAllTeamMembers() {
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
if (teamMembers.isEmpty()) {
System.out.println("Company has not added any team members");
return;
}
System.out.format(" Name%n");
for (TeamMember t : teamMembers) {
System.out.println(t.getTeamMembers() + " ");
}
}
public int quit() {
System.out.println("Are you sure you want to quit? y/n");
String userResponse = scan.nextLine();
boolean loop = true;
while (loop) {
if (userResponse.equalsIgnoreCase("y")) {
System.out.println("Program ending");
return 0;
} else if (userResponse.equalsIgnoreCase("n"))
return 5;
}
return 0;
}
public boolean checkIfTeamMemberNameExists(String name) {
//get team member linked list
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
//if a team member with the same name already exists return true
if (!teamMembers.isEmpty()) {
for (TeamMember t : teamMembers) {
if (t.getTeamMembers().equals(name)) {
return true;
}
}
}
return false;
}
}
This is the output I'm getting. How do I get it to print the names entered?
[1]: https://i.stack.imgur.com/FVhVm.png
The first problem is that TeamMembers don't remember the names you give them. Add a field for the name, and a method to retrieve it:
private String name;
public TeamMember(String name) {
this.name = name;
this.teamMembers = new LinkedList<>();
}
public String getName() {
return name;
}
The second problem is that displayAllTeamMembers does not display the "name" of the team member. There was no way it could have done it because the team members didn't even have a name, but now they do.
public void displayAllTeamMembers() {
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
if (teamMembers.isEmpty()) {
System.out.println("Company has not added any team members");
return;
}
System.out.format(" Name%n");
for (TeamMember t : teamMembers) {
System.out.println(t.getName());
}
}
A third possible problem is that each individual "team member" has a list of team members. That just seems confusing to me and makes me wonder if you have misread the instructions for this exercise.
Below is the minimum code change required to make your code work. But I would suggest to follow design patterns before if you a build a working prod ready system around this code.
public class TeamMember {
private static LinkedList<TeamMember> teamMembers;
public LinkedList<TeamMember> getTeamMembers() {
return teamMembers;
}
public void setTeamMembers(LinkedList<TeamMember> teamMembers) {
teamMembers = teamMembers;
}
private Scanner scan = new Scanner(System.in);
public TeamMember(String name) {
if(teamMembers==null) {
teamMembers = new LinkedList<>();
}
}
}

EDIT (judge harshly): My display() method won't display and I'm not sure why

I recently posted a question in regards to my display() method only displaying certain objects, and was able to correct that with some feedback I received earlier in regards to my toString() method. However, I had to change my idNum to an int, and now my displayMethod() won't display at all. I tried retracing my steps and am unsure what happened.
The object array that is supposed to hold an identification number, a sales amount, and the persons name. However, when I display the array, nothing is displaying. I've tried the for loop, enhanced for loop and tried just a system.out.print invoking the get() methods.
I don't know if it has something to do with my displayDatabase() method, the way I am using my Scanner variable (USER_INPUT) to set the data entered, or something to do with my constructors.
My constructor looks like this:
==================================================
public class Salesperson
{
private String salesName;
private int salesID;
private double annualSales;
public Salesperson(String salesName, int salesIDNum, double yearlySales)
{
this.salesName = salesName;
salesID = salesIDNum;
annualSales = yearlySales;
}
public String getSalesName()
{
return salesName;
}
public void setSalesName(String salesName)
{
this.salesName = salesName;
}
public double getSalesID()
{
return salesID;
}
public void setSalesID(int salesIDNum)
{
salesID = salesIDNum;
}
public double getAnnualSales()
{
return annualSales;
}
public void setAnnualSales(double yearlySales)
{
annualSales = yearlySales;
}
#Override
public String toString()
{
return String.format("%s-%-10s%-10.2f", salesName,
salesID, annualSales);
}
}
And my code for application looks like this:
import java.util.Arrays;
import java.util.Scanner;
public class CreateSalesperson
{
private static final Scanner USER_INPUT = new Scanner(System.in);
private static final int UPPER_SIZE_LIMIT = 20;
private static final int LOWER_SIZE_LIMIT = 0;
private static Salesperson[] salesStaffInDatabase = new
Salesperson[20];
private static int numOfSalesPpl = 0;
private static boolean loop = true;
public static void main(String[] args)
{
String selection;
selection = programMenu();
String response;
while(loop)
switch(selection)
{
case "A":
if(numOfSalesPpl == UPPER_SIZE_LIMIT)
{
System.out.print("Database has reached capacity.");
System.out.print(" Please delete a record before ");
System.out.println("adding to the database.");
}
else
{
addRecord();
}
break;
case "a":
if(numOfSalesPpl == UPPER_SIZE_LIMIT)
{
System.out.print("Database has reached capacity.");
System.out.print(" Please delete a record before ");
System.out.println("adding to the database.");
}
else
{
addRecord();
}
break;
case "C":
if(numOfSalesPpl == LOWER_SIZE_LIMIT)
{
System.out.print("Database is empty. ");
System.out.print("Please add a record.");
}
else
{
changeRecord();
}
break;
case "c":
if(numOfSalesPpl == LOWER_SIZE_LIMIT)
{
System.out.print("Database is empty. ");
System.out.print("Please add a record.");
}
else
{
changeRecord();
}
break;
case "E":
System.out.print("You Are Leaving Database");
loop = false;
break;
case "e":
System.out.print("You Are Leaving Database");
loop = false;
break;
}
}
public static void changeRecord()
{
String idNum;
String salesName;
double salesAmount;
String response;
System.out.print("Enter Sales ID: ");
idNum = USER_INPUT.nextLine();
if(isValidID(idNum))
{
int searchResult = Arrays.binarySearch(salesStaffInDatabase, idNum);
System.out.println(salesStaffInDatabase[searchResult]);
}
else
{
System.out.println("Invalid Sales ID");
}
}
public static boolean isValidID(String idNum)
{
boolean isValid= false;
for(int val = 0;val < numOfSalesPpl && !isValid; ++val)
{
if(salesStaffInDatabase[val].equals(idNum))
{
isValid = true;
}
}
return isValid;
}
public static void addRecord()
{
int idNum;
String salesName;
double salesAmount;
String idNo;
String response;
do
{
System.out.print("Please enter sales ID: ");
idNum = USER_INPUT.nextInt();
idNo = Integer.toString(idNum);
if(idNo.length() != 8)
System.out.println("Sales ID must be 8 digits long: ");
}
while(idNo.length() < 8 || idNo.length() > 8);
System.out.print("Name: ");
salesName = USER_INPUT.nextLine();
USER_INPUT.nextLine();
System.out.print("Sales Amount: ");
salesAmount = Double.parseDouble(USER_INPUT.nextLine());
salesStaffInDatabase[numOfSalesPpl] = new
Salesperson(salesName,idNum,salesAmount);
salesStaffInDatabase[numOfSalesPpl].setSalesName(salesName);
salesStaffInDatabase[numOfSalesPpl].setSalesID(idNum);
salesStaffInDatabase[numOfSalesPpl].setAnnualSales(salesAmount);
System.out.print("Do you want to display database Y/N?: ");
response = USER_INPUT.nextLine();
while(response.equalsIgnoreCase("Y")||response.equalsIgnoreCase("yes"))
{
displayDatabase();
}
}
public static void displayDatabase()
{
for(int val=0;val < numOfSalesPpl; val++)
{
System.out.println(salesStaffInDatabase[val]);
}
}
public static String programMenu()
{
String selection;
do
{
System.out.println("(A)dd a Record");
System.out.println("(C)hange a Record");
System.out.println("(E)xit Database");
System.out.print("Enter selection: ");
selection = USER_INPUT.nextLine();
}
while(!selection.equalsIgnoreCase("a") &&
!selection.equalsIgnoreCase("c")
&& !selection.equalsIgnoreCase("e"));
return selection;
}
}
=================================================================
In Java, whenever you want to display an object as string, you must override the toString() method.
The code that you posted, the Salesperson's toString() method returns only the salesID and anualSales. If you want to display another attribute, you must place it in the toString() method.
If you want to display the first name on the beginning of the output, you can do:
#Override public String toString() {
return String.format("%s - %-10s%-10.2f", salesFirstName, salesID, annualSales);
}
edit the toString()method in Salesperson class :
#Override
public String toString() {
return "Salesperson{" +
"salesFirstName='" + salesFirstName + '\'' +
", salesLastName='" + salesLastName + '\'' +
", salesID='" + salesID + '\'' +
", annualSales=" + String.format("%-10.2f", annualSales)+
'}';
}

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()?
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.
You need to create an instance of your list:
ArrayList<A> phone = new ArrayList<>();
ArrayList <A> phone;
Should be:
ArrayList phone = new ArrayList();
Also, the add() method in this line
phone.add().addContact();
should contain an A object to add to the ArrayList.
you need to return object of A
public A addContact() {
sc.nextLine();
System.out.println("Enter name:");
name = sc.nextLine();
System.out.println("Enter number:");
num = sc.nextInt();
return new A(name,num);
}
and
if(c==1)
{
phone.add(addContact);
}
Your problem starts here:
ArrayList <A> phone;
only declares that list; but doesnt define it. Thus you run into a NullPointerException when you try to run your code.
You need
ArrayList <A> contacts = new ArrayList<>();
instead. I took the freedom to give that variable a reasonable name, too. (this list is about storing contents, it is not storing phones; and it is also not a single phone ... just a list of contact information)
But there is more. You see, you are getting your abstractions wrong. Your Contact class (A is just a terrible name for that class) should not be dealing with a scanner to fetch its data.
Instead, you want to do something like:
class Contact {
private final String name;
private final int number;
Contact(String name, int number) {
this.name = name;
this.number = number;
}
and then, within your main method, you do something like:
boolean loop = true;
while (loop) {
... have user enter a name and a number
if (name.equals("STOP")) {
loop = false;
} else {
Contact contact = new Contact(name, number);
phones.add(contact);
}
}
I can't give the working code. Just check below points to make your program better.
Why you are creating constructor with arguments when you using add contact method.
Where you are created object for class A in class Main.
Try to check how to use ArrayList class. Because you are not using add() properly.

Categories

Resources