Pointer with public array - java

Here is the thing- my Main method only calls InitGui. Inside the whole class (basically the whole file, i have the InitGui method and a few public static gui objects. One of the objects is actuall an array
public static JButton Keys[] = null;
And I have a method called placeKeys that gets the location for each JButton "Keys" and places it on the panel. The whole code works when I do not use this method, basically instead of for i=0 to whatever, I want just call placeKey(arguments here...) instead of
for each jButton to be placed like this
for i=0 to whatever
Keys[i] = new JButton(jBStringArray[i]);
Keys[i].setLocation(2 + i*kSize,2+row*50);
Keys[i].setSize(50, kSize);
keyboardPane.add(Keys[i]);
I have the method written down but it reports a pointer error at the placeKeys when it tries to access the Keys[] , meaning the first line of the method
Hope you understood me

Before your for loop (either when you declare it, or, if you rely on the null check, just before the for loop) you need to create the array with Keys = new JButton[whatever+1];. Oh and please start your variable names with a lowercase letter - it's the universally-accepted thing to do.

//assuming jBStringArray is already defined here
public static JButton Keys[] = new JButton[jBStringArray.length];

Related

java get value from JTextField and set it as BigInteger

I have two classes in a package: firstClass and secondClass.
I created a textfield in firstClass, let's assume it's txtStringNumber.
I created a method in firstClass to get txtStringNumber value, like this:
public String getStrNumber(){
String strNumber = txtStringNumber.getText();
return strNumber;
}
I must pass it to secondClass as String and put the strNumber as BigInteger value.
In second class I created a method to get value of txtStringNumber from firstClass, like tis:
public static String theNumbers(){
firstClass f = new firstClass();
return f.getStrNumber();
}
public static String strAllNumbers = theNumbers();
When I print strAllNumbers in secondClass, it prints the correct value. Then I add this:
public static BigInteger bigAllNumbers = new BigInteger(strAllNumbers);
In my mind, it should works. But in real, it doesn't. Error occurs.
So I check the error, there said:
throw new NumberFormatException("Zero length BigInteger");
I guess BigInteger accept strAllNumbers as empty.
But just like I already said, when I print strAllNumbers directly without set it to BigInteger, it returns the correct value.
What's wrong here and how can I fix this?
You're creating a firstClass object, f, and getting a String from its textfield before anybody ever has a chance to enter text in it. So no surprise that it's empty.
Solution: Don't do this! Only get the text after something that makes sense has been entered.
I'm guessing that you have two firstClass objects, one displayed, and a second one created in this method, and are guilty of magical thinking that changes to the displayed object will be reflected in the newly created one, but that's not how programming works. Instead pass a valid reference of the displayed object to the other object that needs it.
You're creating a new instance of firstClass in the theNumbers method (firstClass f = new firstClass();), it's very unlikely the the value of the text field has been set to anything useful (especially by the user)
You either need to supply a means of firstClass to pass the value from the text field to secondClass, probably via a setter of some kind (this is classic producer-consumer pattern) or set up a mechanism for firstClass to notify secondClass when the value changes and then have secondClass retrieve that value (this is a class observer pattern).
In any case, you should not be creating a new instance of these classes, you need to create them and then pass these instance to which ever one is going to act as the controller...

Object in Object Array doesn't want to store my data

fairly new to this language. Long time lurker, first time question asker.
In my program, I load a bunch of strings from a text file and then pass all of that information inside of a String array to a program that takes the data point by point (it comes in a reliable pattern) and assigns it to variables inside a class.
I use this loop to create the objects.
Gladiator[] gladiator = new Gladiator[(match.contestants)];
for ( int a = 0; a < match.contestants; a++) {
gladiator[a] = new Gladiator();
gladiator[a].populategladiators(parsedInfo,a);
}
Gladiator class full of public final variables which are defined in the method populategladiators. The syntax is as follows:
this.name = parsedInfo[0+mod][0];
this.culture = parsedInfo[1+mod][0];
this.background = parsedInfo[2+mod][0];
etc.
At the moment, I only load two gladiators and it seems like maybe both are being set at once with both pass throughs? Anyone have any thoughts on this?
Also, in another method in class Gladiator, should I be able to call this.name and be okay to get data about the object I specified when calling the method?
Edit: Trying to make the code look right. Giving up since there isn't much.
2nd Edit: Example of variable declaration in gladiator class:
public static String name;
public static String culture;
public static String background;
I had my variables set as static, thus it wasn't allowing me to set individual variables for the objects. I just didn't understand what the static keyword meant.

Cannot refer to a non-final variable inside an inner class, then null error

I have little problem with inner methods in Java. In line:
dReservation[i].dispose();
I have an error:
Cannot refer to a non-final variable dReservation inside an inner class defined in a different method
I have read many threads in forum, but there are two solutions of that problem which didn't works:
Cannot refer to a non-final variable inside an inner class defined in a different method
Cannot refer to a non-final variable i inside an inner class defined in a different method
Why a non-final "local" variable cannot be used inside an inner class, and instead a non-final field of the enclosing class can?
I have tried to set JDialog[] dReservation as global field for my class (GUIShowReservations). Then my error disappears, but in the inner method (actionPerformed) instead of dReservation[i] is null.
Just the same history is when I set JDialog[] dReservation as final field. It is null.
bShowReservations = new JButton("Show Reservations");
bShowReservations.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
JDialog[] dReservation = new JDialog[10000];
for(Object o: reservations)
{
rez = (Reservations)o;
reservation.append(rez.getGroup());
dReservation[i] = new JDialog();
dReservation[i].setSize(400, 300);
dReservation[i].setLocationRelativeTo(null);
dReservation[i].setVisible(false);
dReservation[i].setLayout( null );
dReservation[i].setTitle("Edition");
bEditAccept = new JButton("Edit");
bEditAccept.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
rez.setTeacher(cEditTeacher.getSelectedItem().toString());
dao.update(rez);
dReservation[i].dispose();
}
});
bEditAccept.setSize(160, 24);
bEditAccept.setLocation(10, 200);
dReservation[i].add(bEditAccept);
}
}
});
Could you help me? I want to see a proper JDialog in my inner method instead of null.
It's hard to answer, because the code is incomplete, and the above code doesn't make much sense. I'll explain what it actually does, because I don't think that it does what you want it to do.
The code creates a single button labeled "Show Reservations". When this button is clicked, an array of ten thousand (!) JDialog instances is created (why?). All these dialogs are null.
Then, a loop is done, iterating on the reservations. For each reservation, a new JDialog is created, containing a new button named "Edit", which closes the dialog when clicked.
And the last one of these dialogs is stored in the giant array, at the index i. All the other ones are created for nothing, since they're replaced by the next one, at the same index in the array.
So at the end of the loop, you have created one dialog for each reservation, but stored only one of them in a giant array. And since this giant array is a local variable, nobody can use this dialog anyway, because the array and its unique dialog goes out of scope. So your action listener does the equivalent of the following one, but in a very slow and inefficient way:
bShowReservations.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
for (Object o: reservations) {
rez = (Reservations) o;
reservation.append(rez.getGroup());
}
}
}
Also not that your code is full of bad practices. You're not using generic collections, you're setting sizes on buttons, you're not using a layout manager and instead set arbitrary locations...
If you tell us what the code should do, we could help you make it do that.

