ArrayList is empty when called in seperate class Java - java

I have class which initiates an arraylist of type String. I then add some dummy data into this array.
public class Main {
public static void main(String[] args)
{
Home h = new Home();
h.add();
}
}
public class Home
{
public ArrayList<String> Group_Customers= new ArrayList<String>();
public void add()
{
String[] group1 = {"0", "Mr", "Smith", "Andrew"}
for(int i = 1; i < group1.length; i++)
{
Group_Customers.add(group1[i]);
}
Add_Booking a = new Add_Booking();
a.Add();
}
}
In a seperate class. I then call this arraylist and add more data to it. However the array is empty in this different class
public class Add_Booking
{
String Title;
String Firstname;
String Surname;
public void add_Data
{
Title = "Mr";
Firstname = "Bob";
Surname = "Gallow";
save_Data();
}
public void save_Data
{
Home h = new Home();
String[] responses = {Title, Firstname, Surname};
for(int i = 1; i < responses.length; i++)
{
h.Group_Customers.add(responses[i]);
}
System.out.println(h.Group_Customers);
}
}
--Outputs responses without group1 test from class Home.
Am I refering to Group_Customers wrong within this different class?
All help appreciated.
Thanks

When calling Home h = new Home(); you instantiate a new Home with the default constructor.
Make sure you add the dummy data in the constructor if you want the array to contains data. Also, the actual code would not compile, you can't just throw method call in class body.
You would have something like this :
public class Home
{
//Declare the List
public ArrayList<String> Group_Customers = null;
//Default constructor
public Home()
{
//Instantiate and add dummy data
Group_Customers = new ArrayList<String>();
Group_Customers.add("test");
}
}
public class Add_Booking
{
public static void main(String args[])
{
//Construct a new home with default constructor.
Home h = new Home();
//Add new data
h.Group_Customers.add("new data");
//Display List content (should display test and new data)
System.out.println(h.Group_Customers);
}
}
Note that by convention, variable should start with a lower-case and an upper-case at each words so you should rename your variable as groupCustomers.

Related

Arraylist output getting overriden [duplicate]

