How would this final variable be already assigned and not initialized? - java

I have a final variable, save, that is a serializble class for some information. What I've attempted to do is to set a final variable as that serializable class, however I get some conflicting warnings. I'm attempting to make it so that if the file isn't loadable / doesn't exist, it will simply create a new instance, otherwise it will use the old one.
My issue as it stands is commented in the code at the constructor opening, closing, and on reading the object from the ObjectInputStream
private final CannonSet save;
public CannonManager(ManCannon plugin) { // Warning that save is not initialized
if (/* some conditional statement */) {
//lot of code removed, unnecessary to problem
//essentially, save was set conditionally here (loaded from file)
this.save = new CannonSet();
}
if (this.save == null) {
this.save = new CannonSet(); // Warning that save may have already been set
}
}

It looks like you just need to declare your temp object at full method scope, test if it's null at the bottom where you are checking this.save instead, and then do the assignment. Basically, just have one line ONLY where you assign the instance field. Abbreviated from your code:
public CannonManager(ManCannon plugin) {
CannonSet temp = null;
try{
// stuff happens
temp = (CannonSet) in.readObject();
}catch( ... ){
// exception handling
}
if(temp == null){
this.save = new CannonSet();
}else{
this.save = temp;
}
}

You can't do this to a final variable:
if (this.save == null) {
this.save = new CannonSet(); // Warning that save may have already been set
}
If save was initialized - and only in this case comparison to null is possible, then you can't reassign it.
Conditional logic is possible with final variables and in many cases it looks similar to:
final CannonSet save;
if(condition1){
save = new CannotSet(1);
} else
if(condition2){
save = new CannotSet(2);
} else {
save = new CannotSet(3);
}

I found that using a temp variable throughout the constructor made this a lot simpler:
private final CannonSet save;
public CannonManager(ManCannon plugin) {
CannonSet temp = null;
/* code .... */
if (temp == null) {
this.save = new CannonSet();
} else {
this.save = temp;
}
}

Related

