java: newbie on indexing object arrays - java

I wish to create a java method that returns an array of type: ABCout, where class ABCout is defined as:
public class ABCout {
public int numOut;
public double[] myArray;
}
and the java method is:
public ABCout[] GetABC( double myInput ) throws Exception {
ABCout[] userABC = new ABCout[3];
userABC[0].numOut = 10;
userABC[0].myArray = new double[1];
userABC[0].myArray[0] = myInput;
/* here I only fill the 0'th element, but once working I will fill the others */
return userABC;
}
but I'm getting the error: java.lang.NullPointerException : null
Anyone see what I'm doing wrong?

You initialized the array, but not the objects in it. You probably need to do:
ABCout[] userABC = new ABCout[3];
for (int i = 0; i < userABC.length; ++i) {
userABC[i] = new ABCout();
}
Also, you need to instantiate myArray:
public class ABCout {
public int numOut;
public double[] myArray;
public ABCout() {
myArray = new double[10];
}
}

You need to instantiate the ABCout object you store in the array.
public ABCout[] GetABC( double myInput ) throws Exception {
ABCout[] userABC = new ABCout[3];
userABC[0] = new ABCout(); // instantiate
userABC[0].numOut = 10;
userABC[0].myArray = new double[1];
userABC[0].myArray[0] = myInput;
/* here I only fill the 0'th element, but once working I will fill the others */
return userABC;
}

You're declaring an array of ABCout, but you're trying to access the first element of that array before assigning it.
public ABCout[] GetABC( double myInput ) throws Exception {
ABCout[] userABC = new ABCout[3];
userABC[0] = new ABCout();
userABC[0].numOut = 10;
userABC[0].myArray = new double[1];
userABC[0].myArray[0] = myInput;
return userABC;
}

//add this
userABC[0] = new ABCount();
userABC[0].numOut = 10;
userABC[0].myArray = new double[1];
userABC[0].myArray[0] = myInput;
Although you definetly need to study some object oriented coding before doing + you should read some basic java tutorial as well

As others have stated, there was no instantiation of the 0th object and therefore you had a runtime error. You could also do this:
public ABCout[] GetABC( double myInput ) throws Exception {
ABCout[] userABC = new ABCout[3];
ABCout current = new ABCout();
current.numOut = 10;
current.myArray = new double[1];
current.myArray[0] = myInput;
userABC[0] = current;
return userABC;
}

Related

How to read copy the array with the array from another class? [In loading file]

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.

getting a length of a string from a variable array java

