Can't access variables using getter - java

So hey guys, im having some trouble with a script i am writing (with a custom api and stuff)
So what i have is a main class where i use data from my GUI to edit variables in my ScriptVariables class like this:
GUI g = new GUI();
ScriptVariables sv = new ScriptVariables();
String foodNameString = g.textField.getText();
sv.setFoodName(foodNameString);
String amountString = g.textField_1.getText();
int amountInt = Integer.parseInt(amountString);
sv.setAmount(amountInt);
double healthPercentageValue = g.slider.getValue();
sv.setHealthPercentage(healthPercentageValue);
(Ps: i logged this with getter and this bit works fine)
Now in another class i try to access it AFTER that previous code is executed i do it like this:
ScriptVariables sv = new ScriptVariables();
String foodName2 = sv.getFoodName();
int amount2 = sv.getAmount();
Now the problem is when i log those vars i get null for the string and 0 for the int.
Any ideas?

You are accessing two different instances of ScriptVariables so they don't share instance variables. The fact that you have set the text and foodName properties on the first instance does not affect the new instance you create in your other class.
What you can do is either make the text and foodName properties static, or pass a reference to the first ScriptVariables instance to the second piece of code.

ScriptVariables sv = new ScriptVariables(); is creating a different instance than the one for which you previously set its fields (foodName and amount). This new instance has its foodName and amount fields still not initialized, hence the null and zero values.
Assuming your second class is ScriptVariablesAccessor, then you can include a field of type ScriptVariables in its class definition. This field would then be used to pass the previously filled instance via a constructor or a setter method.
public class ScriptVariablesAccessor {
private ScriptVariables sv;
public ScriptVariablesAccessor(ScriptVariables sv) {
this.sv = sv;
}
// or use a setter
public void setScriptVariables(ScriptVariables sv) {
this.sv = sv;
}
public void processVariables() {
String foodName = sv.getFoodName();
int amount = sv.getAmount();
// do something with foodName and amount;
}
}
Below is how you would call this class with the prepared ScriptVariables:
ScriptVariablesAccessor svAccessor = new ScriptVariablesAccessor(sv);
svAccessor.processVariables();

You created two different ScriptVariables objects.
foodNameString and amountString can be created in static, and since you are getting them from another class, you can set them to public or protected but not private , then call ClassName.amountString to get the value.
Or you can apply the Singleton Pattern.
Or just simply pass the ScriptVariables object or those strings to another class's method.

Related

Use the result set of a class method into another class method

