Java Swing Object[][] getData() confusion - java

Hi I'm having some trouble getting started with a problem in a Java course learning Swing and starting on JTables and getting data into them. It's going to be hard to explain so I'm just going to post the code I was given, along with the question.
The question is:
The getData() method needs to return an Object[][] containing the data represented by the class.
The first class is MusicAlbum
class MusicAlbum {
private String id;
private String name;
private String genre;
private boolean isCompilation;
private int track_count;
public MusicAlbum(String id, String name, String genre, boolean isCompilation, int track_count) {
this.id = id;
this.name = name;
this.genre = genre;
this.isCompilation = isCompilation;
this.track_count = track_count;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getGenre() {
return genre;
}
public boolean isCompilation() {
return isCompilation;
}
public int getTrackCount() {
return track_count;
}
public boolean equals(Object obj) {
if (obj instanceof MusicAlbum)
return this.id.equalsIgnoreCase(((MusicAlbum)obj).id);
return super.equals(obj);
}
}
The class I have to implement the methods in is MusicDataObject (at the bottom)
import java.util.Random;
import java.util.Scanner;
public class MusicDataObject {
private List<MusicAlbum> albums = new ArrayList<>();
private Random random = new Random(); // for generating IDs
public void addAlbum(MusicAlbum album) throws IllegalArgumentException {
if (searchAlbum(album.getId()) != null)
throw new IllegalArgumentException("Album ID is not new!");
albums.add(album);
}
public MusicAlbum searchAlbum(String id) {
for (MusicAlbum album : albums) {
if (album.getId().equalsIgnoreCase(id)) {
return album;
}
}
return null;
}
public MusicAlbum removeAlbum(String id) {
MusicAlbum album = searchAlbum(id);
albums.remove(album);
return album;
}
public void updateAlbum(MusicAlbum album)
throws IllegalArgumentException {
if (removeAlbum(album.getId()) == null)
throw new IllegalArgumentException("Album ID does not exist!");
addAlbum(album);
}
public String generateID() {
String formatter = "A%0" + (int)Math.ceil(Math.log10(albums.size() * 2) + 1) + "d";
String ID;
do {
ID = String.format(formatter, random.nextInt(albums.size() * 2 + 1));
} while (searchAlbum(ID) != null);
return ID;
}
public void saveData(String fileName) throws IOException {
// make sure that the file exists or try to create it
File fout = new File(fileName);
if (!fout.exists() && !fout.createNewFile())
return;
PrintWriter out = new PrintWriter(fout);
for (MusicAlbum album: albums) {
out.println(serializeAlbum(album));
}
out.close();
}
public String serializeAlbum(MusicAlbum album) {
return String.format(
"%s;%s;%s;%b;%d",
album.getId(),
album.getName(),
album.getGenre(),
album.isCompilation(),
album.getTrackCount());
}
public void loadFile(String fileName) throws FileNotFoundException {
albums = new ArrayList<>();
Scanner in = new Scanner(new File(fileName));
while (in.hasNext()) {
// --- split the next line with the character ";"
String line = in.nextLine();
String[] tokens = line.split(";");
// --- construct a new MusicAlbum using the resulting tokens. NOTE: This isn't very robust.
// If a line doesn't contain enough data or the data is invalid, this will crash
albums.add(new MusicAlbum(
tokens[0],
tokens[1],
tokens[2],
Boolean.parseBoolean(tokens[3]),
Integer.parseInt(tokens[4])
));
}
}
// ----- these methods need to be implemented
public Object[][] getData() {
// TODO
}
public String[] getColumnNames() {
// TODO
}
}
The sample data being used is in a txt file, formatted as so:
A01;Defiance;Soundtrack;true;24
A02;Insomniac;Punk Rock;false;14
A03;A Great Day For The Race;Gypsy Jazz;false;10
A04;Viva La Internet;Ska;false;31
A05;New Surrender;Rock;false;17
So basically it's this getData() method they want me to implement that is giving me grief. I don't fully understand what they want me to do, nor do I fully understand what the Object[][] does.
I hope I have been clear enough, and I will appreciate all help given. Also please try to explain things as best you can and dumb them down as much as possible, I'm new to a lot of this :)
Thanks for your time.

Object[][] is a 2-dimensional array. Each of its element is an Object[], a one-dimensional array.
Your task is to create a 2 dimensional array, having one element (Object[]) for each of your MusicAlbum. An Object[] should hold the properties of a MusicAlbum like id, name, genre, isCompilation and track_count.
You can create an object array like this:
Object[] arr = new Object[] { "some", "values", 23, true };
You can create a 2 dimensional array like this:
Object[][] arr2d = new Object[size][];
And you can iterate over all your MusicAlbums, create an Object[] for each of them containing the properties of that music album, and set it in the arr2d.
You can set/get elements of a 2-dimensional array just like any other arrays:
// Set first element:
arr2d[0] = arr;
// Get first element:
Object[] firstElement = arr2d[0];
The getColumnNames() method should just return a String[] (a String array) containing the column names, the names of the properties.
And it might be obvious but note that the order you return the column names and the order of the property values (in the elements of the Object[]) should be the same.

Related

How can I return int and string attributes in a single Java method?

I would like to return the values of all the attributes from the BaseballPlayer class. The method that needs to do this must be the public string getBaseballPlayer(int i) method (because I need to reference this method inside getBaseballPlayers() to return all the values as an arraylist of strings) I'm having trouble doing this because all the attributes have different datatypes (int, String, Height).
I've tried doing this:
public String getBaseballPlayer(int i){
ArrayList <String> bArray = new ArrayList <String>();
bArray.add(getHometown());
bArray.add(getState());
bArray.add(getHighSchool());
bArray.add(getPosition());
However, it only works for the string methods, and doesn't necessarily return the actual values but rather the get methods for each string attribute.
public class BaseballPlayer extends Player implements Table {
private int num;
private String pos;
public BaseballPlayer( int a, String b, String c, int d,
String e, String f, String g, Height h){
super(a,ft,in,c,d,e,f,ht);
num = a;
pos = b;
}
public BaseballPlayer(){}
//Returns the value of a specific attribute. The input parameter start
with 0 for the first attribute, then 1 for the second attribute and so
on.
//you can use getBaseballPlayer(int i) in getBaseballPlayers( ) with a for
loop getting each getBaseballPlayer(int i).
public String getBaseballPlayer(int i){
ArrayList <String> bArray = new ArrayList <String>();
bArray.add(getHometown());
bArray.add(getState());
bArray.add(getHighSchool());
bArray.add(getPosition());
return (bArray);
}
//Returns the value of all attributes as an ArrayList of Strings.
public ArrayList <String> getBaseballPlayers(){
}
I'm just looking for the simplest way to return each attributes value, then using that method return each value as an arraylist of strings in another method.
It is not a good practice to return the whole object as one String. Unless and otherwise, you are forced to do this, do not try and do.
Well, if your requirement can't be changed, and if you want everything from the Baseball object to be in one string, you can concatenate all the parameters with a delimiter like ":".
Eg:
public String getBaseballPlayer(int i){
return getHometown() + ":" + getState() + ":" +getHighSchool() + ":" + getPosition();
}
On the invoking side, you can get the individual values from this String using "split()" method of String.
What you want to do, if you want to do it perfectly, is what Gson is for. It rides on top of simple JSON and can encode arbitrary classes, data structures, and other types into JSON such that you can reconstruct those objects easily from the JSON representation. It's easy to use considering how powerful what it does really is.
It's even easier to use regular JSON if you don't need to encode types that JSON won't handle by itself. In your case, it seems that this could be good enough. The great thing about JSON is that it's a standard. You don't have to choose an encoding scheme, and you already have libraries written in any language you can think of that can read your String'ified data.
Here's an example that roughly follows what your code is doing:
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
public class BaseballPlayer {
private String name;
private String hometown;
private String state;
private int age;
private double height;
private String position;
static ObjectMapper mapper = new ObjectMapper();
public BaseballPlayer( String name, String hometown, String state, int age, double height, String position) {
this.name = name;
this.hometown = hometown;
this.state = state;
this.age = age;
this.height = height;
this.position = position;
}
public void setName(String name) {
this.name = name;
}
public void setHometown(String hometown) {
this.hometown = hometown;
}
public void setState(String state) {
this.state = state;
}
public void setAge(int age) {
this.age = age;
}
public void setHeight(float height) {
this.height = height;
}
public void setPosition(String position) {
this.position = position;
}
public String toString() {
return String.format("Name: %s from %s, %s (height: %.1f)", name, hometown, state, height);
}
public BaseballPlayer(){}
// Turn a BaseballPlayer object into a String
public String getAsJSON() {
Map<String, Object> info = new HashMap<>();
info.put("name", name);
info.put("hometown", hometown);
info.put("state", state);
info.put("age", age);
info.put("height", height);
info.put("position", position);
try {
return mapper.writeValueAsString(info);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Here's the method you ask for. I don't know what 'i' is supposed
// to do, since we're in the class for a single baseball player. You
// could create a class that contains a list of baseball players, but
// why not just use a List by itself, as I've done.
public String getBaseballPlayer(int i) {
return getAsJSON();
}
// Turn a list of BaseballPlayer objects into a list of Strings
public static List<String> playersToStrings(List<BaseballPlayer> players) {
List<String> r = new ArrayList<>();
for (BaseballPlayer player : players) {
r.add(player.getAsJSON());
}
return r;
}
// Turn a list of Strings into a list of BaseballPlayer objects
public static List<BaseballPlayer> stringsToPlayers(List<String> playerStrings) {
List<BaseballPlayer> r = new ArrayList<>();
for (String playerString : playerStrings) {
try {
BaseballPlayer player = mapper.readValue(playerString, BaseballPlayer.class);
r.add(player);
} catch (IOException e) {
e.printStackTrace();
}
}
return r;
}
public static void main(String... args) {
// Create a list of BaseballPlayer objects and print them
List<BaseballPlayer> players = new ArrayList<>();
players.add(new BaseballPlayer("Joe", "Boston", "MA", 25, 6.1, "First Base"));
players.add(new BaseballPlayer("Sam", "San Francisco", "CA", 28, 5.8, "Pitcher"));
players.add(new BaseballPlayer("Kelly", "Chicago", "IL", 32, 6.4, "Catcher"));
System.out.println(players);
// Convert the list to a list of Strings and print the list
List<String> playerStrings = playersToStrings(players);
System.out.println(playerStrings);
// Convert the Strings back into BaseballPlayer objects and print them
players = stringsToPlayers(playerStrings);
System.out.println(players);
}
}
and here's the resulting output:
[Name: Joe from Boston, MA (height: 6.1), Name: Sam from San Francisco, CA (height: 5.8), Name: Kelly from Chicago, IL (height: 6.4)]
[{"hometown":"Boston","name":"Joe","state":"MA","position":"First Base","age":25,"height":6.1}, {"hometown":"San Francisco","name":"Sam","state":"CA","position":"Pitcher","age":28,"height":5.8}, {"hometown":"Chicago","name":"Kelly","state":"IL","position":"Catcher","age":32,"height":6.4}]
[Name: Joe from Boston, MA (height: 6.1), Name: Sam from San Francisco, CA (height: 5.8), Name: Kelly from Chicago, IL (height: 6.4)]
Here, each player is turned into JSON individually. A few more lines of code, and you could turn an array of Baseball Player objects into a single String.
If this JSON-only solution isn't good enough for you, check out Gson. It can preserve all Java types. It just takes a bit more setup to describe how each of your objects should be turned into JSON and back.

Why I can't get objects from file properly?

I have list of custom objects that I writre and then read to file.
Here is my class:
public class Book implements Serializable{
private int isbn;
private String category;
private String authorName;
public int getIsbn() {
return isbn;
}
public String getCatId() {
return category;
}
public void setIsbn(int isbn) {
this.isbn = isbn;
}
public void setCategory(String category) {
this.category = category;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public String getAuthorName() {
return authorName;
}
public Book() {}
//copy book
public Book(Book book, int id) {
this.category = book.category;
this.title = book.title;
this.authorName = book.authorName;
this.isbn = id;
}
}
Here is function that I use to write the list of objects:
private static <T> void writeToFile(List<T> items, String fileName) {
try {
String path = "src\\hw1\\library\\repos\\" + fileName;
FileOutputStream f = new FileOutputStream(path, true);// true- means append to file
ObjectOutputStream o = new ObjectOutputStream(f);
// Write objects to file
o.writeObject(items);
o.close();
f.close();
} catch (Exception e) {}
}
And here is function that I reade from the list:
private static <T> List<T> readFromFile(Context context, String fileName) {
try {
String path = "src\\hw1\\library\\repos\\" +fileName ;
FileInputStream fi = new FileInputStream(path);
ObjectInputStream oi = new ObjectInputStream(fi);
// Read objects
List<T> items = (List<T>)oi.readObject();
oi.close();
fi.close();
return items;
} catch (Exception e) {}
return null;
}
The List of objects is written to the file,
but when I try to read it with function above the objects that I get from file only objects that was written to file first time.
Any idea why I get from file only objects that was written to file first time?
I only asume that
but when I try to read it with function above the objects that I get
from file only objects that was written to file first time.
Single write will put given list into a file, second write will put another list into that file - because you are appending to file
Now, you read method always reads from the begining so every invocation of readFromFile will result in reading the same (very first) object (list in your case) from given file. You would have to do do more f.readObject() on the same stream.
If you are not going to read all objects at once, I would suggest to use 1 file per list, so you will not have use file seeking to "shift" position of file pointer (nor doing empty f.readObject() invocations)

android studio: having trouble setting global string array

Hi I'm working on an android studio project using global arrays,
I can read from the global arrays fine, and have no problem writing
to the global integers ,But i cannot figure out how to set the global
array from code, this is the important parts of the project:
added this under application tag in the android manifest xml:
android:name=".Globals"
java class Globals:
import android.app.Application;
public class Globals extends Application {
public int empnum=13;
public int getData3() {
return empnum;
}
public void setData3(int empnum) {
this.empnum = empnum;
}
public String[] passw = {"0123","0123","0123","0123","0123","0123","0123","0123","0123","0123","0123","0123","0123"};
public String[] getData4() {
return passw;
}
public void setData4(String[] passw) {
this.passw = passw;
}
public int login=0;
public int getData5() {
return login;
}
public void setData5(int login) {
this.login = login;
}
public String[] empname = {"Name1","Name2","Name3","Name4","Name5","Name6","Name7","Name8","Name9","Name10","Name11","Name12","Name13","Not logged in"};
public String[] getData6() {
return empname;
}
public void setData6(String[] empname) {
this.empname = empname;
}
Here is the block of code I'm having trouble with
inner class of java class TimeIn:
final Globals g = (Globals) getApplication();
final String[] empname = g.getData6();
final String[] passw = g.getData4();
public void onClick(View v) {
i = 0;
String empname = edit2.getText().toString();
int getemn = Integer.parseInt(edit.getText().toString());
if (i == 0 && h == 0) {
g.setData3(getemn);
g.setData6(String[getemn], empname); // This one line right here won't compile, I have tried different combinations but have had 0 luck
i = 1;
h = 1;
}
}
I have no problems getting and using a String array, this is how it works to get
an array value and compare it to a string:
public void onClick(View v) {
i = 0;
String getemp = edit2.getText().toString();
int getemn = Integer.parseInt(edit.getText().toString());
if (i == 0 && getemp.equals(passw[getemn])) { // All of this works perfectly
g.setData3(getemn);
g.setData5(0);
tfone.setText("Empoyee " + getemn);
tftwo.setText("Logged in");
i = 1;
}
if (i == 0 && getemp != (passw[getemn])) {
tfone.setText("No matches found");
edit2.setText("Not logged in");
i = 1;
}
}
So I know this line of code is wrong:
g.setData6(String[getemn], empname);
but for
the life of me I can't figure out how it should be written, the only error hint is I
get from hovering over the line-
array type expected; found 'java.lang.String'
Anyone know what I'm doing wrong?
In Global class, you declare the method with one parameter
public void setData6(String[] empname) {
this.empname = empname;
}
but when you call, you put 2 parameters g.setData6(String[getemn], empname);
You should remove one parameter
or add another method with 2 parameters in Globals class
Also
You are wrong in here
...
String empname = edit2.getText().toString();
int getemn = Integer.parseInt(edit.getText().toString());
...
g.setData6(String[getemn], empname); // This one line right here won't compile, I have tried different combinations but have had 0 luck
The setData6 function now require 2 parameters, one is String array and the other is String
but the way you put the String array to the function is wrong
Here is a simple example that show how to pass the String array to function
public class Test {
public static void setData6(String[] empnameList, String empname) { // with the `String array` you should declare the variable name like `empnameList` or `arrEmpname` NOT `empname` because `empname` make confusing when you read code
this.empnameList = empnameList;
this.empname = empname;
}
public static void main(String[] args) {
String[] strArray = new String[]{"Name1","Name2","Name2"};
String empName = "Na";
setData6(strArray,empName); // call method with 2 parameters here
}
}
Hope this help
Solved!! it turns out I had to modify my setter part of my Globals class, so this first part (the getter method) in the Globals class is correct:
public String[] compname = {"Manager's company", "Company2", "Company3", "Company4", "Company5", "Company6", "Company7", "Company8", "Company9", "Company10", "Company11", "Company12", "Company13", "Not punched in"};
public String[] getData7() {
return compname;
}
I had to change the getter part of my Globals class to this:
public int setcmpn = 0; // <-- Edited, this should equal some integer value
public void setData7(int setcmpn, String compname) { // removed [] from 2nd argument
this.setcmpn = setcmpn;
this.compname[setcmpn] = compname; // added in [] after array's name and fill it with the first argument from setData7 method
}
And to set the value of the desired index from any class just use:
Globals g = (Globals) getApplication();
g.setData7(getemn, getemp);
where getemn is an integer and getemp is a string.

How to Insert ArrayList data to the DataBase

Im try to insert data into Database using ArrayList.there is a Erro msg.
That is my Custmer.class method. this is what i got from when i going to pass ArrayList into another class.
incompatible types: ArrayList<String> cannot be converted to ArrayList<Inquiries>
I want to know how to do this using correct Using OOP concept
public void passingMsg(ArrayList<Inquiries> arrlist){
try {
System.out.println("Method "+arrlist);
String sq = "INSERT INTO Inquiries (name,mail,tp,msg)VALUES(?,?,?)";
PreparedStatement pr = con.prepareStatement(sq);
for(int i=0;i<arrlist.size();i++){
pr.setString(1,arrlist.get(i).getName());
pr.setString(2,arrlist.get(i).getMail());
pr.setString(3,arrlist.get(i).getTp());
pr.setString(4,arrlist.get(i).getMsg());
}
pr.executeQuery();//executeBatch();
} catch (SQLException ex) {
}
}
and this is how i get values from user
String name = txtName.getText();
String mail = txtEmail.getText();
String tp = txtTp.getText();
String msg = txtMsg.getText();
ArrayList<String> arrInq = new ArrayList<String>();
arrInq.add(name);
arrInq.add(mail);
arrInq.add(tp);
arrInq.add(msg);
Custmer c =new Custmer();
if( c.passingMsg(arrInq)){
try {
JOptionPane.showMessageDialog(this, "Successs!!");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Unsuccesss!!");
e.printStackTrace();
}
}
and this is my Inquiries.class :
public class Inquiries {
private String name;
private String mail;
private String tp;
private String msg;
public Inquiries(String name,String mail,String tp,String msg){
this.name = name;
this.mail = mail;
this.tp = tp;
this.msg = msg;
}
//
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getTp() {
return tp;
}
public void setTp(String tp) {
this.tp = tp;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
Can Some one please explain whats wrong with this. please ?
Reason For Error
This was simply telling you that your types were incompatible for the operation you were trying to perform. In your passingMsg() method, you have its header as: public void passingMsg(ArrayList<Inquiries> arrlist). However, inside your "how i get values from user" area, which I will now refer to as "2nd Snippet", you have your method call declared as: if( c.passingMsg(arrInq)). This means that you are implying that your parameter being passed, arrInq in this case, is of the type ArrayList<Inquiries>, but it's not. It's being initialized in your 2nd Snippet as: ArrayList<String> arrInq = new ArrayList<String>();
Simple Fix
I take no responsibility for this code; use at your own risk. To fix this, you would want to change that entire 2nd Snippet to something similar to the following:
String name = txtName.getText();
String mail = txtEmail.getText();
String tp = txtTp.getText();
String msg = txtMsg.getText();
ArrayList<Inquiries> arrInq = new ArrayList<Inquiries>();
arrInq.add(new Inquiries(name, mail, tp, msg));
Custmer c = new Custmer();
try {
c.passingMsg(arrInq);
JOptionPane.showMessageDialog(this, "Successs!!");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Unsuccesss!!");
e.printStackTrace();
}
You would also want to change the method header to either return a boolean, or fix it up a little bit to actually throw the exception. Such as:
public void passingMsg(ArrayList<Inquiries> arrlist) {
System.out.println("Method " + arrlist);
String sq = "INSERT INTO Inquiries(name,mail,tp,msg) VALUES(?,?,?)";
PreparedStatement pr = con.prepareStatement(sq);
for (Inquiries inquiries : arrlist) {
pr.setString(1, inquiries.getName());
pr.setString(2, inquiries.getMail());
pr.setString(3, inquiries.getTp());
pr.setString(4, inquiries.getMsg());
}
pr.executeQuery();//executeBatch();
}
Let's talk in O-O-P way.
Here Inquiries is your model, model is nothing but simple class that has instance members and public methods to get and set value of model's instance variable.
Generally we put all database related operations code in their respective models.
e.g. I have model "Model" which typically maps to database table say it as "TableModel" ,I would do something like this:
public class Model{
private int id;
private String attr;
//other properties of the model
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
//other getters and setters
//here we write methods to performs database operations
public void save(){
//use "this" to get properties of object
//logic to save to this object in database table TableModel as record
}
public void delete(int id){
//logic to delete this object i.e. from database table TableModel
}
public Model get(int id){
//retrieve record from table TableModel with this id
}
//other methods to get data from database.
}
Now question is how I can use this in some another class. Let's say I have list of Model objects and I wish to insert them in to database.I will do it something like this:
public class AnotherClass{
public void someMethod(){
//create list of models objects e.g. get them from user interface
ArrayList<Model> models=new ArrayList<>();
for(int i=0;i<3;i++){
Model model=new Model();
model.setId(i);
model.setAttr("attr"+i);
models.add(model);
}
SomeOtherClass obj=new SomeOtherClass();
obj.insert(models);
}
}
public class SomeOtherClass{
//other code above.....
//my method that inserts each Model object in database
//Note: this is sample method , you should do it in optimized way
// e.g. batch insert
public void insert(ArrayList<Model> models){
for(Model myModel:models){
myModel.save();
}
}
//other code below.....
}
You are using the wrong type parameter for the ArrayList. Instead of ArrayList<String> you need ArrayList<Inquiries>. To fix the problem, you should remove this code ...
ArrayList<String> arrInq = new ArrayList<String>();
arrInq.add(name);
arrInq.add(mail);
arrInq.add(tp);
arrInq.add(msg);
... and replace it with this code:
ArrayList<Inquiries> arrInq = new ArrayList<Inquiries>();
arrInq.add(new Inquiries(name, mail, tp, msg));

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)

Categories

Resources