NullPointerException with own class [duplicate] - java

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();
}

Related

Exception in thread "main" java.lang.NullPointerException: program compiles fine, but the error shows when it runs [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
public void traverseRowLR(String [] list, String [] key, String pool)
{
pool = "left to right";
ArrayList<Location> obj = new ArrayList<Location>();
for(int i = 0; i<key.length; i++)
{
for(int a=0;a<list.length;a++)
if(list[a].indexOf(key[i])>-1)
finalList.add(new Location(key[i],a+1,list[a].indexOf(key[i]),pool));
}
}
That above is the method. The error is on the line of the second for loop.
Heres another place the error is mentioned:
public MazeAH(String [] key, String [][] wordBank)
{
maze = wordBank;
answer = key;
}
//other methods
public ArrayList<Location> solve()
{
mergeRow(maze, rowWords);
mergeCol(maze, colWords);
traverseRowLR(rowWords, answer, horizontal);
traverseRowRL(rowWords, answer, horizontal);
traverseRowTB(colWords, answer, vertical);
traverseRowBT(colWords, answer, vertical);
return finalList;
}
The error is in the line:
traverseRowLR(rowWords, answer, horizontal);
Finally, heres the driver program, sorry if im posting too much code, im not sure what's necessary: The goal of this program is to merge rows and columns together into Strings, and then search for words in the "key" word bank. I originally completed this project using non-void methods, but my professor wants me to redo it with void methods.
import java.util.*;
public class SolveWordSearchAH
{
public static void main(String [] args)
{
String [][] letters = {{"e","p","l","i","r","q","k","o","s","a"},
{"u","k","i","e","s","y","x","c","n","f"},
{"c","p","o","z","g","f","q","a","y","r"},
{"p","e","m","c","z","a","n","t","e","i"},
{"g","u","g","q","t","a","b","r","h","e"},
{"g","i","q","v","b","e","d","b","s","s"},
{"c","o","f","f","e","e","i","l","r","q"},
{"h","r","e","t","a","w","b","d","e","l"},
{"y","q","o","k","w","v","p","x","h","z"},
{"c","d","n","t","f","q","k","b","p","w"}};
String [] key = {"coffee", "water", "taco", "hershey", "fries"};
//can have another key array if needed-depends on your implementation
MazeAH m=new MazeAH(key, letters);
ArrayList<Location> answer=m.solve();
System.out.println(answer);
}
}
My variables are declared here:
private ArrayList<Location> finalList = new ArrayList<Location>();
private String [][] maze;
private String [] answer;
private String vertical="";
private String horizontal = "";
private String [] rowWords;
private String [] colWords;
Here is the error in the compile log:
Exception in thread "main" java.lang.NullPointerException
at MazeAH.mergeRow(MazeAH.java:117)
at MazeAH.solve(MazeAH.java:26)
at SolveWordSearchAH.main(SolveWordSearchAH.java:24)
Heres MergeRow:
public void mergeRow(String[][] letters, String [] words)
{
String []temp = new String [letters.length];
for(int i=0; i<letters.length; i++)
{
temp[i]="";
for(int a=0; a<letters[0].length; a++)
{
temp[i]+=letters[i][a];
}
}
for(int s = 0; s<temp.length; s++)
{
temp[s] = words[s];
}
}
Heres the updated trace:
Exception in thread "main" java.lang.NullPointerException
at MazeAH.mergeRow(MazeAH.java:117)
at MazeAH.solve(MazeAH.java:26)
at SolveWordSearchAH.main(SolveWordSearchAH.java:24)
You declare rowWords and colWords but never assign anything to them. This means they will hold the default value of null, and any attempt to access array elements is going to fail.
I don't know how many elements you need to store in rowWords and colWords, but if 100 is enough you can initialize them with:
public MazeAH(String [] key, String [][] wordBank)
{
maze = wordBank;
answer = key;
rowWords = new String[100];
colWords = new String[100];
}
"The error is on the line of the second for loop", clearly refers to the line;
for(int a=0;a<list.length;a++)
[Although stack trace to support this statement is missing. Try to print the correct most meaningful part of the stack trace in your next question.]
Now, if this is throwing a NullPointerException, it means at run time of your code, the value of list is null.
You can easily check this by writing a System.out.println(line); before your loop.
Based on the little code you have shared, I can only say that this is a result of you sending a null value as rowWords in you traverseRowLR call.
Perhaps you are never initializing the variable rowWords
I hope this helps!

Array List showing only most recent object added [duplicate]

This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Why do I keep getting only tha last object value in Java ArrayList?
(2 answers)
Closed 4 years ago.
package com.snapfires.pdf;
public class FultonObj {
private String fileNo;
private String parcelId;
private String situs;
public String getFileNo() {
return fileNo;
}
public void setFileNo(String fileNo) {
this.fileNo = fileNo;
}
public String getParcelId() {
return parcelId;
}
public void setParcelId(String parcelId) {
this.parcelId = parcelId;
}
public String getSitus() {
return situs;
}
public void setSitus(String situs) {
this.situs = situs;
}
}
package com.snapfires.pdf;
import java.util.ArrayList;
public class List {
public static void main(String arg[]) {
ArrayList<FultonObj> list = new ArrayList<FultonObj>();
FultonObj fuOb = new FultonObj();
String file1 = "file#1";
String file2 = "file#2";
String file3 = "file#3";
String parcelId1 = "parcelId1";
String parcelId2 = "parcelId2";
String parcelId3 = "parcelId3";
String situs1 = "situs1";
String situs2 = "situs2";
String situs3 = "situs3";
fuOb.setFileNo(file1);
fuOb.setParcelId(parcelId1);
fuOb.setSitus(situs1);
list.add(fuOb);
fuOb.setFileNo(file2);
fuOb.setParcelId(parcelId2);
fuOb.setSitus(situs2);
list.add(fuOb);
fuOb.setFileNo(file3);
fuOb.setParcelId(parcelId3);
fuOb.setSitus(situs3);
list.add(fuOb);
for(int b=0; b<list.size(); b++) {
System.out.println(list.get(b).getFileNo());
System.out.println(list.get(b).getParcelId());
System.out.println(list.get(b).getSitus());
}
}
}
When I run this small program, I am only getting the last object that was added to the List. Although it iterates through the list but the result is that it prints out the last object that was added. e.g.
file#3
parcelId3
situs3
file#3
parcelId3
situs3
file#3
parcelId3
situs3
I want all the objects that were added to the List to be there not just the last object. Could someone let me know why this is not happening?
I don't think creating new FultonObj object each time will solve my issue. Here is why. I am reading a text file where it is possible that one line may have only file# and second line may only have file# and parcelId and third line may have file#, parcelId, situs. Or any combination of file#, parcelId, situs per line. However the order will always be same, meaning you will always have: file#, parcelId, situs. So I need to make sure that fuOb is complete before I add it to ArrayList. If I create multiple fuOb then it is possible that none of the fuOb will be complete, meaning it has file#, parcelId, situs.
Your program should be like this. Everytime you are setting data in fuOb it is overriding the previous data..
FultonObj fuOb1 = new FultonObj();
fuOb1.setFileNo(file1);
fuOb1.setParcelId(parcelId1);
fuOb1.setSitus(situs1);
list.add(fuOb1);
FultonObj fuOb2 = new FultonObj();
fuOb2.setFileNo(file2);
fuOb2.setParcelId(parcelId2);
fuOb2.setSitus(situs2);
list.add(fuOb2);
make three FultonObj not use one
fuOb1.setFileNo(file1);
fuOb1.setParcelId(parcelId1);
fuOb1.setSitus(situs1);
list.add(fuOb1);
fuOb2.setFileNo(file2);
fuOb2.setParcelId(parcelId2);
fuOb2.setSitus(situs2);
list.add(fuOb2);
fuOb3.setFileNo(file3);
fuOb3.setParcelId(parcelId3);
fuOb3.setSitus(situs3);
list.add(fuOb3);

entering multiple values in link list in java

Using LinkedList I want to access the data members of the class StudData. StudData should have an array of object. This code doesn't show errors but doesn't execute successfully either.
import java.util.LinkedList;
import java.util.Scanner;
public class StudData {
public int roll_no;
public String name;
private Scanner sc;
void enter() {
sc = new Scanner(System.in);
System.out.println("enter:");
sc.nextInt(roll_no);
sc.next(name);
}
public static void main(String[] args) {
StudData p= new StudData();
LinkedList <StudData> ll=new LinkedList<StudData>();
for (int i=0; i<20; i++) {
p.enter();
ll.add(p);
}
}
}
The code shared should compile ideally. But there would be a possible exception at:
sc.nextInt(roll_no); // roll_no is 0 by default
Hence this would throw an java.lang.IllegalArgumentException: radix:0. In case you want to take roll_no as an input from user, you can change the code to:
roll_no = sc.nextInt();
It looks to me like you made a mistake (although I am on the train working with my phone)
sc.nextInt(roll_no);
sc.next(name);
Should be:
roll_no = sc.nextInt();
name = sc.next();
The variables can't be set by passing them as arguments, because a String is immutable and an int is a primitive.

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 pass a String value to another class in Java

Currently, I am running into a problem in my Java code. I am somewhat new to Java, so I would love it if you kept that in mind.
My problem is with passing a String value from one class to another.
Main Class:
private static void charSurvey()
{
characterSurvey cSObj = new characterSurvey();
cSObj.survey();
System.out.println();
}
Second:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class characterSurvey
{
public void survey(String character)
{
Scanner s = new Scanner(System.in);
int smartChina = 0,smartAmerica = 0,dumbAmerica = 0;
String answer;
System.out.println("Are you good with girls?");
System.out.println("y/n?");
answer = s.nextLine();
if(answer.equalsIgnoreCase("y"))
{
smartChina = smartChina - 3;
smartAmerica = smartAmerica + 2;
dumbAmerica = dumbAmerica + 4;
}
//...
//ASKING SEVERAL OF ABOVE ^
List<Integer> charSelect = new ArrayList<Integer>();
charSelect.add(smartChina);
charSelect.add(smartAmerica);
charSelect.add(dumbAmerica);
Collections.sort(charSelect);
Collections.reverse(charSelect);
int outcome = charSelect.get(0);
if(smartChina == outcome)
{
character = "smartChina";
}
else if(smartAmerica == outcome)
{
character = "smartAmerica";
}
else if(dumbAmerica == outcome)
{
character = "dumbAmerica";
}
System.out.println(character);
s.close();
}
}
When I call the first class I am trying to grab the value of the second.
Disclaimer* the strings in this class were not meant to harm anyone. It was a joke between myself and my roommate from China, thanks.
It seems as if you want to obtain the character in your main class after the survey has completed, so it can be printed out in the main method.
You can simply change your void survey method to a String survey method, allowing you to return a value when that method is called:
class CharacterSurvey {
public String takeSurvey() {
//ask questions, score points
String character = null;
if(firstPerson == outcome) {
character = "First Person";
}
return character;
}
}
Now, when you call this method, you can retrieve the value returned from it:
class Main {
public static void main(String[] args) {
CharacterSurvey survey = new CharacterSurvey();
String character = survey.takeSurvey();
System.out.println(character);
}
}
There are several mistakes here.
First off, in your main class as you write you call the method survey() on the CharacterSurvey object but the survey itself the way it is implemented needs a String parameter to work
public void survey(String character)
Also this method returns void. If you want somehow to grab a string out of that method you need to declare the method as
public String survey() {}
this method returns a string now.
If i were to give a general idea, declare a String variable in the second class which will be manipulated inside the survey method and once the survey is declared as a String method return the value at the end inside the method.
By doing that you'll be able to receive the String value by calling the method on the characterSurvey object (and of course assign the value to a string variable or use it however).
Hope this helped

Categories