Having trouble with accessing array data from one class to another - java

I am having some trouble with passing data of an array from one class to the next.
edits
I am now no longer getting the error, and my code compiles, but as I had been warned, I got null for every element of the array. Now that I have taken out the static modifiers though, it still gives me null. I have also updated the code.
Here is the class where the array is created.
public class AssignSeat {
String[] arrangement = new String[12];
public void SeatStart() {
arrangement[0] = "Collins";
arrangement[2] = "Faivre";
arrangement[3] = "Kinnard";
arrangement[6] = "Morgans";
arrangement[7] = "Rohan";
arrangement[8] = "Shatrov";
arrangement[9] = "Sword";
arrangement[11] = "Tuckness";
System.out.format("%-15s%-15s%n", "seat", "passenger");
for (int i=0; i<arrangement.length; i++) {
System.out.format("%-15s%-15s%n", i+1, arrangement[i]);
}
}
public String[] getArrangement() {
return arrangement;
}
public void setArrangement(String[] arrangement) {
this.arrangement = arrangement;
}
}
and here is the method trying to access the information. It is specifically the for loop that I need help with so Ignore other areas where there are mistakes. Thank you.
public void actionPerformed(ActionEvent event) {
Scanner scanner = new Scanner(System.in);
AssignSeat seat = new AssignSeat();
if(event.getSource() instanceof JButton){
JButton clickedButton = (JButton) event.getSource();
String buttonText = clickedButton.getText();
if (buttonText.equals("first class")) {
entername.setVisible(true);
seatnum.setVisible(true);
confirmed.setVisible(true);
inputline.setVisible(true);
outputline.setVisible(true);
if ((seat.arrangement[1] == null)) {
System.out.println(seat.arrangement[0]);
System.out.println(seat.arrangement[2]);
two.setForeground(Color.green);
}
} else if (buttonText.equals("coach")) {
//System.out.println("so does this!");
entername.setVisible(true);
seatnum.setVisible(true);
confirmed.setVisible(true);
inputline.setVisible(true);
outputline.setVisible(true);
if ((seat.arrangement[4] == null)) {
five.setForeground(Color.green);
}
if ((seat.arrangement[5] == null)) {
six.setForeground(Color.green);
}
if ((seat.arrangement[10] == null)) {
eleven.setForeground(Color.green);
}
}
}
}

The problem lies in the fact that the array was declared as static, but the initialization code for it is in the constructor. Remove all the static modifiers in the original code, and replace this part:
if (AssignSeat.getArrangement()[1].equals("null"))
With this:
AssignSeat assign = new AssignSeat();
if (assign.getArrangement()[1] == null)
Also notice that "null" is not a null value, use null (without quotes) for that.
A different approach would be to leave the array as an static member, but initialize it statically, like this:
private static String[] arrangement = new String[12];
static {
arrangement[0] = "Collins";
arrangement[2] = "Faivre";
arrangement[3] = "Kinnard";
arrangement[6] = "Morgans";
arrangement[7] = "Rohan";
arrangement[8] = "Shatrov";
arrangement[9] = "Sword";
arrangement[11] = "Tuckness";
}
In that case, this would work:
if (AssignSeat.getArrangement()[1] == null)
But I still believe that making the array static is going to be problematic if several instances of the class happen to be modifying its contents.

Replace
if (AssignSeat.getArrangement()[1].equals("null"))
with
if (AssignSeat.getArrangement()[1] == null)
If the value is null, you can't invoke methods (like equals) on it. You need to compare the value directly to null, which is a constant rather than a string.

Ok, I'm a bit confused as to what you're trying to do in the first class. You are initializing a static array from an instance method...
In other words, the String values in the array will be null until you call SeatStart from an instance of the class.
Try to initialize the String array from the static constructor for AssignSeat to make sure it has been initialized before you use it: http://www.snippetit.com/2009/05/java-static-variables-static-methods-and-static-constructor/

You are trying to use an attribute of a class, without instantiating the object first. Until you call a default/user-defined constructor, there is no memory dedicated to the attribute of that object.
Even though you manage to call the method you are using a static method, which can be called without an instance of the object being required.
Create a constructor for the object (or use a default constructor) and then you will be able to access your attribute because your object will be on the heap and have memory allocated for the string[].

