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.
Related
This question already has answers here:
Compiler says "Variable might not have been initialized", although I have a flag variable to guarantee it [duplicate]
(7 answers)
Closed 4 years ago.
I'm learning Java and I have encountered a behaviour that I don't understand. All similar topics I have found here provided walkaround with initialization with default values (which I happily used) but no one has explained why the following approach generates errors.
To understand Java better, I have written the code below just to isolate the problematic part, so please focus on the error I'm asking about - I know this code does not make much sense.
public class Test {
public static void main(String[] args) {
int value;
ValueContainer valueContainer;
boolean isInputLegal = false;
while (!isInputLegal) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Set value ");
value = scanner.nextInt();
isInputLegal = true;
} catch (NumberFormatException | InputMismatchException e) {
scanner.nextLine();
isInputLegal = false;
}
if (isInputLegal) {
valueContainer = new ValueContainer(value);
}
}
valueContainer.printValue();
}
}
class ValueContainer {
int value;
public ValueContainer(int value) {
this.value = value;
}
public void printValue() {
System.out.println(value);
}
}
The error appears in line valueContainer = new ValueContainer(value); and in line valueContainer.printValue();
Things I have tried:
I thought maybe there is some kind of exception I am missing, so I replaced catch (NumberFormatException | InputMismatchException e) with catch (Exception e). Didn't help.
I thought maybe the compiler thinks the loop can go infinite and still not provide initialization, so I added a counter to the loop, which stops it after 1000 iterations and inserts some default values. Didn't help.
I understand that this error shows up usually when the programmer makes a mistake and leaves a path that leads to usage of initialized value, but I am 90% percent positive this is not the case here.
Try initialising your value, so instead of writing:int value; write: int value = 0,
also try and initialise your ValueContainer with the default constructor, and set it's value with a setter
public static void main(String[] args) {
int value = 0;
ValueContainer valueContainer = new ValueContainer();
boolean isInputLegal = false;
while (!isInputLegal) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Set value ");
value = scanner.nextInt();
isInputLegal = true;
} catch (NumberFormatException | InputMismatchException e) {
scanner.nextLine();
isInputLegal = false;
}
if (isInputLegal) {
valueContainer.setValue(value);
}
}
valueContainer.printValue();
}
This should work (with adding a setter method in your ValueContainer class)
This question already has answers here:
Get variable by name from a String
(6 answers)
Closed 4 years ago.
I would like it so that a user can tell my code that when a certain variable has a certain value it should do something. I have written a simple code sample of what I would like this to look like and I hope you can make sense of it. Is it in any way possible to make a String and let Java check wheter the variable that carries the same name is equal to the value of another variable.
int turn = 1;
String variable = "turn";
int compareToThisValue = 1;
if (variable.toVariable() == compareToThisValue) {
System.out.println("Yes it works thank you guys!");
{
I guess the following code can help. It uses java Reflection to get the job done. If you have some other requirements this can be tweaked to do so.
import java.lang.reflect.*;
class Test {
int turn = 1;
boolean checkValueVariable(String variableName, int value) throws Exception {
Field[] fields = this.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.getName().equals(variableName))
return field.getInt(this) == value;
}
return false;
}
public static void main(String... args) {
Test test = new Test();
String variableName = "turn";
int variableValue = 1;
try {
System.out.println(test.checkValueVariable(variableName, variableValue));
} catch (Exception e) {
e.printStackTrace();
}
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am a bit lost...I'm learning Java and have to program a small poll command line application.
We are supposed to program it in german first(to be consistent between us all), so I'll try to translate it, so it's easier to read for you.
My problem is, that it's throwing an exception (while compiling) as following:
Exception in thread "main" java.lang.NullPointerException
at communication.Poll.addQuestionItem(Poll.java:18)
at main.PollTool.main(PollTool.java:8)
am I initializing my array "questionItems" wrong? Aren't I supposed to do it like that? What's wrong here? Did I forget something? :(
main.PollTool:
package main;
import communication.Poll;
public class PollTool {
public static void main(String[] args) {
Poll poll = new Poll ("Best Smartphone:",3);
poll.addQuestionItem("iPhone"); //<--line 8
poll.addQuestionItem("Android");
poll.addQuestionItem("Windows Phone");
poll.askQuestions("This poll determines the polularity of different Smartphones.");
}
}
communication.Poll:
package communication;
import java.util.Scanner;
import calculations.QuestionItem;
public class Poll {
private String questionTitle;
private QuestionItem[] questionItems;
private int count;
private Scanner in = new Scanner(System.in);
public Poll(String s,int arraySize){
questionTitle = s;
questionItems = new QuestionItem[arraySize]; //<--problem here?
}
public void addQuestionItem(String s){
if(count<questionItems.length){
questionItems[count++].setItemText(s); // <--exception here
}
}
public void askQuestions(String topic){
System.out.println(topic);
System.out.println(questionTitle);
for(int i=0; i<questionItems.length; i++){
System.out.println("- - - "+ questionItems[i].getItemText() +" - - -");
System.out.print("Your numerical answer: ");
questionItems[i].vote(in.nextInt());
}
}
void evaluation(){
//not ready :)
}
}
calculation.QuestionItem:
package calculation;
public class QuestionItem {
int count;
int overall;
String text;
public void vote (int pointValue){
overall += pointValue;
count++;
}
public double getDurchschnitt(){
return (double) overall/count;
}
public void setItemText(String s){
text = s;
}
public String getItemText(){
return text;
}
}
When you initialize an array of objects like this:
questionItems = new QuestionItem[arraySize];
All of the values are null by default.
In addQuestionItem, you try to call a method on an object in the array. However, that object starts off null, so this line of code doesn't work:
questionItems[count++].setItemText(s);
What you have to do is initialize the object before setting the text:
questionItems[count] = new QuestionItem();
questionItems[count].setItemText(s);
count++;
Alternatively, you can do what Constant suggested, and initialize all the objects when you initialize the array.
By the looks of it, you're making the array but it doesn't contain the objects yet. You probably want this in the constructor instead.
questionItems = new QuestionItem[arraySize];
for(int i = 0; i < questionItems.length; i++) {
questionItems[i] = new QuestionItem();
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm supposed to write exceptions to prevent invalid objects, such as Strings having no blanks or the double and int numbers being in a certain range. I am really confused on how to do this. Am I supposed to use an if/else statement? Or more try/catch statements?
EDIT: Each object needs to be validated. The strings cannot have blanks or contain only blanks, and the numbers cannot be less than zero. There are five other try/catch statements but I only included one. My question is what would I write so that the exception output is different for the different problems and is there a way to write it to avoid writing each exception for each separate try/catch? I looked at other posts about writing exceptions but I haven't learned what super is or does and cannot use it.
public class CD {
String artistname = "";
String albumname = "";
double cdprice = 0;
int amountinstock = 0;
public CD(final String artistname, final String albumname, final double cdprice, final int amountinstock) {
this.artistname = artistname;
this.albumname = albumname;
this.cdprice = cdprice;
this.amountinstock = amountinstock;
}
public static void main(final String[] arg) throws Exception {
try {
final CD cd1 = new CD("Muse", "The Resistance", 11.99, 20);
System.out.println(cd1.toString());
System.out.println("=========================");
} catch (final CDException cde) {
System.out.println(cde.getMessage());
System.out.println("=========================");
}
}
}
I would check the String, int,... with an if-statement and if something is incorrect throw an IllegalArgumentException.
First you have to write conditions (i.e. if statements) that check if the input is invalid. When you detect invalid input, you should throw an exception.
You can write custom exception like mentioned here.
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
You can give some logical name to your custom exception like IntegerNumberOutofRangeException.
And then you can use if else in your code and throw that custom exception for specific condition you have mentioned.
Code
int intNumber = 50;
if (intNumber > 60 && intNumber < 100) {
// Do your work
} else {
throw new CustomException("Integer number out of expected range of 60 to 100");
}
You should use IF to make validations.
A best practice is to not throw an exception from the constructor of a class.
Another best practice is to not make validations in the constructor of the class.
So a ruff improvement of your code would be (i didn't run it and there are still improvements to be made):
public class CD {
String artistname = "";
String albumname = "";
double cdprice = 0;
int amountinstock = 0;
public String ValidationMessage = "";
public CD(final String artistname, final String albumname, final double cdprice, final int amountinstock) {
this.artistname = artistname;
this.albumname = albumname;
this.cdprice = cdprice;
this.amountinstock = amountinstock;
}
public boolean ValidateCD()
{
this.ValidationMessage = "";
if (/*insert validation condition here*/)
{
this.ValidationMessage = "CD IS NOT VALID BECAUSE TITLE IS WRONG";
return false;
}
return true;
}
public static void main(final String[] arg) throws Exception {
final CD cd1 = new CD("Muse", "The Resistance", 11.99, 20);
final boolean isValid = cd1.ValidateCD();
if (!isValid) {
System.out.println(cd1.ValidationMessage);
}
}
}
I am getting a null exception error from this segment of code and I am not sure what causing it. The array itemcatalog has being populate for i =0 to 8. I am new to java so any assistance will be greatly appreciated. The error message points to the line of the while statement. Thanks
public class ItemCatalog {
private static ItemCatalog instance = new ItemCatalog();
private Item itemCatalog[] = new Item[9];
private ItemCatalog(){
};
public static synchronized ItemCatalog getInstance() {
return instance;
}
public void populateCatalog()
{
itemCatalog[0] = new Item("bb","Baked Beans",new BigDecimal("0.35"));
itemCatalog[1] = new Item("cf","Cornflakes",new BigDecimal("1.00"));
itemCatalog[2] = new Item("s0","Sugar",new BigDecimal("0.50"));
itemCatalog[3] = new Item("tb","Tea Bags",new BigDecimal("1.15"));
itemCatalog[4] = new Item("ic","Instant Coffee",new BigDecimal("2.50"));
itemCatalog[5] = new Item("b0","Bread",new BigDecimal("0.50"));
itemCatalog[6] = new Item("s0","Sausages",new BigDecimal("1.30"));
itemCatalog[7] = new Item("e0","Eggs",new BigDecimal("0.75"));
itemCatalog[8] = new Item("m0","Milk",new BigDecimal("0.65"));
}
public BigDecimal getPrice(String itemCode)
{
int i = 0;
while (!itemCode.equals(itemCatalog[i].getItemCode()))
{
i++;
}
BigDecimal itemPrice = itemCatalog[i].getItemprice();
return itemPrice;
}
}
I solved the issue. I was populating the catalog in the main class which was giving the null exception error. I instantiate it in the jframe instead and it works. The follow code solved the issue, but is this the best place to populate the catalog?
private void saleButtonActionPerformed(java.awt.event.ActionEvent evt) {
String itemCode = this.itemCodeinput.getText();
int itemQuantity =Integer.parseInt(this.itemQuantityinput.getText());
ItemCatalog catalog = ItemCatalog.getInstance();
catalog.populateCatalog();
BigDecimal price = catalog.getPrice(itemCode);
itemCostoutput.setText(price.toString());
}
If your itemCode doesn't match any entries in your itemCatalog, then eventually
while (!itemCode.equals(itemCatalog[i].getItemCode()))
{
i++;
}
will increment i to 11, in which case itemCatalog[11] is either empty or out of bounds.
If addition, you should use a for loop to iterate through the itemCatalog:
for (int i = 0; i < itemCatalog.length; i++) {
if (itemCode.equals(itemCatalog[i].getItemCode()) {
return (BigDecimal) itemCatalog[i].getItemprice();
}
}
return null // you can change this from null to a flag
// value for not finding the item.
From the comments, it's clear the design isn't sound.
Here's a possible solution :
public BigDecimal getPrice(String itemCode) {
for (int i=0; i<itemCatalog.length; i++) { // not going outside the array
if (itemCatalog[i].getItemCode().equals(itemCode)) { // inversing the test to avoid npe if itemCode is null
return itemCatalog[i].getItemprice();
}
}
return null; // default value
}
This supposes your array is correctly filled with itemCatalogs having an itemCode.
How do you end your loop?
Seems that the loop will keep going until i is 10. Then your will have exceeded the limit.
Unless this is a uni assignment where you have to use arrays, I'd also suggest using a map, rather than an array. This way your lookup will be the same time, whether your collection has 100,000 entries or 10.
You will also reduce risk of NPE or ArrayOutOfBounds exception
See http://docs.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html
When adding the object use the item code as the key. Then lookup by the key.
The cost of using a map is increased memory usage.