Java; null pointer on newly created array with user-defined length

So, right after the public class declaration, I've declared an array as follows:
public String[] accept;
From here then, I'm looking to take user input to see how long this array should be - and following this, we'd enter into a loop to populate the array with Strings. I put the following into a method;
if (scanner.hasNextInt()) {
wcount = scanner.nextInt();
//create the array.
String accept[] = new String[wcount];
}
System.out.println(accept.length);
But unfortunately, no nice. Java returns with;
Exception in thread "main" java.lang.NullPointerException
Obviously, attempting to go straight into a for loop to populate the array, will also give the same results. At first glance, I'm assuming this has something to do with it being initialised as a public array outside of the method itself - but I'm honestly not too sure. Can anyone lend a hand on this?
You are declaring a new array in your if block, which is hiding your previously declared array. When the block exits, the variable goes out of scope and you get an NPE attempting to access the (unchanged) instance variable. Change your code to actually initialize your instance variable like so:
if (scanner.hasNextInt()) {
wcount = scanner.nextInt();
//create the array.
accept = new String[wcount];
}
System.out.println(accept.length);
You are recreating a new accept [] as local variable. Change your loop as below
if (scanner.hasNextInt()) {
wcount = scanner.nextInt();
//create the array.
accept = new String[wcount];
}
Change String accept[] to just accept within the if statement, you are redeclaring a new one within that scope, leaving the old one null.
String accept[] = new String[wcount];
declares a variable, and stores the reference to the new string array into it.
You probably want to use the previously declared variable instead. To do that, simply use assignment expression directly:
accept = new String[wcount];

Elements in java ArrayList taking up two places

I have made a LinkedList to store State objects which is a class I have created. I can add states to the list as expected, but whenever I try the size() method on the list it always returns twice the amount of elements I have added. Why is it doing this and how can I then use the get(n) method if each element has 2 values of n?
Here's the code used to create and add to the list:
static ArrayList<State> stateTable = new ArrayList<State>();
stateTable.add(new State(new Item(0,0)));
I will add that the adding to the list is done inside the constructor for State objects so that all created States get put in the stateTable.
Thanks
I will add that the adding to the list is done inside the constructor
for State objects so that all created States get put in the
stateTable.
If you already add the states to your list inside the constructor and additionally have the line
stateTable.add(
new State(new Item(0,0)) // <= first time inside new State(...)
); // <= second time explicitely in this line
then you are indeed adding it twice.
search for .add( and make sure you are not calling it in multiple places.
If your ArrayList is not marked as private mark it as private.
If you return your ArrayList from a method do return a read-only version via: Collection.unmodifiableList(stateTable);
If you load the data in one method or the constructor and do not intend to do it anywhere else than do it something like:
private static final List<State> stateTable;
static
{
final List<State> temp;
temp = new ArrayList<State>();
temp.add(new State(new Item(0,0)));
stateTable = Collections.unmodifiableList(stateTable);
}
Using the unmodifiableList will cause your program to crash if you add objects into it.

Categories