Simply define the SeaStart as an Array.
public String[] SeatStart() {
arrangement[0] = "Collins";
arrangement[2] = "Faivre";
arrangement[3] = "Kinnard";
return arrangement;
}
For convinience, make a new array to copy the array from AssignSeat class. Then retrieve the value from that array.
public void actionPerformed(ActionEvent event) {
AssignSeat seat = new AssignSeat();
String[] foo = seat.SeatStart();
System.out.println(foo[0]);
System.out.println(foo[1]);
System.out.println(foo[2]);
}
Though you can acces it also with:
System.out.println(seat.SeatStart()[0]);
The result would be:
Collins
null
Faivre
and that 'null' is because apparently you haven't allocate a value for arrangement[1] :-)
But in the end, it works.

Related

need to store value after passing to method for latter check

I am passing few values to mail method for sending the details like below
private static String getTeam(String Team, List<String> prioritys1, String number,String description
) {
StringBuilder builder1 = new StringBuilder();
for (String v : prioritys1) {
if ( v == "1") {
Integer cnt1 = count1.get(new Team(Team, v,number,description));
if (cnt1 == null) {
cnt1 = 0;
}
else
if (cnt1 !=0){
cnt1 = 1;
mail1(Team,v,number,description);
}}
else
if ( v == "3") {
Integer cnt1 = count1.get(new Team(Team, v,number,description));
if (cnt1 == null) {
cnt1 = 0;
}
else
if (cnt1 !=0){
cnt1 = 1;
mail1(Team,v,number,description);
}}
}
return builder1.toString();
}
I tried to store in arrays but it didnt worked.
I after pass above parameters, i need to store the value of the number. i need to store the number so that next time while passing the parameters i need to check first whether the number is already passed or not if not then only i need to pass to mail.
can any one help on this
With this code very complicated understand what you are doing. But if you need check value that already been processed store it outside of the method. Create global class variable:
public class className {
private final List<String> ARRAY = new ArrayList<>(); // global variable
public void yourMethod(String value) {
if (!ARRAY.contains(value)) {
mail(value);
ARRAY.add(value);
}
}
}
I dont know your case and I can not get better example.
You need to store the value in a "class level" variable. Whether the variable type needs to be static or instance will depend on your implementation of the method.
If you can post a sample code, we can help further.
You need to compare with 2 equals and not 1
Instead of
if( Team = A )
you need this way
if( Team == A )
Using Team = A, your saying that every time your code reaches that line it will equal Team to A.

Editable 2D Array

