This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I would like to ask help for my project. I am a newbie programmer and I don't get this error "exception in thread main java.lang.nullpointerexception"
this is my code:
public class Slumbook{
public String codeName;
public Slumbook(){
//
}
public Slumbook(String codeName){
this.codeName = codeName;
}
public String getCodeName(){return codeName;}
public void setCodeName(String codeName){this.codeName = codeName;}
}
And the Driver Program code is:-
import java.util.*;
public class SlumbookD{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Slumbook[] slum = new Slumbook[20];
for(int n=0; n<10; n++){
slum[n].setCodeName(sc.nextLine());
}
}
}
You allocated the array ... but you failed to allocate any objects contained in the array.
SUGGESTION:
import java.util.*;
public class SlumbookD {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Slumbook[] slum = new Slumbook[20];
for(int n=0; n<slum.length; n++){
slum[n] = new Slumbook(sc.nextLine);
}
}
}
... OR BETTER ...
// You only need one class - with it's own main(). Not two classes...
public class Slumbook{
public String codeName;
public Slumbook(String codeName){
this.codeName = codeName;
}
public String getCodeName(){
return codeName;
}
public void setCodeName(String codeName){
this.codeName = codeName;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Slumbook[] slum = new Slumbook[20];
for(int n=0; n<slum.length; n++){
slum[n] = new Slumbook(sc.nextLine);
}
}
}
You have created blank array but not initialize it, you have to associate object reference at your array index and then you can call any number of setter methods on that index.
Slumbook[] slum = new Slumbook[20];
for(int n=0; n<10; n++){
slum[n] = new Slumbook(); // Instantiate Slumbook class and assign reference
slum[n].setCodeName(sc.nextLine());
}
You need to initialize the Array elements before using them.
Slumbook[] slum = new Slumbook[20];
for(int n=0; n<10; n++){
slum[n] = new Slumbook();
slum[n].setCodeName(sc.nextLine());
}
You can initialize all the elements of array at once to avoid any future Exceptions
Slumbook[] slum = new Slumbook[20];
for(int i = 0 ; i < slum.length ; i++) //initializing all the elements
slum[i] = new Slumbook();
for(int n=0; n<10; n++){
slum[n].setCodeName(sc.nextLine());
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am very confused!!
In my Question class, I am trying to print a question in an array and the corresponding multiple choice answers stored in a separate 2D array. I put that in a loop and am passing int row from the main method and trying to get user input and pass that back to my Question class. Probably doesn't make sense but I get a null point error.
Here's all of my code
public class Question{
private int selectedAnswer;
public String[] questions =
{
"Favourite sweet",
"Favourite subject at Hogwarts",
"Dream vacation",
"Favourite Drink",
"Dream House",
"What do you desire the most?",
"Favourite dress robe colour",
"Pick a muggle career",
"Pick a creature"
};
private String[][] options =
{
{"1.Acid Pops","2.Sherbert Lemons","3.Bertie Bott's Every Flavour Beans",
"4.Cake","5.Hagrid's Rock Cakes","6.Chocolate Frogs","7.Ginger Newt",
"8.I hate sweets"},
{"1.Care of Magical Creatures","2.Charms","3.Defense Against the Dark Arts",
"4.Divination","5.Herbology","6.History of Magic","7.Muggle Studies","8.Potions",
"9.Study of Ancient Runes","10.Transfiguration"},
{"1.Anywhere with friends","2.Egypt","3.Hogwarts","4.Museum","5.India","6.Forest",
"7.Can't be bothered with a vacation"},
{"1.Unicorn blood", "2.Pumpkin Juice", "3.Butter beer", "4.Coca-Cola", "5.Tea", "6.Coffee", "7.Brandy"},
{"1.The Burrow", "2.A Cottage", "3.Thirteen Grimmauld Place", "4.Malfoy Manor"},
{"1.Friends", "2.Success", "3.Money", "4.Power"},
{"1.Black", "2.Red", "3.Pink", "4.Green", "5.Orange", "6.Blue"},
{"1.Lawyer", "2.Teacher", "3.Social Worker", "4.Prime Minister", "5.Google Employee"},
{"1.Centaur", "2.Basilisk", "3.Unicorn", "4.Thestral", "5.Phoenix", "6.Hippogriff", "7.Dementor"}
};
private String[] quizQuestion;
private String[][] quizOptions;
//new update:
private String quizQuestion;
private String[] quizOptions
public Question(int row){
for(int i= row; i< questions.length; i++){
**quizQuestion[i] = questions[i];** //null point error
quizQuestion = questions[i]; // new update
for(int j = row; j < options[i].length; j++){
quizOptions[i][j] = options[i][j];
quizOptions[i] = options[i][j]; // new update
}
}
}
public String[] getQuizQuestion(){
**return this.quizQuestion;** //null point error
}
public String[][] getQuizOptions(){
return this.quizOptions;
}
public void setSelectedAnswer(int userInput){
selectedAnswer = userInput;
}
}
Main method
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Question q = new Question(0);
System.out.println(q.getQuizQuestion());
System.out.println(q.getQuizOptions());
Scanner keyboard = new Scanner (System.in);
int userInput = keyboard.nextInt();
System.out.println("Select an answer: ");
q.setSelectedAnswer(userInput);
}
}
You have to create an array before you can fill it.
public Question(int row){
quizQuestion = new String[ <expected length> ];
quizOptions = new String[ <expected length> ][]; //Outer array
for(int i= row; i< questions.length; i++){
**quizQuestion[i] = questions[i];** //null point error
quizOptions[i] = new String[]; //Each inner array
for(int j = row; j < options[i].length; j++){
quizOptions[i][j] = options[i][j];
}
}
}
But, as far as I can tell, quizQuestion should just be one String. And quizOptions should be a String array. If a Question object holds the details of only one question, the question should be a String and the options should be only the options of that question.
Update:
private String quizQuestion;
private String[] quizOptions
public Question(int row){
quizQuestion = questions[row];
quizOptions = new String[options[row].length];
for(int j = 0; j < options[row].length; j++){
quizOptions[j] = options[row][j];
}
}
public String getQuizQuestion(){
return this.quizQuestion;
}
public String[] getQuizOptions(){
return this.quizOptions;
}
Also, you may not need to copy options at all:
private String quizQuestion;
private String[] quizOptions
public Question(int row){
quizQuestion = questions[row];
quizOptions = options[row]; //Just refer to the existing piece
}
public String getQuizQuestion(){
return this.quizQuestion;
}
public String[] getQuizOptions(){
return this.quizOptions;
}
sorry I'm really new to all of this. I know this is a stupid/easy question, but how would I display the shuffled array after i've set it all up. I have my code below and made the class that creates the array and has the algorithm for shuffling the integers inside the array. But I can't figure out how to display the shuffled array. Heres my code below:
My main:
package lab4b;
import java.util.Scanner;
public class Lab4B {
public static void main(String[] args) {
Shuffler test = new Shuffler(15);
test.Shuffle();
test.display();
}
}
and my Shuffle class:
package lab4b;
import java.security.SecureRandom;
public class Shuffler {
private static final SecureRandom randomNumbers = new SecureRandom();
private int [] data;
public Shuffler (int size){
data = new int [size];
for(int i = 0; i<data.length;i++){
data[i]= i+1;
}
}
public void Shuffle(){
int temp;
for(int first = 0; first<data.length; first++){
int second = randomNumbers.nextInt(data.length);
temp = data[first];
data[first] = data[second];
data[second] = temp;
}
}
public void display()
{
for(int counter =0; counter<data.length; counter++ ){
System.out.print(data[counter]+ " ");
}
System.out.println();
}
}
In this loop you are reset the value of the dataarray
for(int counter =0; counter<data.length; counter++ ){
// data[counter] = counter + 1; - do not do this
System.out.print(data[counter]+ " ");
}
This question already has answers here:
Is this a valid way to count instances of objects?
(2 answers)
Closed 6 years ago.
I am a new user in java. As a programming exercise i have to make a program that - asks how many objects the user wants to create and then creates them. Class also calls for a class method that prints the number of created objects. also
to write the class which creates the objects. Class must be able to keep track of the number of created objects. Class also needs the method that prints the number of objects. Check the completed class for the names of the class and method.
I have tried following but have not reached any where so i am expecting some help: Please help!!
import java.util.Scanner;
public class NumberOfObjects{
public static void main(String args[]) {
System.out.print("How many objects do you want to create:");
Scanner reader = new Scanner(System.in);
int amount = reader.nextInt();
Thing[] things = new Thing[amount];
for(int i = 0; i<amount; i++) {
things[i] = new Thing();
}
Thing.numberOfObjects();
}
class Thing{
int count;
public void numberOfObjects(){
System.out.println(count);
}
}
}
You forgot 3 things:
1- to increment the count of the objects when they are created. You can do so in the Thing constructor.
2- declare the count variable as static to allow the variable to be shared between all objects of type Thing.
3 - to declare the numberOfObjects method as static since it is a class method that you are accessing via the Thing class
Try this:
import java.util.Scanner;
public class NumberOfObjects{
public static void main(String args[]) {
System.out.print("How many objects do you want to create:");
Scanner reader = new Scanner(System.in);
int amount = reader.nextInt();
Thing[] things = new Thing[amount];
for(int i = 0; i<amount; i++) {
things[i] = new Thing();
}
Thing.numberOfObjects();
}
class Thing{
private static int count = 0;
public Thing(){
count++;
}
public static void numberOfObjects(){
System.out.println(count);
}
}
}
class Box
{
//Keep track of all your objects
Thing[] objs;
int cursor;
public Box(int countOfObjects)
{
objs = new Thing[countOfObjects];
}
//add new object to the array
public void add(Thing thing)
{
objs[cursor++] = thing
}
//gets the object
public Thing getThing(int pos)
{
if(pos < 0 || pos >= objs.lenght())
throw;
return objs[pos];
}
//count the objects
public int numberOfObjects()
{
System.out.println(objs.lenght());
return objs.lenght();
}
}
}
class Thing()
{
//any field you need to store
}
Your main should look like this
public static void main(String args[]) {
System.out.print("How many objects do you want to create:");
Scanner reader = new Scanner(System.in);
int amount = reader.nextInt();
Box box = new Box(amount);
for(int i = 0; i<amount; i++) {
box.Add(new Thing());
}
box.numberOfObjects();
}
Declare count as static and add count in constructor.Another import thing,move Thing class out of NumberOfObjects Class,otherwise, the Thing class is an inner class, you will need create NumberOfObjects instance first and use this object to create Thing instance.
import java.util.Scanner;
public class NumberOfObjects{
public static void main(String args[]) {
System.out.print("How many objects do you want to create:");
Scanner reader = new Scanner(System.in);
int amount = reader.nextInt();
Thing[] things = new Thing[amount];
for(int i = 0; i<amount; i++) {
things[i] = new Thing();
}
Thing.numberOfObjects();
}
}
class Thing{
private static int count ;
public Thing(){
count++;
}
public static void numberOfObjects(){
System.out.println(count);
}
}
I want to create a game and I need to read file from the notepad
when I use my loadfile.java alone, it work very well. Then, I would like to copy my data into datafile.java as it will be easier for me to do the fighting scene. However, I can't copy the array in my loadfile.java to the datafile.java and I don't understand why.
import javax.swing.*;
import java.io.*;
import java.util.Scanner;
public class loadfile
{
static String filename = "Save.txt";
static int size = 4;
static int s;
static int[] number;
static String[] line;
private static void load() throws IOException
{
BufferedReader reader = new BufferedReader(new FileReader(filename));
while (reader.readLine()!= null)
{
size++;
}
size -= 4;
reader.close();
line = new String[size];
number = new int[size];
BufferedReader reader2 = new BufferedReader(new FileReader(filename));
for (int i = 0; i < size; i++)
{
line[i] = reader2.readLine();
}
reader2.close();
for (int i = 4; i < size; i++)
{
number[i] = Integer.parseInt(line[i]);
}
}
public static String[] getData()
{
return line;
}
public static int[] getNumber()
{
s = size - 4;
int[] num = new int[s];
for (int i = 0; i < s; i++)
{
num[i] = number[i+4];
}
return num;
}
public static int getDataSize()
{
return size;
}
public static int getNumberSize()
{
return size - 4;
}
This is my loadfile.java
I use the file with 4 names and 9 * n int in the notepad as I want to check whether I have the character first before I read the file. However, before I can handle this problem, I got another problem that I can't copy the array into my datafile.java
The datafile.java is separate with two constructor. One is for Starting the game and one is for loading the data. The constructor with the (int num) is the problem I have. First, I would like to show the java first:
import java.util.Arrays;
import java.io.*;
public class datafile
{
private static String[] data;
private static int[] number;
private static String[] name;
private static int[] a, d, s;
private static int[] hp, maxhp;
private static int[] mp, maxmp;
private static int[] lv, exp;
public datafile()
{
initialization();
name[0] = "Pet";
a[0] = 100;
d[0] = 100;
s[0] = 100;
hp[0] = 500;
mp[0] = 500;
maxhp[0] = 500;
maxmp[0] = 500;
exp[0] = 100;
lv[0] = 1;
}
public datafile(int num) throws IOException
{
initialization();
loadfile l = new loadfile();
for (int i = 0; i < l.getNumberSize(); i++)
{
number[i] = l.getNumber()[i];
}
for (int i = 0; i < l.getDataSize(); i++)
{
data[i] = l.getData()[i];
}
for(int i = 0; i < 4; i++)
{
name[i] = data[i];
}
for(int i = 0; i < 4; i++)
{
a[i] = number[1+(i*9)];
d[i] = number[2+(i*9)];
s[i] = number[3+(i*9)];
hp[i] = number[4+(i*9)];
mp[i] = number[5+(i*9)];
maxhp[i] = number[6+(i*9)];
maxmp[i] = number[7+(i*9)];
lv[i] = number[8+(i*9)];
exp[i] = number[9+(i*9)];
}
}
public static String getName(int n)
{
return name[n];
}
public static int getAttack(int n)
{
return a[n];
}
public static int getDefense(int n)
{
return d[n];
}
public void initialization()
{
name = new String[3];
a = new int[3];
d = new int[3];
s = new int[3];
hp = new int[3];
mp = new int[3];
maxhp = new int[3];
maxmp = new int[3];
lv = new int[3];
exp = new int[3];
}
public static void main (String[] args) throws IOException
{
new datafile(1);
}
}
When I run the program, the debugging state this line
data[i] = l.getData()[i];
as an error
I don't know what wrong with this line and I tried so many different ways to change the way the copy the method. However, it didn't work
The error says this:
Exception in thread "main" java.lang.NullPointerException
at datafile.<init>(datafile.java:38)
at datafile.main(datafile.java:92)
I hope you guys can help me with this problem because I don't want to fail with my first work
in your datafile(int num)
you call
loadfile l = new loadfile();
but you never call the load() method on you loadfile
l.load();
Edit: my bad, I didn't see your initialization method, but regardless, I'm going to stick with my recommendation that you radically change your program design. Your code consists of a kludge -- you've got many strangely named static array variables as some kind of data repository, and this suggests that injecting a little object-oriented design could go a long way towards creating classes that are much easier to debug, maintain and enhance:
First I recommend that you get rid of all of the parallel arrays and instead create a class, or likely classes, to hold the fields that need to be bound together and create an ArrayList of items of this class.
For example
public class Creature {
private String name;
private int attack;
private int defense;
// constructors here
// getters and setters...
}
And elsewhere:
private List<Creature> creatureList = new ArrayList<>();
Note that the Creature class, the repository for some of your data, should not be calling or even have knowledge of the code that loads the data, but rather it should be the other way around. The class that loads data should create MyData objects that can then be placed within the myDataList ArrayList via its add(...) method.
As a side recommendation, to help us now and to help yourself in the future, please edit your code and change your variable names to conform with Java naming conventions: class names all start with an upper-case letter and method/variable names with a lower-case letter.
I'm trying to fill an array using a method and later print that array out.
However when I try to do so all it gives me are zeroes. I think my fill method is not working properly but I'm not sure why. I'm trying to understand arrays but so far no good. I would prefer an explanation rather than an answer. If I can get this myself it would be best.
import java.util.Scanner;
public class diverScore {
static double score = 0;
static double validDegreeOfDiff = 0;
public static void main(String[] args) {
double[] score = new double[6];
inputAllScores(score);
printArray(score);
}
public static double[] inputAllScores(double[] x) {
Scanner s = new Scanner(System.in);
double[] array_score = new double[6];
for (int i = 0; i < 6; i++) {
System.out.println("What is the score given by the judge?");
array_score[i] = s.nextDouble();
}
return array_score;
}
public static void printArray(double[] j) {
for (int i = 0; i < 6; i++) {
System.out.println("The array is:" + j[i]);
}
}
}
In your inputAllScores, you're writing to a new local array, and returning it, but you're not using the returned array. It would be better if you wrote to the array that you passed into that method (which inside the method is called x).
try
import java.util.Scanner;
public class DiverScore {
static double score = 0;
static double validDegreeOfDiff = 0;
public static void main(String[] args) {
// double[] score = new double[6];
double[] score = inputAllScores(/*score*/);
printArray(score);
}
public static double[] inputAllScores(/*double[] x*/) {
Scanner s = new Scanner(System.in);
double[] array_score = new double[6];
for (int i = 0; i < 6; i++) {
System.out.println("What is the score given by the judge?");
array_score[i] = s.nextDouble();
}
return array_score;
}
public static void printArray(double[] j) {
for (int i = 0; i < 6; i++) {
System.out.println("The array is:" + j[i]);
}
}
}
double[] score = new double[6];
This line simply initializes an array of type double with 6 indexes allocated for it, with each resulting in 0 when printed out.
You could simply change the code in main to this, thus actually using the return value of the inputAllScores function.
public static void main(String[] args) {
double[] score = new double[6];
printArray(inputAllScores(score));
}
HTH