Im a student learning Java and this is part of my program and it is supposed to get the length of a string but the strings are all in an array. I try to run this in eclipse and it says i get an error where it sayslength = name[x].length() can someone let me know if there is a way to fix this
public class GuessName
{
Random random = new Random();
Scanner scan = new Scanner(System.in);
String[] name = new String[10];
int x,length;
char guess1,guess2,guess3;
public void names()
{
name[0] = "MARK";
name[1] = "CHARLIE";
name[2] = "MEG";
name[3] = "KYLE";
name[4] = "JUSTIN";
name[5] = "KATARINA";
name[6] = "JOEL";
name[7] = "KEVIN";
name[8] = "MICHAEL";
name[9] = "JENNA";
name[10] = "GREG";
}
public void start()
{
x = random.nextInt(10);
length = name[x].length();
}
You have an array, as follows:
String[] name = new String[10];
The number between the [] represents the size of the array. In your example, your array has a size of 10 meaning your array has 10 indexes which are [0,9] (because indexes start at 0). The last line of your names() method is:
name[10] = "GREG";
Do you know where I'm getting at?
Also, what does your main method look like? If you're receiving a NullPointerException it probably means you are calling start() before names().
I commented out the parts that was problematic. Also, you are trying to initialize 11 names as opposed to 10. Please note that arrays index starts at 0. I don't know why you have scanner object in there but you can use this block to complete your code.
import java.util.Random;
import java.util.Scanner;
public class GuessName {
// Scanner scan = new Scanner(System.in);
String[] name = new String[10];
int x,length;
char guess1,guess2,guess3;
public GuessName()
{
name[0] = "MARK";
name[1] = "CHARLIE";
name[2] = "MEG";
name[3] = "KYLE";
name[4] = "JUSTIN";
name[5] = "KATARINA";
name[6] = "JOEL";
name[7] = "KEVIN";
name[8] = "MICHAEL";
name[9] = "JENNA";
// name[10] = "GREG";
}
public void start()
{
Random random = new Random();
this.x = random.nextInt(10);
this.length = name[this.x].length();
}
public static void main(String[] args) {
GuessName gn = new GuessName();
gn.start();
System.out.println("The name is: "+gn.name[gn.x]+" and the length is: "+ gn.x);
} }

Getting NullPointer Exception when declaring LinkedBlockingQueue<String>

This is the code I have. I have getting Null Pointer Exception in the last line of the constructor (workerQueue[i] = new LinkedBlockingQueue(100);):
public class QueueThreadPool {
private BlockingQueue<String>[] workerQueue;
private Thread[] workerThreads;
private int numQueues;
private int numThreads;
public QueueThreadPool(int numThreads, int numQueues) {
this.numQueues = numQueues;
this.numThreads = numThreads;
for(int i=1; i<=numQueues; i++){
workerQueue[i] = new LinkedBlockingQueue<String>(100);
}
}
public static void main(String args[]){
System.out.println("Start...");
new QueueThreadPool(50, 11);
System.out.println("End...");
}
Please help!
Thanks!!
Array workerQueue is not instantiated which you need to do.
private BlockingQueue<String>[] workerQueue;
workerQueue is a reference of BlockingQueue<String>[] type, not a Object.
But also you cannot create a generic array of BlockingQueue<String>. Instead of that create a List of BlockingQueue<String>. Ex -
private List<BlockingQueue<String>> workerQueue= new ArrayList<>();
you can also create the list Object at constructor.
private List<BlockingQueue<String>> workerQueue= new ArrayList<>();
public QueueThreadPool(int numThreads, int numQueues) {
this.workerQueue = new ArrayList<>(numQueues); // <-- initialize the field.
this.numQueues = numQueues;
this.numThreads = numThreads;
...
You haven't initialized workerThreads. You have to do something like workerQueue= new BlockingQueue<String>[numQueues];
Two problems in the code: the field need to be initialized, the loop should go from 0 to the array-size's - 1. Here is how the fixed code should look like:
public class QueueThreadPool {
private BlockingQueue<String>[] workerQueue;
private Thread[] workerThreads;
private int numQueues;
private int numThreads;
public QueueThreadPool(int numThreads, int numQueues) {
this.workerQueue = new BlockingQueue<String>[numQueues] // <-- You need to initialize the field.
this.numQueues = numQueues;
this.numThreads = numThreads;
for(int i=0; i < numQueues; i++){ // <-- Indexing into arrays goes from 0 to size-1 (inclusive).
workerQueue[i] = new LinkedBlockingQueue<String>(100);
}
}

How to put array in an object in Java?

I am trying to clone an array and return as an object, not an array type.
z
public IntVector clone()
{
IntVector cloneVector = new IntVector(3);
int[] newItems = new int[10];
for(int i=0 ; i<itemCount_; ++i)
{
newItems[i] = items_[i];
}
cloneVector = newItems; // is there a way to do something like this??
return cloneVector;
}
Main method looks like this
public static void main(String[] args)
{
IntVector vector = new IntVector(5);
vector.push(8);
vector.push(200);
vector.push(3);
vector.push(41);
IntVector cloneVector = vector.clone();
}
*there are two other methods which makes an array:IntVector() and puts value into array:push()
Declare a new constructor for IntVector which takes an int array and a count:
IntVector(int[] data, int n) {
items_ = data.clone();
itemCount_ = n;
}
Then you can write clone like this:
public IntVector clone() {
return new IntVector(items_, itemCount_);
}
You can make that new constructor private if you like, so only clone can use it.

Data from my class is null?

I have a class holding a boolean, and two doubles, and then an array of that class, I need the boolean and doubles to have defaults values of false, 0.0, and 0.0, and then I have function that refers to an element of the array and the moment I try to access an one of the variables from the class it throws an exception saying its null. Here is my class and my function calling it.
public class PanelData {
boolean flag = false;
double tempStart = 0.0;
double tempEnd = 0.0;
}
private PanelData[] panelInfo = new PanelData[115];
private void panelInfoHandler (int i, double timeStart, double timeEnd) throws SQLException
{
if (!panelInfo[i].flag) {
delete();
insert();
panelInfo[i].flag = true;
panelInfo[i].tempStart = timeStart;
panelInfo[i].tempEnd = timeEnd;
}
else if (panelInfo[i].tempStart <= timeStart && panelInfo[i].tempEnd >= timeEnd) {
}
else
{
insert();
panelInfo[i].tempStart = timeStart;
panelInfo[i].tempEnd = timeEnd;
}
}
here is how I call the class.
panelInfoHandler(9, parsedStart, parsedEnd);
new PanelData[115] creates an array of 115 null references. Have you populated panelInfo with references to actual objects?
At a minimum, you then need to loop through that array and create new instances of PanelData for each element in the array, e.g.
for (int i = 0; i < panelInfo.length; i++)
panelInfo[i] = new PanelData();
Your array is full of null elements until you initialize it. To clarify, if you create an array of primitive objects, you get an array of default (i.e. 0) values. However, an array of Objects gets created with null elements.
int[] myIntArray = new int[10]; // 10 default values of 0
Integer[] myIntegerArray = new Integer[10]; // 10 null elements
add this line and then assign the values:
if(panelInfo[i] == null) panelInfo[i] = new PanelInfo();
You need to do something like
for(int i=0;i<115; i++)
{
PanelInfo[i] = new PanelData();
}
(Or whatever is the correct Java Syntax)
public class PanelData {
boolean flag = false;
double tempStart;
double tempEnd;
public PanelData() {
flag = false;
tempStart = 0.0;
tempEnd = 0.0;
}
private PanelData[] panelInfo = new PanelData[115];
for(int i = 0; i < 115; i++)
panelInfo[i] = new PanelData();
Creating the default constructor lets you instantiate the variables with the default values (false, 0.0, 0.0) in this case so you can test if you are getting a vanilla object back or not.

Categories