I want to create a 2D Array that creates a mini seating chart of an airplane. So far, I've gotten it to successfully print out something that looks like this:
1A(0) || 1B(0) || 1C(0)
2A(0) || 2B(0) || 2C(0)
3A(0) || 3B(0) || 3C(0)
4A(0) || 4B(0) || 4C(0)
The zeroes represent an empty seat, and the number one is used to represent an occupied seat.
I first created the program with arrays that were class variables for a First Class, but I wanted to make this program usable for an Economy Class section. The only difference between the two sections is the size of the array so I edited my code to look like this:
public class Seating
{
private int FIRSTCLASS= 12;
private int ECONOMYCLASS= 240;
private int occupied, column;
private String[][] seatchart;
private int[][] seatlist;
private String[][] namelist;
private String name;
public String customer;
public Seating(String seatclass)
{
seatclass.toUpperCase();
if (seatclass.equals("FIRSTCLASS"))
{
seatchart= new String[FIRSTCLASS/3][3];
seatlist= new int[FIRSTCLASS/3][3];
namelist= new String[FIRSTCLASS/3][3];
}
else
if (seatclass.equals("ECONOMY"))
{
seatchart= new String[ECONOMYCLASS/3][3];
seatlist= new int[ECONOMYCLASS/3][3];
namelist= new String[ECONOMYCLASS/3][3];
}
}
public void Creation()
{
for (int i=0; i< seatlist.length; i++)
{
for (int j=0; j<seatlist[i].length; j++)
{
seatlist[i][j]= 0 ;
}
}
I get an null pointer exception error around for (int i=0; i< seatlist.length; i++)
How can I fix this error?
Thanks in advance!
The problem is with this line:
seatclass.toUpperCase();
Replace it with:
seatclass = seatclass.toUpperCase();
I think you are creating the class with a string like "firstclass" rather than "FIRSTCLASS" right? Those aren't the same strings and just invoking the toUpperCase method on the string without assigning the result to a variable to then be tested means nothing happens.
Then since none of your if conditions are met, the arrays are not initialized and a null pointer exception is thrown when Completion() is called.
I'm not sure if you are new to java programming, but I wanted to add a few recommendations to your class:
public class Seating {
private static int FIRSTCLASS= 12; // Make these constants static since they pertain to all
private static int ECONOMYCLASS= 240; // instances of your class. That way there is exactly on
// copy of the variables, which is more memory efficient.
private int occupied;
private column; // Okay but Java convention is to declare each member variable on its own line
// increases code readability.
private String[][] seatchart;
private int[][] seatlist;
private String[][] namelist;
private String locSeatClass;
private String name;
public String customer; // Okay but better to leave this private and then provide getter and
// setter methods to provide access to this string. Much easier to track
// down who is changing its value in your code.
public Seating(String seatclass) { // Java convention is to place the opening bracket here not
// on the next line.
// Make sure that seatClass is not null or empty. NOTE: This is a neat trick for
// simultaneously checking for both null and empty strings in one shot. Otherwise, you have
// you have to check for null and then examine the string's length which is more code.
if ("".equalsIgnoreCase(seatClass) {
throw new IllegalArgumentException("Seat class undefined.");
}
// Store the seat class in a member variable for use. Could also be a local variable.
// My original solution is problematic because it changes the original value of the seat
// class that was passed into the constructor (you might want that information).
locSeatClass = seatclass.toUpperCase();
if (locSeatClass.equals("FIRSTCLASS"))
{
seatchart= new String[FIRSTCLASS/3][3];
seatlist= new int[FIRSTCLASS/3][3];
namelist= new String[FIRSTCLASS/3][3];
}
else if (locSeatclass.equals("ECONOMY")) {
seatchart= new String[ECONOMYCLASS/3][3];
seatlist= new int[ECONOMYCLASS/3][3];
namelist= new String[ECONOMYCLASS/3][3];
}
else {
// Throw an exception if someone passes in an unknown seat class string.
throw new IllegalArgumentException("Unknown seat class detected.")
}
}
public void creation() { // NOTE: Java convention is to begin method names with a lower
// case letter.
// This method is unnecessary. Arrays of integers are initialized with an initial value
// of zero by default. However, if you want to make your class reusable, you could change
// change the name of the this method to clear, which would allow you to clear the arrays of
// an existing object.
for (int i=0; i< seatlist.length; i++)
{
for (int j=0; j<seatlist[i].length; j++)
{
seatlist[i][j]= 0 ;
}
}
}
The only way that line of code can generate a NPE is if seatlist is null. Unless you assign null to seatlist somewhere else in your class, the only way it can be null is if the argument that you pass to the Seating constructor does not match either "FIRSTCLASS" or "ECONOMY". Check your call to the constructor. Also, you might want to just use seatclass.equalsIgnoreCase().
You should modify your constructor to at least warn about that eventuality, since it is vital to the proper operation of the class that any instances of Seating have valid seatlist and namelist arrays.

Return value from method java

I have a program in java that I wrote to return a table of values. Later on as the functions of this program grew I found that I would like to access a variable within the method that isn't returned but I am not sure the best way to go about it. I know that you cannot return more than one value but how would I go about accessing this variable without a major overhaul?
here is a simplified version of my code:
public class Reader {
public String[][] fluidigmReader(String cllmp) throws IOException {
//read in a file
while ((inpt = br.readLine()) != null) {
if (!inpt.equals("Calls")) {
continue;
}
break;
}
br.readLine();
inpt = br.readLine();
//set up parse parse parameters and parse
prse = inpt.split(dlmcma, -1);
while ((inpt = br.readLine()) != null) {
buffed.add(inpt);
}
int lncnt = 0;
String tbl[][] = new String[buffed.size()][rssnps.size()];
for (int s = 0; s < buffed.size(); s++) {
prse = buffed.get(s).split(dlmcma);
//turns out I want this smpls ArrayList elsewhere
smpls.add(prse[1]);
//making the table to search through
for (int m = 0; m < prse.length; m++) {
tbl[lncnt][m] = prse[m];
}
lncnt++;
}
//but I return just the tbl here
return tbl;
}
Can anyone recommend a way to use smpls in another class without returning it? Is this perhaps when you use a get/set sort of setup?
Sorry if this seems like an obvious question, I am still new to the world of modular programming
Right now you have this tbl variable. Wrap it in a class and add the list to the class.
class TableWrapper {
// default accessing for illustrative purposes -
// setters and getters are a good idea
String[][] table;
List<String> samples;
TableWrapper(String[][] table, List<String> samples) {
this.table = table;
this.samples = samples;
}
}
Then refactor your method to return the wrapper object.
public TableWrapper fluidigmReader(String cllmp) throws IOException {
// your code here
String tbl[][] = new String[buffed.size()][rssnps.size()];
TableWrapper tw = new TableWrapper(tbl,smpls);
// more of your code
return tw;
}
Then later in your code where you were going
String[][] tbl = fluidigmReader(cllmp);
You instead go
TableWrapper tw = fluidigmReader(cllmp);
String[][] tbl = tw.table;
List<String> smpls = tw.samples;
If you had used a dedicated class for the return value (such as the TableWrapper mentioned in another answer), then you could add additional fields there.
That is the good thing about classes - they can be extended. But you cannot extend String[][] in Java.
You can set a field, instead of a local variable, which you can retrieve later with a getter. You want to avoid it unless it is needed, but in this case it is.
You can use class(Inside Reader class) variable for this. But make sure that it's read/write is synchronized

Java: Copy Constructor not going as planned

I have a bit of a problem. I'm making a Finite Automata checker.
Given an input, and the DFA, does it end on a accepting state.
My problem is creating a new DFA_State from another's target.
DFA_State state0, state1, curr_state, init_state, temp; //fine, I think
state0 = new DFA_State();
state1 = new DFA_State();
state0 = new DFA_State("State 0",true, state0, state1); //fine, I think
init_state = new DFA_State(state0); //fine, I think
but, this bit is throwing up problems.
temp = new DFA_State(curr_state.nextState(arr1[i]));
*
*
curr_state = new DFA_State(temp);
Thanks for any help,
Dave
Edit:
God I was retarded when I did this, AFAIK, I just wasn't thinking straight, added methods to set the values to the DFA_State object.
//in DFA_State class
public void set(DFA_State on_0, DFA_State on_1, Boolean is_accepting, String name){
this.on_0 = on_0;
this.on_1 = on_1;
this.is_accepting = is_accepting;
this.name = name;
}
//in main
DFA_State state0, state1, curr_state;
state0 = new DFA_State();
state1 = new DFA_State();
state0.set(state0, state1, false, "State 0");
state1.set(state1, state0, true, "State 1");
curr_state = state0;//initial state
//iterate across string input changing curr_state depending on char c
curr_state = getNextState(c);
//at end
if(curr_state.isAccepting())
System.out.println("Valid, " + curr_state.getName() + " is accepting);
else
System.out.println("Invalid, " + curr_state.getName() + " is not accepting);
In that first line, you declare the variables state0, state1, curr_state, init_state and temp as being variables of type DFA_State. However, that only declares them, they are not yet initialized. The next few lines are all okay. Second line creates a state without anything in it and assigns it to state0, so does the third line for state1. Fourth line overwrites your previous state0 assignment with a new DFA_State that has actual contents. Fifth line creates a DFA_State as a copy of state0 and assigns it to init_state.
Assuming there's nothing in between this and the first line of your second code block, now you'll get a problem. You're assigning temp with a new DFA_State that uses a copy-constructor with an argument relying on curr_state. But at that point, that variable hasn't been initialized yet. Just because it was declared doesn't mean it has somehow already been structured in memory. When you call nextState on it, there's simply no variable to resolve this to. Don't expect to get something like a pointer that will eventually point to a part of what you put in curr_state.
I'm just guessing, but from your code style I'd say you have a background in C or C++. Look into the differences between those languages and Java. If possible, I'd also advise you to make your DFA_State class immutable, since this is more reliable and will avoid mistakes. That means getting rid of the no-args constructor. Here's a reworking of it (not actually compiled, might contain errors):
package foundations.of.computing;
/**
*
* #author Kayotic
*/
class DFA_State {
private final String state;
private final DFA_State on_0;
private final DFA_State on_1;
private final boolean isAccepting;
//private DFA_State dummy;
public DFA_State(DFA_State arg) {
//this(arg.is_accepting(), arg.on0(), arg.on1());
state = arg.get_name();
isAccepting = arg.is_accepting();
on_0 = arg.on0();
on_1 = arg.on1();
}
public DFA_State(String name, Boolean accepting, DFA_State on0, DFA_State on1) {
state = name;
isAccepting = accepting;
on_0 = on0;
on_1 = on1;
}
public String get_name(){
return state;
}
public Boolean is_accepting() {
return isAccepting;
}
public DFA_State on0() {
return on_0;
}
public DFA_State on1() {
return on_1;
}
public DFA_State nextState(char i) {
if (i == '0') {
return on0();
} else if (i == '1') {
return on1();
} else {
System.out.println("Error with input");
return null;
}
}
}
Even if you can't make the instance variables final, it's best to at least make them private, since you already have methods for getting them.
There are better memory representations of DFAs than the object-oriented.
You should use a simple lookuptable:
int[] table = new int[vocabularyCount][stateCount];
Every State and every word gets a number, starting with 0.
Fill the table with the state transitions, or -1, if there is no transition. Now you just need the translation methods for the states and the words.
Heres a generic DFA algorithm:
public boolean checkSentence(String s, int[] finishes) {
// fill table
int state = 0; // assuming S0 is the start state
for (int i = 0; i < s.length(); i++) {
state = table[translate(s.charAt(i))][s];
}
for (int i = 0; i < finishes.length; i++) {
if (finishes[i] == state) {
return true;
}
}
return false;
}
The program is quite poorly written. Look at this in your FoundationsOfComputing.java:
state0 = new DFA_State();
state1 = new DFA_State();
state0 = new DFA_State("State 0",true, state0, state1);
You essentially created 3 instances of state - two instances which are not initialized (first two lines in your code) - all their instance variables are null.
Then you create the third instance, which you point to the first two uninitialized ones, and assign it to state0 variable. Please note, at this point, it is only the value of the variable that changes, not the values you passed in the DFA-State constructor!!! So, what you now have in state0 is a state that points to two uninitialized states.
Now let's look at the code further down in the FoundationsOfComputing.java:
while (i < arr1.length) {//loops through array
System.out.println(i + ". scan shows " + arr1[i]);
temp = new DFA_State(curr_state.nextState(arr1[i]));
System.out.println(" "+curr_state.get_name()+ " moves onto " + temp.get_name());
curr_state = new DFA_State(temp);
i++;
}
I am guessing this throws NullPointerException - that code moves to the on_0 state of state0 - which is a state that has not been initialized (all it's instance variables are null), so in the following pass of the loop, when it calls curr_state.nextState(whatever), it would return null and you are trying to pass that to the copy-constructor which would result in NPE.
Ok so we know this is homework. Let's do this instead of telling you the answer let's try and work through it on your own. If you are seeing a NullPointerException (NPE). Grab the second line of the exception:
java.lang.NullPointerException: null
at com.blah.blah.SomeObject.someMethod(SomeArgumentType):1234 <<< here
....
That 1234 is the line number in the file that contains SomeObject. If you goto that line number you can see exactly where the NPE is being generated from. For example if line 1234 was:
this.foo = bar.indexOf("caramel");
You can easily deduce what was null. No clue? Well this can never be null so this.foo isn't the problem. If this could be null you couldn't be inside that method because this points to the instance you are currently within. Therefore, the only other statement where a variable is being dereferenced is bar so bar must be null. Let's look at your code:
temp = new DFA_State(curr_state.nextState(arr1[i]));
Say you find out the line above is tossing an exception. Well there could be several things that could be null. curr_state could be null, or arr1 could be null in which case this line would blow up. However, if arr1[i] is null or curr_state.nextState() is returning null then you won't see the NPE pointing at this line, but would be coming out of the constructor should someone try to call methods on that method parameter.
Hopefully, this will give you the tools you need to track down problems in your application by understanding exception stack traces.

Casting inner objects in java - unchecked exception

I'm having a problem with inner classes. I build an object (let's say a train) with an inner class representing states (let's say the stops of the train).
I'm trying to run this code:
private void CustomObjectBuilder (String [] origin) {
final int array_dim = origin.length;
InnerCustomObject[] tmp_bin = new InnerCustomObject[array_dim];
for (int ii = 0; ii < array_dim; ii++) {
String debug = extractData(origin[ii]);
tmp_bin[ii].setData(debug);
}
}
It compiles just just fine but at runtime I get a null object exception.
What am I doing wrong?
Here you can finde the original code:
public class CustomObject {
InnerCustomObject [] stops;
public class InnerCustomObject {
String name, station, schedTime, depTime, schedRail, depRail;
public void setData (String origin) {
this.station = origin;
}
}
}
Edit: I solved by calling
CustomObject.InnerCustomObject ico = new CustomObject(). new InnerCustomObject();
why it needs to be so verbose?
Well, the most immediate thing I notice is you don't populate tmp_bin[] with any objects after you declare it. When you first create an array, all it contains are nulls.
So when you do this in your loop:
tmp_bin[ii].setData(debug);
There is nothing to invoke setData() on, resulting in the exception.
Re edit: you can just do
InnerCustomObject ico = this.new InnerCustomObject();
since you're creating them within your outer CustomObject class's CustomObjectBuilder() instance method.
InnerCustomObject[] tmp_bin = new InnerCustomObject[array_dim];
declares an array of array_dim elements but all are null. Then this
tmp_bin[ii].setData(debug);
won't work.
No problem with inner classes only with an object that is null (=NPE) so you cannot call the method setData().
In your loop you have to create new instance of InnerCustomObject. By new InnerCustomObject[size] you do not create new instances.

Categories