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

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

Related

Method in class can't access arraylist from same class

I don't understand why but my method can't access the arraylist. When I try to add from input it says error: cannot find symbol.
public class Kitchen{
public static void Kitchen(String[] args ){
ArrayList<String> Utensil = new ArrayList<String>();
Utensil.add("Knife");
Utensil.add("Boiler");
System.out.println(Utensil);
}
public void addUtensil(){
Scanner sc = new Scanner(System.in);
System.out.println("Utensil to add? ");
String new = sc.nextLine();
Utensilio.add(new);
}
}
You have to pass the Utensil ArrayList as a parameter to the addUtensil() method.
public static void Kitchen(String[] args ){
ArrayList<String> Utensil = new ArrayList<String>();
Utensil.add("Knife");
Utensil.add("Boiler");
addUtensil(Utensil);
System.out.println(Utensil);
}
public static void addUtensil(List<String> Utensil){
Scanner sc = new Scanner(System.in);
System.out.println("Utensil to add? ");
String new = sc.nextLine();
Utensilio.add(new);
}
There are two different methods
Kitchen
addUtensil
you declared a below local variable in one method(Kitchen) and trying to access on other method(addUtensil).
ArrayList<String> Utensil = new ArrayList<String>();
In java you can not access the local variable of one method to another
Another option is to define it as an class variable, remember that we can access a static variable via not static method,but on the other side it's not
public class Kitchen{
private static ArrayList<String> Utensil = new ArrayList<String>();
public static void Kitchen(String[] args ){
Utensil.add("Knife");
Utensil.add("Boiler");
System.out.println(Utensil);
}
public void addUtensil(){
Scanner sc = new Scanner(System.in);
System.out.println("Utensil to add? ");
String new = sc.nextLine();
Utensilio.add(new);
}
}

ArrayList is empty when called in seperate class 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.

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

Java - How to create a class instance from user input

I want this program to ask the user for input, and create a class instance with a name equal to the input of the user. Then, the createMember class will create a text file, where all the data of the user will be stored. How do I go about doing it?
Here's the main method:
public static void main(String[] args) {
String input = keyboard.nextLine();
input = new createMember(); // Error. can't do that for some reason?
}
}
Here's the createMember class
public class createMember {
public void setMembership() {
Scanner keyboard = new Scanner(System.in);
out.println("Username: ");
String input = keyboard.nextLine();
try {
//Creates a text file with the same name as the username where data is stored.
Formatter x = new Formatter(input);
} catch (Exception e) {
out.println("Could not create username");
}
}
//Methods for the user
Guys... I know I can simply create an instance like this:
createMember member = new createMember();
What I actually want to do is HAVE THE USER do that on his own, so the program is flexible and usable for many people. So, based on the input, there will be a separate folder that stores the data for each user.
Looks like you need a non-default Constructor: (Constructors CANNOT return any value, not even void, as the instance is what is actually returned.
String input = keyboard.nextLine();
Member m = new Member(input);
public class Member {
private String name;
public Member(String name) {
this.name = name;
}
public void setMembership() {
try {
//Creates a text file with the same name as the username where data is stored.
Formatter x = new Formatter(name);
} catch (Exception e) {
out.println("Could not create username");
}
}
}
You need a constructor
public class CreateMember {
private String input;
public CreateMember(String input){
this.input = input;
}
public String getInput(){
return input;
}
}
To access the input use CreateMember.getInput()
public static void main(String[] args){
String input = scanner.nextLine();
CreateMember member = new CreateMember(input);
System.out.println(member.getInput());
}

Categories

Resources