Search ArrayList with For Loop NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I keep receiving this error but I cannot see any logical errors in my code.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
private double getValueOrDefault(String symbol, double defaultValue) {
double value = getValue(symbol);
if (value != -1)
return value;
else
return defaultValue;
}
public void createStocks() {
// try get stock realtime values
stocks.add(new TechStock("BB", 30.3));
stocks.add(new TechStock("GOOG", getValueOrDefault("GOOG", 5.8)));
stocks.add(new TechStock("AMZN", getValueOrDefault("AMZN", 6.3)));
stocks.add(new FinanceStock("GLNG", getValueOrDefault("GLNG", 121)));
}
public static double getValue(String symbol) {
// read data
try {
URL url = new URL(API_URL.replace("XXX", symbol));
Scanner s = new Scanner(url.openStream());
// find price
while (s.hasNextLine()) {
String line = s.nextLine();
if (line.startsWith("\"price\"")) {
// split shenanigans
String[] f = line.split("\"");
return Double.parseDouble(f[3]);
}
}
// if we reached here: the stock is invalid
return -1;
} catch (Exception ex) {
ex.printStackTrace();
}
return -1;
}
public class StockFrame extends Frame
{
private int amount;
private Portfolio portfolio;
private ArrayList <StockMarket> stocks = new ArrayList<StockMarket>();
private TextArea stockDetails;
private TextField purchaseCode;
private boolean found = false;
private int locateStock() {
for(int i = 0; i<stocks.size(); i++) {
if(stocks.get(i).getCode().equals(purchaseCode.getText())) {
return i;
}
}
return -1;
}
private void a() {
int position = locateStock();
if(position != -1){
StockMarket bs = stocks.get(position);
.....
}
I tried changing I to 1 but I still receive the NullPointerException.
The error seems to be located at the int position = locateStock(); but I am unsure.
A NullPointerException occurs when you try to reference an object that hasn't been declared at that point in the execution of your program.
The fact that you still got the exception when you tried changing the initial value of i to 1 tells me that when you call locateStock(), your List of TechStocks hasn't been initialized with a new List<TechStock>() statement prior to calling locateStock(). Therefore, when you try to declare the for loop using stocks.size(), you get an exception, since stocks is null at that point.
However, it's difficult to say how to exactly fix your problem because you didn't really offer enough information in your snippet for anyone to know how that code fits in context with the rest of your program.

how to access a variable outside the loop

Hi I am writing a program with some crazy logic and I have several loops. I need to access the variable 'Sets' outside my first loop. How can I do that?
class Example1 {
public static String sets = new String();
static Set<String> reports(){
try{
String sets = "";
fir(i=1; i<3; i++){
While(bufferedReader.readLine() != null){
if (condition1){
if(condition2){
for(condition3){
if(condition4){
sets = ("test1" + "test2");
for(condition5){
sets = sets.concat("test3");
}
}
}
}
}
}
}
}
}
// ****** I need to access sets here *******
}
You need to define the variables you want to use at the level you want to use them. e.g. if you want to access them at the outer most level of you method you need to define them at the output most level of your method, e.g. at the start of the method.
BTW: I suggest you use the formatter in your IDE to ensure your code is readable. e.g.
class Example1 {
static Set<String> reports() {
Set<String> sets = new HashSet<>();
try {
for (int i = 1; i < 3; i++) {
String line;
while ((line = bufferedReader.readLine()) != null) {
if (condition1) {
if (condition2) {
for (condition3) {
if (condition4) {
sets.add("test1");
sets.add("test2");
for (condition5) {
sets.add("test3");
}
}
}
}
}
}
}
} finally {
}
return sets;
}
}
Note: since you are just processing data, with input from a file and output of a Set, it is highly likely you should be using Java 8 streams, however it is not clear from your example exactly what you are trying to do.

Accessing an enum type to create an object through inheritance

My assignment is to use take an old lab we created an wrap a GUI around it, simple enough.. I have no problem creating the GUI or inheriting variables to create different objects but one object requires an Enum type in its parameters and i seem to be having a tough time assigning an enum type to the object even though the compiler doesn't complain so maybe you guys can help me out.
Manager class containing the enum class :
public enum Department {
PAYROLL, PRODUCTION, ACCOUNTING, RESEARCH, MARKETING;
public static Department getRandomDepartment() {
Department[] d = Department.values();
int size = Department.values().length;
return d[r.nextInt(size)];
}
};
there is a mutator method setDepartment that can be utilized but i am not sure how to instantiate it.
public void setDepartment(Department d) {
department = d;
}
heres my Add manager method in my GUI class :
if(command.equals("Add Manager")){
m_name = inputName.getText();
m_num = inputNum.getText();
m_year = Integer.parseInt(inputHire.getText());
m_yearlyPay = Double.parseDouble(inputYearly.getText());
if(inputDepartment.equals("Payroll") || inputDepartment.equals("payroll")){
Manager temp = new Manager(m_name,m_num,m_year,m_yearlyPay,Manager.Department.PAYROLL);
System.out.println(temp);
}
if(inputDepartment.equals("Production") || inputDepartment.equals("production")){
Manager temp = new Manager(m_name,m_num,m_year,m_yearlyPay,Manager.Department.PRODUCTION);
System.out.println(temp);
}
if(inputDepartment.equals("Accounting") || inputDepartment.equals("accounting")){
Manager temp = new Manager(m_name,m_num,m_year,m_yearlyPay,Manager.Department.ACCOUNTING);
System.out.println(temp);
}
if(inputDepartment.equals("Research") || inputDepartment.equals("research")){
Manager temp = new Manager(m_name,m_num,m_year,m_yearlyPay,Manager.Department.RESEARCH);
System.out.println(temp);
}
if(inputDepartment.equals("Marketing") || inputDepartment.equals("marketing")){
Manager temp = new Manager(m_name,m_num,m_year,m_yearlyPay,Manager.Department.MARKETING);
System.out.println(temp);
}
}
theres obviously something wrong with my method because when i input the department through the GUI it doesn't recognize the department i added, any thoughts on what my next step should be?
Enums always provide a valueOf(String) static factory which could help you I think.
i.e
Manager.Department.valueOf("PAYROLL") will return a Manager.Department.PAYROLL
I seemed to have fixed the problem and like always its something simple but thats coding for you lol,
i forgot to instantiate a string variable to act as a holder for the GUI so when i was inputting the department the string was going nowhere so it wasn't recognizing the department.
the working code is now :
if(command.equals("Add Manager")){
m_name = inputName.getText();
m_num = inputNum.getText();
m_year = Integer.parseInt(inputHire.getText());
m_yearlyPay = Double.parseDouble(inputYearly.getText());
department = inputDepartment.getText();
if(department.equalsIgnoreCase("Payroll")){
Manager temp = new Manager(m_name,m_num,m_year,m_yearlyPay,Manager.Department.PAYROLL);
System.out.println(temp);
}
if(department.equalsIgnoreCase("Production")){
Manager temp = new Manager(m_name,m_num,m_year,m_yearlyPay,Manager.Department.PRODUCTION);
System.out.println(temp);
}
if(department.equalsIgnoreCase("Accounting")){
Manager temp = new Manager(m_name,m_num,m_year,m_yearlyPay,Manager.Department.ACCOUNTING);
System.out.println(temp);
}
if(department.equalsIgnoreCase("Research")){
Manager temp = new Manager(m_name,m_num,m_year,m_yearlyPay,Manager.Department.RESEARCH);
System.out.println(temp);
}
if(department.equalsIgnoreCase("Marketing")){
Manager temp = new Manager(m_name,m_num,m_year,m_yearlyPay,Manager.Department.MARKETING);
System.out.println(temp);
}
}
thanks for any input that was provided

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

Having trouble with accessing array data from one class to another

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.

Categories