Java, Using a String in an array in elsewhere? - java

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

Related

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

Java - Using an object inside an object

I am working on a project ( I had a problem yesterday and so many people helped me!) so I decided to ask for help again.
My code has 3 classes. ProjectMain,Students,Classroom. I created an array of Classroom objects. Right now I have 3 Classroom objects. But I have to assign student objects to these Classroom objects. For example : classarray[0] is an object from Classroom class and studentobject.get(0) , studentobject.get(1) ... will be students objects inside classarray[0] object. But I have failed on this while coding. Here are my classes :
public class Classroom
{
private String classname;
private String word[] = null;
protected ArrayList<Students> studentobject = new ArrayList<Students>(10);
public String[] getWord()
{
return word;
}
public void setWord(String[] word)
{
this.word = word;
}
public ArrayList<Students> getStudentobject()
{
return studentobject;
}
public void setStudentobject(ArrayList<Students> studentobject)
{
this.studentobject = studentobject;
}
public String getClassname()
{
return classname;
}
public void setClassname(String classname)
{
this.classname = classname;
}
public void classroomreader(String filename)
{
// This method gets the name of Classroom
File text = new File("C:/Users/Lab/Desktop/classlists/" + filename
+ ".txt");
Scanner scan;
try
{
scan = new Scanner(text);
String line = scan.nextLine();
word = line.split("\t");
line = scan.nextLine();
word = line.split("\t");
} catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
}
}
This is my student class :
public class Students extends Classroom
{
private String name,id;
private int age;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
And my main class :
public class ProjectMain
{
public static void main(String[] args)
{
Classroom[] classarray = new Classroom[3];
//I got 3 Classroom objects here
classarray[0]=new Classroom();
classarray[1]=new Classroom();
classarray[2]=new Classroom();
classarray[0].classroomreader("class1");
classarray[0].studentobject.get(0).setName(classarray[0].getWord()[1]);
//The problem is in here. When my code comes to the line above,
// at java.util.ArrayList.rangeCheck(Unknown Source) error comes out.
// I tried to get first object in studentobject Arraylist, and tried to set it's name
// to the variable which my text reader reads.
How can I write what I have in my mind?
Your classroomreader method reads the file but don't do much of it... maybe you want to create some instance of Students within it.
scan = new Scanner(text);
String line = scan.nextLine();
word = line.split("\t"); // won't be used
line = scan.nextLine();
word = line.split("\t"); // erased here
There you only have the last line (split) of the file in word attribute.
When creating Classroom instance studentobject list is created empty and it stays that way so you can't access first (or any) object in it.
To populate your list you may add to Classroom method like this:
public void addStudent(Student s)
{
studentobject.add(s);
}
classroom contains the following field declaration
String word[] = null;
the main class, incl the classroomreader does not set a value to this field. Yet you are going to invoke
classarray[0].getWord()[1]
which then must fail.
tip: don't use expressions like this, which can be found in your main class (at least not in early stages of development, or learning)
classarray[0].studentobject.get(0).setName(classarray[0].getWord()[1]);
resolve into variables and several steps. Compilers are smart enough to produce the same code if the context is not disturbed, ie the long expression is resolved into a single block.
Never forget that the purpose of programming languages is to make programs readable for humans. :) Code with abbreviations or "tricks" simply shows some philodoxical attitude (imho)

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

How can I fix output from ArrayList?

I'm writing a program that reads from a file. Each line in the file contains information about a student.Each student is represented by an object from the class "Student". The class Student has a method getName that returns the student's name.The method that goes through the file returns and ArrayList containing student objects. My problem is that every time I use a for loop to access the ArrayList and get the name of each student, what I get is the name of the last student in the list. The method that go through the file is called "FileAnalyzer" Below is my code.
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class StudentStats {
public static void main(String[] args) {
List<Student> example = null;
example = FileAnalyzer("C:\\Users\\achraf\\Desktop\\ach.csv");
for ( int i = 0; i < example.size(); i++)
{
System.out.println(example.get(i).getName());
}
}
public static List<Student> FileAnalyzer(String path) //path is the path to the file
{
BufferedReader br = null;
List<Student> info = new ArrayList<Student>();
String line = "";
try {
br = new BufferedReader (new FileReader(path));
while ((line = br.readLine()) != null)
{
//We create an object "Student" and add it to the list
info.add(new Student(line));
}
}
catch (FileNotFoundException e) {
System.out.println("Aucun fichier trouvé");
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return info;
}
In case you need it, here's the code for the class student
// This class create objects for each student
public class Student {
private static String Name ="";
private static String Sex = "";
private static String Grade = "";
//constructor
public Student(String infos)
{
String [] etudiant = infos.split(",");
Name = etudiant[0];
Sex = etudiant[1];
Grade = etudiant[2];
}
// Getter functions
public String getName()
{
return Name;
}
public String getSex()
{
return Sex;
}
public String getGrade()
{
return Grade;
}
}
Below is the content of a typical file that the programs reads.
lovett,M,12
Achos,F,23
Loba,M,24
THE REAL problem is that after running my code to get the names, I get the name "Loba" three times instead of getting all the names.
Here is the problem in your Student class:
private static String Name ="";
private static String Sex = "";
private static String Grade = "";
You need to remove the static from the member variables otherwise all the objects will share the same attributes and hence you see only the last values written in those variables always.
Learn more about instance and class variables here: http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
Your member variables are declared static in the Student class. That means that they exist as one copy throughout your program, not as one copy per instance which is what you want. Every time you're creating a new student, you're setting the name, sex and grade to something new, but these values are not associated with any particular student. All students share these attributes, and they are being overwritten in your file reading loop, so whatever is the last name in your file will be the name of the static variables.

Get String From Another Method?

I have two methods, the first one creates a string, then I want to use that string in the second method.
When I researched this, I came across the option of creating the string outside of the methods, however, this will not work in my case as the first method changes the string in a couple of ways and I need the final product in the second method.
Code:
import java.util.Random;
import java.util.Scanner;
public class yaya {
public static void main(String[] args) {
System.out.println("Enter a word:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
Random ran = new Random();
int ranNum = ran.nextInt(10);
input = input + ranNum;
}
public void change(String[] args) {
//more string things here
}
}
Create an instance variable:
public class MyClass {
private String str;
public void method1() {
// change str by assigning a new value to it
}
public void method2() {
// the changed value of str is available here
}
}
You need to return the modified string from the first method and pass it into the second. Suppose the first method replaces all instances or 'r' with 't' in the string (for example):
public class Program
{
public static String FirstMethod(String input)
{
String newString = input.replace('r', 't');
return newString;
}
public static String SecondMethod(String input)
{
// Do something
}
public static void main(String args[])
{
String test = "Replace some characters!";
test = FirstMethod(test);
test = SecondMethod(test);
}
}
Here, we pass the string into the first method, which gives us back (returns) the modified string. We update the value of the initial string with this new value and then pass that into the second method.
If the string is strongly tied to the object in question and needs to be passed around and updated a lot within the context of a given object, it makes more sense to make it an instance variable as Bohemian describes.
Pass the modified string in the second method as an argument.
create a static variable used the same variable in both the method.
public class MyClass {
public string method1(String inputStr) {
inputStr += " AND I am sooo cool";
return inputStr;
}
public void method2(String inputStr) {
System.out.println(inputStr);
}
public static void main(String[] args){
String firstStr = "I love return";
String manipulatedStr = method1(firstStr);
method2(manipulatedStr);
}
}
Since you mentioned that both methods should be able to be called independently, you should try something like this:
public class Strings {
public static String firstMethod() {
String myString = ""; //Manipulate the string however you want
return myString;
}
public static String secondMethod() {
String myStringWhichImGettingFromMyFirstMethod = firstMethod();
//Run whatever operations you want here and afterwards...
return myStringWhichImGettingFromMyFirstMethod;
}
}
Because both of these methods are static, you can call them in main() by their names without creating an object. Btw, can you be more specific about what you're trying to do?

Categories

Resources