This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I am getting this run time error which says there is a null pointer exception. I am just a beginner at Java and don't understand what this means.
Error message is as follows:
Exception in thread "main" java.lang.NullPointerException
at MyLongArray.insert(MyLongArray.java:26)
at MyLongArray.main(MyLongArray.java:69)
import java.util.*;
public class MyLongArray
{
private long a[];
private int nElems;
public MyLongArray(int size)
{
long[] a = new long[size];
nElems = a.length;
}
public int find(long searchKey) {
int m =0;
for(int i=0; i < nElems; i++)
if(searchKey == a[i])
m = i;
return m;
}
public void insert(long value) {
#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.print("At what index do you want to insert? "); int i = sc.nextInt();
a[i] = value;
}
public long getElem(int index) {
return a[index];
}
public boolean delete(long value) {
long[] temp = new long[nElems];
int f = 0;
int o = 0;
for(int i=0; i < nElems; i++)
{
if(value != a[i])
{
temp[o++] = a[i];
}
else
f = 1;
}
for(int j=0; j < nElems; j++)
a[j] = temp[j];
for(int i=0; i < nElems; i++)
System.out.print(a[i] + " ");
if (f==1)
return true;
else
return false;
}
public void display()
{
for(int i =0; i < nElems; i++)
System.out.print(a[i] + " ");
}
public static void main(String[] args)
{
MyLongArray m = new MyLongArray(5);
m.insert(5);
m.find(21);
m.getElem(2);
m.delete(3);
m.display();
}
}
In constructor MyLongArray with long[] a = new long[size], you are declaring new local array a, instead of initializing your class variable array. After that in the insert method, you are trying to set elements in a non-initialized array a.
Use a = new long[size] instead of long[] a = new long[size].
You need to use a = new long[size] or this.a = new long[size] to initialize the instance field instead of declaring a local variable a inside the constructor.
Related
class Account {
int accountNumber;
int balance;
Account(int accountNumber, int balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
Account() {
int accountNumber = 0;
int balance = 0;
}
}
public class HW2 {
public static void main(String[] args) {
Account[] oneH = new Account[100];
accountNumberGenerator(oneH);
balanceGenerator(oneH);
for(int i = 0; i < oneH.length; i++){
System.out.println(oneH[i].accountNumber + " " + oneH[i].balance);
}
}
public static void accountNumberGenerator(Account[] arr){
Account one = new Account();
for(int i = 0; i < arr.length; i++){
arr[i] = one;
arr[i].accountNumber = i+1;
}
}
public static void balanceGenerator(Account[] arr){
int min = 100;
int max = 100000;
for(int i = 0; i < arr.length; i++){
Random rand = new Random();
int random_int = (int)Math.floor(Math.random()*(max-min+1)+min);
arr[i].balance = random_int;
}
}
}
I'm making an object array but it's not working.
Whenever I print each values of the Account array it just shows the 100 and random number that generated last for all values.
I'm not sure what is the problem.
public static void accountNumberGenerator(Account[] arr){
Account one = new Account();
for(int i = 0; i < arr.length; i++){
arr[i] = one;
arr[i].accountNumber = i+1;
}
}
In this method you are only creating one single instance of Account and assigning it to every element of the array.
You need to create a brand new object each iteration of your loop.
public static void accountNumberGenerator(Account[] arr){
for(int i = 0; i < arr.length; i++){
Account one = new Account();
arr[i] = one;
arr[i].accountNumber = i+1;
}
}
Here's a simple way to create 100 accounts.
public class Main {
public static void main(String[] args) {
java.util.Random r = new java.util.Random();
Account[] oneH = new Account[100];
for(int i=0; i<oneH.length; i++)
oneH[i] = new Account(i, r.nextInt(99900)+100);
for(int i = 0; i < oneH.length; i++)
System.out.printf("%3d%7d\n", oneH[i].accountNumber, oneH[i].balance);
}
}
hi so im currently trying to get past this error in my code, if anyone could explain where I went wrong, would be greatly appreciated.
public class Lab07vst100SD
{
public static void main (String[] args)
{
System.out.println();
int size = 10;
School bhs = new School(size);
System.out.println(bhs);
System.out.println(bhs.linearSearch("Meg"));
System.out.println(bhs.linearSearch("Sid"));
System.out.println();
bhs.selectionSort();
System.out.println(bhs);
System.out.println(bhs.binarySearch("Meg"));
System.out.println(bhs.binarySearch("Sid"));
System.out.println();
}
}
class School
{
private ArrayList<Student> students;
private int size;
public School (int s)
{
students = new ArrayList<Student>();
size = s;
}
public void addData()
{
String [] name = {"Tom","Ann","Bob","Jan","Joe","Sue","Jay","Meg","Art","Deb"};
int[] age = {21,34,18,45,27,19,30,38,40,35};
double[] gpa = {1.685,3.875,2.5,4.0,2.975,3.225,3.65,2.0,3.999,2.125};
for(int i = 0; i < name.length; i++)
{
students.add(new Student(name[i], age[i], gpa[i]));
}
size = students.size();
}
public void selectionSort ()
{
for(int h = 0; h < students.size(); h++)
{
int index = h;
Student least = students.get(h);
for (int t = 0; t < size; t++) {
if (students.get(t).equals(least)) {
least = students.get(t);
index = t;
}
Student temp = students.get(h);
students.set(h, least);
students.set(t, temp);
}
}
}
public int linearSearch (String str)
{
// new arraylist
ArrayList<String> names = new ArrayList<String>();
for (int q = 0; q < size; q++) {
names.add(students.get(q).getName());
}
//comparison
for (int y = 0; y < size; y++) {
if (names.get(y).equals(str))
return y;
}
return -1;
};
public int binarySearch (String str) {
// new arraylist and variables
ArrayList<String> names = new ArrayList<String>();
Boolean found = false;
int lo = 0;
int hi = size;
int mid = (lo + hi) / 2;
//for loop for to transverse the array.
for (int m = 0; m < size; m++) {
names.add(students.get(m).getName());
}
while (lo <= hi && !found) {
if (names.get(mid).compareTo(str) == 0)
{
found = true;
return mid;
}
if (names.get(mid).compareTo(str) < 0) {
lo = mid + 1;
mid = (lo + hi) / 2;
}
else {
hi = mid -1;
mid = (lo + hi) / 2;
}
}
if (found)
return mid;
else
return -1;
}
public String toString() {
String temp = "";
for (int s = 0; s < students.size(); s++) {
temp += students.get(s);
}
return temp;
}
}
also, I should mention this uses the student class.
here
public class Student
{
private String name;
private int age;
private double gpa;
public Student (String n, int a, double g)
{
name = n;
age = a;
gpa = g;
}
public String getName() {
return name; }
public int getAge() {
return age; }
public double getGPA() {
return gpa; }
public String toString()
{
String temp = name + " " + age + " " + gpa + "\n";
return temp;
}
}
the school class calls to the student class.
this is what comes back.
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:359)
at java.base/java.util.ArrayList.get(ArrayList.java:427)
at School.linearSearch(Lab07vst100SD.java:78)
at Lab07vst100SD.main(Lab07vst100SD.java:16)
I'm completely confused on why this is happening, I think it may have to do with the ArrayList, other than that, I'm not sure.
please help, and thank you
p.s. I'm new so please bear with my horrible format.
You need call addData:
public static void main (String[] args)
{
System.out.println();
int size = 10;
School bhs = new School(size);
bhs.addData(); // here
System.out.println(bhs);
System.out.println(bhs.linearSearch("Meg"));
System.out.println(bhs.linearSearch("Sid"));
System.out.println();
bhs.selectionSort();
System.out.println(bhs);
System.out.println(bhs.binarySearch("Meg"));
System.out.println(bhs.binarySearch("Sid"));
System.out.println();
}
...
class School
{
private ArrayList<Student> students;
private int size;
public School (int s)
{
students = new ArrayList<Student>(); // Here, it can throw IndexOutOfBoundsException
size = s;
}
...
Please see https://www.tutorialspoint.com/java/util/arraylist_add_index.htm
The capacity of ArrayList must be initialized before ArrayList.add method
.
I am trying to assign value of FileData's instance variable in File class
At first FileData's nextIndex should all be -1, and then it should be assigned the value of counter
I've tried get,set and FileData array to assign value but its not working and
gives NULL POINTER EXCEPTION
I've tried:
class FileData
{
int nextIndex = 0;
public void setIndex()
{
for(int i=0; i<10;i++)
{
nextIndex = -1;
}
}
}
class File
{
public static void main(String args[])
{
FileData[] FD = new FileData[10];
for(int i=0; i<5;i++)
{
FD[i].nextIndex = i;
}
}
}
When working with objects, you first have to create an instance. All I've done is add a declarator in the loop and formatted the code:
class FileData {
int nextIndex = 0;
public void setIndex() {
for (int i = 0; i < 10; i++) {
nextIndex = -1;
}
}
}
class File {
public static void main(String args[]) {
FileData[] FD = new FileData[10];
for (int i = 0; i < 5; i++) {
FD[i] = new FileData();
FD[i].nextIndex = i;
}
}
}
Note that the FileData[] FD = new FileData[10]; bit just declares an array of the type FileData, and does not yet give each object its needed storage space.
The array elements here are null:
FileData[] FD = new FileData[10];
First you need to create the objects:
for(int i=0; i < FD.length ;i++)
{
FD[i] = new FileData();
FD[i].nextIndex = i;
}
I am new to Java and am having an issue calling a method. I was hoping someone might be able to help me figure out what is going on.
The code I have is as follows:
public class QuickFindUF
{
private int[] id;
public QuickFindUF(int N)
{
id = new int[N];
for (int i = 0; i < N; i++)
id[i] = i;
}
public boolean connected(int p, int q)
{ return id[p] == id[q]; }
public void union(int p, int q)
{
int pid = id[p];
int qid = id[q];
for (int i = 0; i < id.length; i++)
if (id[i] == pid) id[i] = qid;
}
}
I took a look on Stack and figured the way to call my method would be using the following code: QuickFindUF x = new QuickFindUF(10);
When I run this I get an error that says
QuickFindUF.java:27: error: class, interface, or enum expected
QuickFindUF x = new QuickFindUF(10);
^
1 error
If someone could point me in the right direction I would really appreciate it. Thanks.
If the code you posted is your complete code, it appears you need a main method.
public class QuickFindUF
{
//
// add this so you can run code when your program executes
//
public static void main(String[] args)
{
QuickFindUF x = new QuickFindUF(10);
//
// call your methods on x here
// e.g.
// boolean connected = x.connected(2, 3);
//
}
private int[] id;
public QuickFindUF(int N)
{
id = new int[N];
for (int i = 0; i < N; i++)
id[i] = i;
}
public boolean connected(int p, int q)
{ return id[p] == id[q]; }
public void union(int p, int q)
{
int pid = id[p];
int qid = id[q];
for (int i = 0; i < id.length; i++)
if (id[i] == pid) id[i] = qid;
}
}
Your main method might be outside the class , You need to declare main method inside the class like this way :
public static void main(String []args){
QuickFindUF x = new QuickFindUF(10);
}
This is my homework(assignment). I really hope someone can help me figure out what I did wrong.
When I tried to create an object of State
state = new State(tablesize, tb);
and then tried to make a copy
State st2 = new State(state);
and then tried to modify the data in state
state.placeNumber(1,1,3);
for some reason, the data in st2 is also changed.
Below is the code. I really hope someone can point out where my mistake is.
Thanks
public class State
{
private int arraysize;
private int lastfilledx;
private int lastfilledy;
private int table[][];
//constructor
public State()
{
}
public State(State s)
{
arraysize = s.getsize();
lastfilledx = s.lastindex_x();
lastfilledy = s.lastindex_y();
table = s.gettable();
}
public State(int size, int[][] tb)
{
arraysize = size;
table = new int[size][size];
//copy the initial table which is a 2d array
table = tb;
for (int i = 0 ; i < size; i++)
{
for(int j = 0 ; j < size ; j++)
{
if ( table[i][j] == 1)
{
lastfilledx = i;
lastfilledy =j;
break;
}
}
}
}
public void placeNumber(int i, int j, int nextvalue)
{
lastfilledx = i;
lastfilledy = j;
table[i][j] = nextvalue;
}
public void printoutput()
{
for (int i=0; i < arraysize; i++)
{
for (int j=0; j < arraysize; j++)
System.out.print(" " + table[i][j]);
System.out.println("");
}
System.out.println("last fill " + lastfilledx + " " + lastfilledy);
}
public int[][] gettable()
{
return table;
}
public int getsize()
{
return arraysize;
}
public int lastindex_x()
{
return lastfilledx;
}
public int lastindex_y()
{
return lastfilledy;
}
}
public class Dikuho extends State
{
private static State state;
public static void main(String[] args) {
int tablesize = 3;
int tb[][] = new int[tablesize][tablesize];
/*****HARDCODE the table data***/
for (int i=0; i < tablesize; i++)
for (int j=0; j < tablesize; j++)
tb[i][j] = 0;
//test case for 3x3
tb[2][2] = 1;
tb[0][0] = tablesize*tablesize;
tb[0][1] = 7;
tb[1][0] = 8;
tb[2][1] = 2;
//initialize the state
state = new State(tablesize, tb);
**//Here is where the problem is. I only change the data in state but the data in st2 is also changed. I'm not sure what happen here.**
State st2 = new State(state);
state.placeNumber(1,1,3);
st2.printoutput(); **//These both printout same output which is not correct**
state.printoutput();
}
}
Your copy constructor has made a shallow copy of table 2D array. Both the original object and the copy refer to the same original array, because you assign the array reference from the original to the new object. That's fine for the int values, because the values are copied. But that's not okay for objects, for which references to the obejct are copied.
Instead of just copying the reference to the array...
table = s.gettable();
You'll need to create a new, copied array:
table = new int[arraysize][arraysize];
// 2 nested for loops here to copy the contents
public int[][] gettable()
{
return table;
}
So, both of your state objects are referencing the same array. you need to create a new array for each instance.