This question already has answers here:
Avoiding overwriting objects in ArrayList
(2 answers)
Closed 3 years ago.
The data which was previously stored in an array list , is getting replaced by updated data.
code is shown below
public class Telivision {
private String tvBrand;
private Double tvCost;
private Integer tvDimension;
private String tvScreen;
public String getTvBrand() {
return tvBrand;
}
public void setTvBrand(String tvBrand) {
this.tvBrand = tvBrand;
}
public Double getTvCost() {
return tvCost;
}
public void setTvCost(String brand) {
if(this.tvBrand.equalsIgnoreCase("Samsung")){
this.tvCost = 100*1.5;
}else if(this.tvBrand.equalsIgnoreCase("Sony")){
this.tvCost = 100*2.0;
}
}
public Integer getTvDimension() {
return tvDimension;
}
public void setTvDimension(Integer tvDimension) {
this.tvDimension = tvDimension;
}
public String getTvScreen() {
return tvScreen;
}
public void setTvScreen(String tvScreen) {
this.tvScreen = tvScreen;
}
#Override
public String toString() {
return "Telivision [tvBrand=" + tvBrand + ", tvCost=" + tvCost + ", tvDimension=" + tvDimension + ", tvScreen="
+ tvScreen + "]";
}
TESTER IS AS SHOWN BELOW
public class TelivisionTester {
public static void main(String[] args) {
Telivision telivision = new Telivision();
ArrayList<Telivision> telList = new ArrayList<Telivision>();
telivision.setTvBrand("SAMSUNG");
telivision.setTvDimension(40);
telivision.setTvScreen("Led");
telivision.setTvCost("Samsung");
telList.add(telivision);
System.out.println(telList);
System.out.println(telivision.getTvBrand()+"Cost is "+telivision.getTvCost());
telivision.setTvBrand("Sony");
telivision.setTvDimension(36);
telivision.setTvScreen("Led");
telivision.setTvCost("Sony");
telList.add(telivision);
System.out.println(telList);
System.out.println(telivision.getTvBrand()+"Cost is "+telivision.getTvCost());
}
the output which is expected is as shown below
[Telivision [tvBrand=SAMSUNG, tvCost=150.0, tvDimension=40, tvScreen=Led],
Telivision [tvBrand=Sony, tvCost=200.0, tvDimension=36, tvScreen=Led]]
but the output observed is as shown below
[Telivision [tvBrand=Sony, tvCost=200.0, tvDimension=36, tvScreen=Led],
Telivision [tvBrand=Sony, tvCost=200.0, tvDimension=36, tvScreen=Led]]
kindly let me know what mistake i am doing in this code
You're list is not being overwritten. You are are adding the same instance of the class twice instead of creating a new one with the new attributes. Because the original istance changed you get the same attributes for both entries in the list. Create a new instance of the object for each Television you add to the list.
public static void main(String[] args) {
Telivision telivision = new Telivision();
ArrayList<Telivision> telList = new ArrayList<Telivision>();
telivision.setTvBrand("SAMSUNG");
telivision.setTvDimension(40);
telivision.setTvScreen("Led");
telivision.setTvCost("Samsung");
telList.add(telivision);
System.out.println(telList);
System.out.println(telivision.getTvBrand()+"Cost is "+telivision.getTvCost());
Telivision secondTelivision = new Telivision();
secondTelivision.setTvBrand("Sony");
secondTelivision.setTvDimension(36);
secondTelivision.setTvScreen("Led");
secondTelivision.setTvCost("Sony");
telList.add(secondTelivision);
System.out.println(telList);
}
You forgot to declare a second Telivision to separate the two.
public class TelivisionTester {
public static void main(String[] args) {
Telivision telivision = new Telivision();
ArrayList<Telivision> telList = new ArrayList<Telivision>();
telivision.setTvBrand("SAMSUNG");
telivision.setTvDimension(40);
telivision.setTvScreen("Led");
telivision.setTvCost("Samsung");
telList.add(telivision);
System.out.println(telList);
System.out.println(telivision.getTvBrand()+"Cost is "+telivision.getTvCost());
Telivision television2 = new Television();
telivision2.setTvBrand("Sony");
telivision2.setTvDimension(36);
telivision2.setTvScreen("Led");
telivision2.setTvCost("Sony");
telList.add(telivision2);
System.out.println(telList);
System.out.println(telivision2.getTvBrand()+"Cost is "+telivision2.getTvCost());
//telList.addAll(telList);
//System.out.println(telList);
}
}
Also “Telivision” is actually spelled Television

Java Program putting "null" in a text file instead of my string

EDIT: I understand what the issue is now. I was creating a new instance of the class which reset the values of the variables inside of it. For anyone wondering you can use 'static' for the value of a variable to stay the same throughout all instance of the class
Example: public static int example = 10;
I am trying to add a string to a text file, however when I add the string it puts "null" in the file instead of my string. The string is "listName"
Class where my a value is set to the string:
public class NewList {
private String listName;
public void newList() {
System.out.println("NEW LIST");
System.out.print("List Name: ");
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
setListName(scanner.next());
System.out.println(listName);
ListsWriter listsWriterObject = new ListsWriter();
listsWriterObject.listsWriter();
}
public String getListName() {
return listName;
}
public void setListName(String listName) {
this.listName = listName;
}
Class where the string is added to the text file:
public class ListsWriter {
public void listsWriter() {
NewList newListObject = new NewList();
File lists = new File("lists.txt");
try{
PrintWriter pw = new PrintWriter(new FileWriter(lists, true));
pw.append(newListObject.getListName() + "\n");
pw.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}
Take a look at the order how your code is executed. You start with your scanner stuff and save the name inside the variable private String listName;. This variable belongs to the instance of the class NewList you are currently in. It is important to note that if you create other instances of NewList then they will all have their own listName variables.
Next you create ListsWriter and call its method. There you try to read the list name with newListObject.getListName() however you use NewList newListObject = new NewList(); before. This will create a new instance of NewList. It has its own listName variable, it is not the same than the variable of the other instance! Thus it is null.
If you want the name of the other instance you need to pass either the value or a reference to this instance to the ListsWriter object.
You can do this by using a constructor for ListsWriter that accepts a String as parameter (or a reference to a NewList object). Or you add the parameter to the method listsWriter.
For example:
public void listsWriter(String listName) {
Okay! so I have modified your code you can use it :)
NewList.java
public class NewList {
private String listName;
public void newList() {
System.out.println("NEW LIST");
System.out.print("List Name: ");
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
listName = scanner.next();
System.out.println(listName);
ListsWriter listsWriterObject = new ListsWriter();
listsWriterObject.listsWriter(listName);
}
public static void main(String[] args) {
new NewList().newList();
}
}
ListsWriter.java
public class ListsWriter {
public void listsWriter(String listName) {
File lists = new File("lists.txt");
try{
PrintWriter pw = new PrintWriter(new FileWriter(lists, true));
pw.append(listName + "\n");
pw.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}

Getting java null pointer exception when adding object class to reportGroup.getReportList()

I have assigned the values to the member of a Report Info class and tried to add to the Report Group class.Getting java null pointer exception.Even though I have already initialized report Info at the very beginning.
Getting error when doing this- reportGroup.getReportList().add(reportInfo);
I have two java classes.
ReportGroup.java
String GroupName;
List<ReportInfo>reportList;
public String getReportGroupName() {
return ReportGroupName;
}
public void setReportGroupName(String reportGroupName) {
ReportGroupName = reportGroupName;
}
public List<ReportInfo> getReportList() {
return reportList;
}
public void setReportList(List<ReportInfo> reportList) {
this.reportList = reportList;
}
}
ReportInfo.java
String ReportName;
String ReportId;
String ReportPath;
//Getter and Setter
Main class:
public class test {
List<ReportInfo> reportInfo = new ArrayList<ReportInfo>();
public static void main(String[] args) throws IOException {
String orgId="346";
String orgName="Ralph Lauren Corporation";
String reportPath= "/"+orgId +"_"+orgName.replaceAll(" ","_");
String reportFolderPath = "C:/Lokesh/Dev Tools/apache-tomcat-6.0.37/webapps/ROOT/Reports";
List<String> filesArray = null;
filesArray = new ArrayList<String>();
String filetowrite="C:/Users/lbandhu/Desktop/test.html";
FileWriter fw=new FileWriter(filetowrite);
ReportGroup reportGroup=new ReportGroup();
reportGroup.setReportGroupName(orgName); //Organization Name such as Ralph Lauren Corporation
fw.write("<html><head><title>"+ reportGroup.ReportGroupName+"</title><h1>Utilization Report</h1><span>Please contact your account manager for a listing of utilization report definitions or with any questions on your organization’s reports. </span><br></head><body><table>");
//fw.write("<br><h>"+orgName+"</h><br>");
File folder = new File(reportFolderPath+reportPath);
List<String> reportNames = listFolder(folder);
for (String rname : reportNames) {
ReportInfo reportInfo=new ReportInfo();
reportInfo.setReportName(rname);
folder = new File(reportFolderPath+reportPath+"/"+reportInfo.ReportName);
System.out.println(folder);
fw.write("<br><tr> "+reportInfo.ReportName +" Utilization Reports</tr><br>"); //Report Name such as Monthly,Quarterly and Yearly
Iterator<String> iterator=listFilesForFolder(folder, filesArray).iterator();
writeReportPath( fw,iterator, reportFolderPath,reportInfo);
fw.write("<br>");
reportGroup.getReportList().add(reportInfo);
}
filesArray.clear();
fw.close();
}
You need to initialize the list in the constructor:
public ReportGroup(){
reportList = new ArrayList<ReportInfo>();
}
or
public ReportGroup(String GroupName){
this.GroupName = GroupName;
reportList = new ArrayList<ReportInfo>();
}
You are initializing the field reportInfo of instances of your test class, but not the field reportInfo of your ReportGroups. It doesn't look like you actually instanciate your test class, and this field is not visible to static (i. e. class) methods anyway. Even if it were visible (for example, if it were static itself), you would shadow it with the local variable reportInfo.
When you do ReportInfo reportInfo = new ReportInfo() in the first line of your for loop, you are creating a new ReportGroup with a new reportInfo member, which is uninitialized.
Your ReportGroup should look about like this:
class ReportGroup {
final List<ReportInfo> reportInfo = new ArrayList<>();
}
Alternatively, you can do the initialization in the constructor:
class ReportGroup {
final List<ReportInfo> reportInfo;
ReportGroup () {
reportInfo = new ArrayList<ReportInfo>;
}
}

Java, Using a String in an array in elsewhere?

I am new at coding. I was doing a project but I was stuck. My code reads a sentence from a text file. It seperates the sentence and gets the second word and records it in an array. I need to use this word in another place but I couldn't do it.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Classroom {
private String classname;
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname;
}
public void classroomreader(String filename) {
// This method gets the name for Classroom
File text = new File("C:/classlists/" + filename + ".txt");
Scanner scan;
try {
scan = new Scanner(text);
String line = scan.nextLine();
String classroomarray[] = line.split("\t");
// ** right now classroomarray[1] has the word which I want.**
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
}
Here is my main class:
public class ProjectMain {
public static void main(String[] args) {
// I created an array with 3 Classroom object inside it.
Classroom[] classarray = new Classroom[3];
//I hope I did this correct.
// I used classroomreader method on my first object.
classarray[0].classroomreader("class1");
// Now I need to use the word in classroomarray[1].
classarray[0].setClassname(????)
}
}
I tried: classarray[0].setClassname(classroomarray[1]); but it gave an error. How can I set the name for my first object?
i'm making just few changes in your code.. try this....definitely this'll work
class Classroom {
private String classname;
String classroomarray[]=null;//declare classroomarray[] here
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname;
}
public void classroomreader(String filename) {
File text = new File("C:/classlists/" + filename + ".txt");
Scanner scan;
try {
scan = new Scanner(text);
String line = scan.nextLine();
classroomarray = line.split("\t");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
}
class ProjectMain {
public static void main(String[] args) {
Classroom[] classarray = new Classroom[3];
//here you need to initialize all elements of the array
classarray[0]=new Classroom();
classarray[1]=new Classroom();
classarray[2]=new Classroom();
classarray[0].classroomreader("class1");
classarray[0].setClassname(classarray[0].classroomarray[1]);
System.out.println(classarray[0].getClassname());// here you'll surely get the the desired results
}
}
Its a little hard for me to understand what your code in the top is doing.. that being said I believe if you have a private variable in your top class and then have an accessor method like
public String getPrivateFieldValue()
{
return somePrivateFieldName;
}
Then you can can set the private variable in your main class when you find the value for it. In your main class you can then say:
Object.getPrivateFieldValue() to get that value
or in your situation:
classarray[0].setClassname(classroomreader.getPrivateFieldValue())
I think your problem lies with the concept of scope. Whenever you create a variable, like classroomarray, java registers that the name of that variable then represents the value you assign to it (in simple terms).
Now what Scope means is that not all variables can be accessed from every place. Classroomarray is created inside classroomReader(), but does not get out of that function once it completes. In a way "lives" inside that function, and that's why you can't use it in the main() method.
If you want to use classroomarray inside the main() method, you'll need to transport it there through some means. There are multiple ways of doing this:
Create a field in ClassRoom, like public String[] classroomarray
Return the classroom array you read from the file from the classroomreader() function. Returning a value means that you're "sending back" a value to whatever code called the function in the first place. For example, add(a, b) would return the sum of a and b. You do this by changing:
public void classroomreader(String filename)
To:
public String[] classroomreader(String filename)
And change:
String classroomarray[] = line.split("\t");
To:
return line.split("\t");
Then, in the main() method, you can use:
String[] classroomFile = classarray[0].classroomreader("class1");
And use the contents as you please.
This is an Example,Hope you don't mind hard interpretation. Please add return to your method like this.
public String[] demo() //Added ()
{
String[] xs = new String[] {"a","b","c","d"}; //added []
String[] ret = new String[4];
ret[0]=xs[0];
ret[1]=xs[1];
ret[2]=xs[2];
ret[3]=xs[3];
return ret;
}
So your new code will be like this
public String[] classroomreader(String filename) {
// This method gets the name for Classroom
File text = new File("C:/classlists/" + filename + ".txt");
String[] classroomarray;
Scanner scan;
try {
scan = new Scanner(text);
String line = scan.nextLine();
classroomarray = new String[] {line.split("\t")};//Change this
// ** right now classroomarray[1] has the word which I want.**
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
return classroomarray;
}
In Main method change this:
String [] strArr = demo();//Calling method which returns value clasroomarray
for ( int i = 0; i < strArr.length; i++) {
System.out.println(strArr[3]);//Printing whatever index you want
//Set Values here like this
Classroom classroom=new Classroom();//Initialize your object class
classroom.set(strArr[3]); //Set value
Hi i suggest you declare
classroomarray[]
as a member variable. Then generate getters and setters.
Later you can do what you want by setting
classarray[0].setClassname(classarray[0].getClassroomarray[1]);
I'm trying to help you on the way you want it to be done, but i don't understand why you wanna it to be done like that.
Edit : Here is the code i'm talking about in the comments below
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Classroom {
private String classname;
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname;
}
public void classroomreader(String filename) {
// This method gets the name for Classroom
File text = new File("C:/classlists/" + filename + ".txt");
Scanner scan;
try {
scan = new Scanner(text);
String line = scan.nextLine();
String classroomarray[] = line.split("\t");
// ** right now classroomarray[1] has the word which I want.**
this.classname = classroomarray[1];
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
}
And finally your main method should look like
public class ProjectMain {
public static void main(String[] args) {
// I created an array with 3 Classroom object inside it.
Classroom[] classarray = new Classroom[3];
classarray[0]=new Classroom();
//I hope I did this correct.
// I used classroomreader method on my first object.
classarray[0].classroomreader("class1");
// Now classname is already set
System.out.println(classarray[0].getClassname());
}
}

Adding an arrayList to another arrayList in a separate class?

I'm having some difficulty adding an arrayList of user details to another arrayList which contains details of each user i create.
I have 2 classes: addUser and Database.
In the addUser class i have the following code:
JLabel submitButton = new JLabel("Submit: ");
contentPane.add(submitButton);
JButton addUser = new JButton("+ Add User");
addUser.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
addToArray();
databaseArray.add(app);
frame.dispose();}});
contentPane.add(addUser);
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
//arraylist of details for a single applicant
final ArrayList<String> app = new ArrayList<String>();
public void addToArray()
{
appNumber = appNumberField.getText();
name = nameField.getText();
date = dateField.getText();
fileLoc = fileLocField.getText();
country = countryRefField.getText();
app.add(appNumber);
app.add(name);
app.add(date);
app.add(fileLoc);
app.add(country);
}
in the database class i have the following code:
public class Database
{
public ArrayList<ArrayList> applicants;
/**
* Constructor for objects of class Database
*/
public Database()
{
applicants = new ArrayList<ArrayList>();
}
/**
* adds a new applicant to the database
*/
public void addApplicant(ArrayList app)
{
applicants.add(app);
}
public void list()
{
int n = applicants.size();
for(int i = 0; i < n ; i++)
System.out.println(applicants.get(i));
}
}
However when i add a user from the addUser class it does not appear when i use the list method in the Database class.
Any help would be appreciated.
Thanks.
import java.util.ArrayList;
public class Store {
int appNumber;// = appNumberField.getText();
String name;// = nameField.getText();
int date;// = dateField.getText();
boolean fileLoc;// = fileLocField.getText();
String country;// = countryRefField.getText();
public Store(int appNumbe, String nam, int dat, boolean fileLo,
String countr) {
appNumber = appNumbe;
name = nam;
date = dat;
fileLoc = fileLo;
country = countr;
}
public static void main(String[] args) {
ArrayList<Store> app = new ArrayList<Store>();
app.add(new Store(22, "Name", 2, false, "India"));
}
}
I think you should try something like this to store data . It will be easy to insert and retrive .

Categories

Resources