i have a class A in which there is a method Method1, in Method1 i want to pass the "rs" to class B method. how can i do it? try different things but unsuccessful.
Note: I did not write the full method code just gave an scenario to find the solution from you.
public class A {
Resultset rs = null;
public void method1() {
this.rs = this.stmt.executeQuery(this.query);
// while (this.rs.next()) {
// int id = rs.getInt("node_Id");
// String name = rs.getString("node_Name");
// String par = rs.getString("node_Parent");
// int lvl = rs.getInt("node_Level");
// System.out.println(+id+" "+name+" "+par+" "+lvl);}
if (success == 0) {
this.conn.rollback();
} else {
System.out.println("rs" + rs);
this.conn.commit();
}
}
now i want to use the variables id,name,par,lvl in another class method like
following
public class B{
public void usage(){
//in here i want to get the varibles id,name,par,lvl
}
}
Right now, you made these variables to be local variables within method1() (which is by the way a really bad name for a method - always use names that mean something, even in examples).
Because of that, you can only pass them around, by well, passing then, such as
B someB instance = ... // however that gets created
while (this.rs.next()) {
int id = rs.getInt("node_Id");
someB.doSomethingWith(id);
That's it. But the better approach would be to have, say a class C that wraps around all the information you want to pass around.
Then instead of creating and passing the individual values, you would collect the required values, and use those to create an instance of your new C class. And then you pass that object to whatever method that is going to need it.

how to insure a certain field in a class has different and unique values in all instances in java?

I'm new to coding and I've faced this problem recently: I'm working on a class which has various fields, and I want to insure each instance of the class has a unique value for a certain field using static variables. for example, consider this class:
public class NetworkNode {
private String NodeName;
private int NodeNumber;
private boolean NodeAttraction;
....
}
in the code above, I want to insure each object created from the class NetworkNode to have a unique and different NodeNumber or in other words, no two NetworkNode objects should have the same NodeNumber field.
what are the ways to do this? thanks.
You could automatically assign a different NodeNumber to each instance if you don't care about the actual value as long as it's unique. Using static variables you could create a private static counter nextNodeNumber in your class NetworkNode:
private static int nextNodeNumber = 0;
In your constructor you could then do
public NetworkNode() {
this.NodeNumber = nextNodeNumber;
++nextNodeNumber;
...
}
This way you just have to ensure, that there is no other way to set/change NodeNumber or nextNodeNumber.
If you are using multiple Threads you would have to secure access to nextNodeNumber to prevent asynchronous access.
1 put a
static Set<String> myuniquevalues ... (for example) for each of your fields
2 in your constructor
public NetworkNode (String value1 ...)
{... check if value1 exists in myuniquevalues , and throw exceptions }
3 if your objects are deleted, you must manage it also ...
Alternative: concentrate creation of your objects in a factory, and manage unicity there.
I recommend you to do some reading about variables and what static means. To make it short, a static variable exists only "once" in your program.
For example, if you create a game, you want the variable score to be static since there will only be one instance of this variable.
In order to have each NetworkNode to have a unique and different NodeNumber, you have to construct the object like this:
public NetworkNode(String NodeName, int NodeNumber, boolean NodeAttraction){
this.NodeName = NodeName;
this.NodeNumber = NodeNumber;
this.NodeAttraction = NodeAttraction;
}
See, here, each NetworkNode will have a different value for each of the variables passed as parameters.
You will then just need to create the object in your main function or whatever like this for example:
NetworkNode myNode = new NetworkNode("node1", 0, true);
Hope it helps,

NullPointerException in while loop when trying to add new Class instances to ArrayList

The more I google this the more confused I'm getting.
I'm bringing in a list of names of unknown length with some other details in from a CSV which I then need to turn into Person objects and store in a list called people which is the instance variable for the class Club, a list of its members basically.
This is a very simplified version of something more complex I need to do in which I need to while loop through a file creating objects for each line which I then need to add to a list collection.
I keep getting a nullPointerException error when I run my code though and I'm stumped how to avoid it. I'm guessing that my variable p when I create the new object would need to change on each loop but I don't think it's possible to change variables dynamically is it?
Can't think how I can commit the object to the collection with a valid non null reference each time. Would be very grateful for any help. I've tried to cut out all the unnecessary stuff in the code below.
Thank you
//class arraylist instance variable of class "Club"
private ArrayList<Person> people;
//class constructor for Club
public Club()
{List<Person> people = new ArrayList<>();}
public void readInClubMembers()
{
//some variables concerning the file input
String currentLine;
String name;
String ageGroup;
while (bufferedScanner.hasNextLine())
{
//some lines bringing in the scanner input from the file
name = lineScanner.next();
ageGroup = "young";
Person p = new Person(); // i guess things are going wrong around here
people.add(p);
p.setName(name);
p.setAgeGroup(ageGroup);
}
}
Remove the List<Person> before people = … inside the constructor, otherwise you are declaring a new local variable people inside the constructor shadowing the field people (which is then never used). This leaves the class field uninitialized (null) and then causes the NPE.
What you want instead is initializing the field people:
public Club() {
// you can also use "this.people = …" to be explicit
people = new ArrayList<>();
}
To show the difference:
class Example {
private int myNumber;
public Example() {
myNumber = 42; // sets the field of the class
int myNumber = 1337; // declares a new local variable shadowing the class field
myNumber = -13; // accesses the object in the closest scope which is the local variable
this.myNumber = 0; // explicitly accesses the class field
}
}

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.

Casting string as a integer member, possible?

Ok my problem isnt really a serious one, im just trying to find a clever way of access/modification of class member variables. Here is the code:
public class Storage{
private int cookies= 0;
private int rolls= 0;
private int candies= 0;
private int lolipops= 0;
private int iceCreams= 0;
public void addCookies(int howMuch){ //this is the dirty way of creating method for
this.cookies = cookies+howMuch; //every member variable
}
public void addValue(String stat, int howMuch){ //i would like to do it only
//by passing the name
//of variable and then cast it as integer
//so that it would relate to my class members
int value = this.(Integer.parseInt(stat)); // <- YES i know its ridiculous
//im just trying to explain what is my aim
value = value + howMuch;
this.(Integer.parseInt(stat)) = value;
}
}
Generally i would like to access a field by passing its name to a method, read value of that member, add to it some value, and then store it. Yes i know that it easily can be done with separate methods, or even with one by using some arraylist and comparisons of member names with parameter passed to method. But i would like to do it "fast" without redundant code writing.
Now i have like 5 members, but what about 15000? My aim is to simplify the whole processing and code writing. So generally is it possible to do such redundant code writing bypass? Since i know that i will always pass appropriate name to method... Unless the rule of thumb is to create method for each variable?
Normally you would use a collection like a Map.
public class Storage{
private final Map<String, Integer> inventory = ...
public void addCount(String key, int count) {
Integer i = inventory.get(key);
if (i == null) i = 0;
inventory.put(key, i + count);
}
I guess that by using reflection you can iterate through the fields/methods of your object and do your computation.
For one specific field:
Field member = myObject.getClass().getField(fieldName);
// If you know the class: Field member = MyClass.class.getField(fieldName);
System.out.println(member.getInt(myObject)); // Get the value
member.setInt(myObject, 4); // Set the value
If you want to something for all the public members:
for(Field member: myObject.getClass().getFields())
// Or you can do: for(Field member: myClass.class.getFields())
{
member.getInt(myObject)); // Get the value
member.setInt(myObject, 4); // Set the value
}
Basically, what you do is that you find the Field object that represents the members of you object, then you can manipulate it.
Most IDEs will generate setters and getters for you. This will do what you want with no bother or effort. If this is insufficient, write a method which uses reflection to set the values.
If you have a class with 15000 members, and by this I assume you mean variables private to a class, then you have other issues to resolve.

Categories