Can't figure out why I'm getting this NullPointerException [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I'm trying to create a card game. It has 3 classes, "PlayingCard", "DeckOfPlayingCards" and "Game".
public class PlayingCard {
private String rank;
private String suit;
public void setRankAndSuit(String rank, String suit) {
this.rank = rank;
this.suit = suit;
}
public String getRankAndSuit() {
return rank + " of " + suit;
}
}
public class DeckOfPlayingCards extends PlayingCard {
// Array of playing card objects
static PlayingCard[] deck = new PlayingCard[2];
DeckOfPlayingCards() { // This is my line 11 BTW
deck[0].setRankAndSuit("1", "S");
deck[1].setRankAndSuit("2", "S");
}
}
public class Game extends DeckOfPlayingCards {
public static void main(String[] args) {
DeckOfPlayingCards newDeck = new DeckOfPlayingCards(); // This is my
// line 6
System.out.println(deck[0].getRankAndSuit());
}
}
Everything compiles fine, but when I run it, I get a Exception in thread "main" java.lang.NullPointerException at DeckOfPlayingCards.<init>(DeckOfPlayingCards.java:11) at Game.main(Game.java:6)
As I understand, this exception is thrown when I'm trying to access something which is null. I simplified the program to see where the problem is, but I still can't figure it out. I initialized the array of 2 elements before I called them, so I don't know what is wrong. Please help me

static PlayingCard [] deck = new PlayingCard[2];
means you initialized an array of but elements haven't been initialized yet
so initialize them like
deck[0] = new PlayingCard();
deck[1] = new PlayingCard();
deck[0].setRankAndSuit("1","S");

Related

Printing out an ArrayList consisting of Arrays [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
For an assignment in my programming class I need to create a program that can store countries. Every country has a name, a population & an area. (KM^2)
import java.util.ArrayList;
import java.util.Arrays;
//Main Class//**
public class P820_Country_Main {
public void run() {
Country Nederland = new Country("Netherlands", 17000000, 41543);
Country Duitsland = new Country("Gernany", 80620000, 357376);
ArrayList<Country> countries = new ArrayList<Country>();
countries.add(Nederland);
countries.add(Duitsland);
System.out.println(Arrays.toString(countries));
}
public static void main(String[] args) {
new P820_Country_Main().run();
}
}
The country class:
public class Country
{
private String countryName;
private int countryPopulation;
private int countryArea;
private double populationDensity;
public Country(String countryName, Integer countryPopulation, Integer countryArea)
{
this.countryName = countryName;
this.countryPopulation = countryPopulation;
this.countryArea = countryArea;
}
}
The issue I'm currently facing is that I can't seem to print out my ArrayList. Every spot of the ArrayList is basically an Array of its own. (Containing a String for the country's name, an int for the population & an int for the area. (Ignore the density variable, that is for later in the assignment)
The way I printed out ArrayList up until this point was as follows
System.out.println(countries);
When I do this with my current ArrayList it will print out the addresses instead of what's inside of the Array.
How do I get it to print out the ArrayList?
Try to declare toString() method in Country class:
public class Country
{
...
public String toString(){
return "Name: "+countryName+", population: "+ countryPopulation + ", area: "+countryArea;
}
...
}

Eclipse error: java.lang.NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Here is the exact error message:
Exception in thread "main" java.lang.NullPointerException
at Application.main(Application.java:22)
I've tried to fix it with what I know... what am I doing wrong?
My code:
public class Application {
private String guitarMaker;
public void setMaker(String maker) {
guitarMaker = maker;
}
public String getMaker() {
return guitarMaker;
}
public static void main (String[] args) {
Application[] guitarists;
guitarists = new Application[1];
guitarists[0].setMaker("Example maker");
System.out.println("My guitar maker is " + guitarists[0].getMaker());
}
}
new Application[1] creates an array of one element, and all elements in that array (in this case, "all the elements" is "that only element") are null by default. That means that guitarist[0] is null, and calling setMaker on it will result in the NullPointerException.
You need to instantiate a guitarist and set assign it to guitarist[0]:
guitarist[0] = new Application();
public class Application {
private String guitarMaker;
public void setMaker(String maker) {
guitarMaker = maker;
}
public String getMaker() {
return guitarMaker;
}
public static void main (String[] args) {
Application[] guitarists;
guitarists = new Application[1];
guitarists[0] = new Application(); //need to create a new object
guitarists[0].setMaker("Example maker");
System.out.println("My guitar maker is " + guitarists[0].getMaker());
}
}
You were calling a method on a null object. The new Application[1] just creates an array after that you need to make new objects in each index of the array
you have to initialise array with size and call new Application() instead of new Application[1] something like:
Application[] guitarists = new Application[1];
guitarists[0] = new Application();
guitarists[0].setMaker("Example maker");
System.out.println("My guitar maker is " + guitarists[0].getMaker());

Error: 'void' type not allowed here [duplicate]

This question already has answers here:
What causes "'void' type not allowed here" error
(7 answers)
Closed 10 months ago.
I'm learning to use classes and part of my assignment is to make this Car class. I'm getting an error on line 6 where I attempt to print of the results of the methods within the class. I think this means that I'm attempting to print something that doesn't exist and I suspect it's the mileage method. I tried changing it to return miles, but that didn't work either. Any ideas?
public class TestCar {
public static final void main(String args[]) {
Car c = new Car ();
c.moveForward(4);
System.out.println ("The car went" + c.mileage() + "miles."); // <-- L6
}
}
class Car {
public int miles = 2000;
public void moveForward(int mf) {
if (miles != 2000) {
miles += mf;
}
}
public void mileage() {
System.out.print(miles);
}
}
The error message is telling you exactly what is wrong -- you're trying to extract a result from a method that does not return a result.
Instead, have the mileage() method return a String, not print out a String.
public String mileage() {
return String.valueOf(miles);
}
Myself, I'd make this a getter method, and instead would do:
public int getMiles() {
return miles;
}
Car.mileage() is void, i.e., does not return anything. It needs to return something, like in:
public int mileage() {
return miles;
}

Nullpointerexception and no compilation errors. Can't find cause [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
been struggling with this problem since a couple of hours. Including looking through the previous questions answered. (Im really new in Java, basicly started a couple of days ago)
it keeps giving me NullpointerExceptions between Register.läggTillhund(nyHund); in the first class and hundRegister.add(nyHund); in the second class.
I have no idea what might be causing them. Does anyone have Ideas?
The purpose of the code (when finished) is to add an object from the 3rd class, into a list in the secondclass using the firstclass as the "main program".
Thanks for the help!
Oskar
First Class (Main)
public class testning {
public static void main(String[] args) {
Hund nyHund = new Hund("Daisy", 13, "labrador", 22.3);
System.out.println(nyHund.toString());
System.out.println(nyHund);
Register.läggTillHund(nyHund);
}
}
Second Class:
import java.util.ArrayList;
public class Register {
private static ArrayList<Hund> hundRegister;
public static void läggTillHund(Hund nyHund){
hundRegister.add(nyHund);
System.out.println(nyHund);
}
public Register(){
hundRegister = new ArrayList<Hund>();
}
}
Third Class
public class Hund {
private String namn;
private int ålder;
private double vikt;
private String ras;
public Hund(String hundnamn, int hundålder, String hundras, double hundvikt) {
this.namn = hundnamn;
this.ålder = hundålder;
this.ras = hundras;
this.vikt = hundvikt;
}
public String getNamn() {
return namn;
}
public int getÅlder() {
return ålder;
}
public double getSvanslängd() {
if ("tax".equals(ras)){
return 3.7;
}else{
return ((vikt*ålder)/10);
}
}
public String toString() {
return namn + "\n" + ålder + "\n"+ras+"\n"+vikt+"\n"+getSvanslängd();
}
}
You're accessing static method. In this case constructor never working. Use private static ArrayList<Hund> hundRegister = new Arraylist<>() ;and delete the constructor. To see what's going on add System.out.println line to construct and you'll see it will never works

Exception NullPointer, suggestions? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I am following the ebook Big Java Late Objects - and I have problem resolving on of the tasks. It is about inheritance. There is Question class and one sub ChoiceQuestion class that extends it.
But when I run the code in my testclass it calls the null exception and I don't know why.
Exception in thread "main" java.lang.NullPointerException
at ChoiceQuestion.addChoice(ChoiceQuestion.java:12)
at TestClass.main(TestClass.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Here are my classes:
public class Question {
private String text;
private String answer;
/**
* Constructs a queston with empty question and answer.
*/
public Question(){
text = "";
answer = "";
}
//=============Setter methods============
public void setText(String questionText){
text = questionText;
}
public void setAnswer(String correctResponse){
answer = correctResponse;
}
//==============Getter Methods=============
public boolean checkAnswer(String response){
return answer.equals(response);
}
public void display(){
System.out.println(text);
}
}
And here is my subclass:
class ChoiceQuestion extends Question {
private ArrayList<String> choices;
//=========Methods==============
public void addChoice(String choice,boolean correct){
choices.add(choice);
if(correct){
//convert choices.size() to string
String choiceString = "" + choices.size();
this.setAnswer(choiceString);
}
}
public void display(){
// Display the question text
super.display();
// Display the answer choices
for(int i=0;i<choices.size();i++){
int choiceNumber = i + 1;
System.out.println(choiceNumber + ": " + choices.get(i));
}
}
}
And my test Class:
import java.util.Scanner;
public class TestClass {
public static void presentQuestion(Question q){
q.display();
System.out.println("Your answer: ");
Scanner in = new Scanner(System.in);
String response = in.nextLine();
System.out.println(q.checkAnswer(response));
}
public static void main(String[] args) {
Question first = new Question();
first.setText("James Gosling");
first.setAnswer("James Gosling");
ChoiceQuestion second = new ChoiceQuestion();
second.setText("In which country was the inventor of Java born? ");
second.addChoice("Austria", false);
second.addChoice("Canada",true);
second.addChoice("Denmark",false);
second.addChoice("United States",false);
presentQuestion(first);
presentQuestion(second);
}
}
Object choices is never initialized.
In Java, objects must be initialized before you can use them. That's why an attempt to call choices.add(choice) yields such an exception.
It is often a good idea to initialize member objects in constructors.
In this case, it looks like you should write a constructor for ChoiceQuestion and initialize your choices ArrayList there.
class ChoiceQuestion extends Question {
private ArrayList<String> choices;
ChoiceQuestion(){
choices = new ArrayList<>();
}
//...
Write private ArrayList choices = new ArrayList();
In the class when you declared it.
You need to initialize your list before use:
private List<String> choices = new ArrayList<String>();
The choices member is never initialized, so the first time you try to access it, you fail with a NullPointerException. You could, for example, initialize it in the class definition:
class ChoiceQuestion extends Question {
private ArrayList<String> choices = new ArrayList<>();
// Rest of the class

Categories