This question already has answers here:
NullPointerException when Creating an Array of objects [duplicate]
(9 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I get a NullPointerException at line 14 the one that says:
points[i].x = new Random().nextInt(30);
My full Code:
import java.util.Random;
public class RandomPoints {
public class Point {
public int x;
public int y;
}
public static void main(String[] args) {
Point[] points = new Point[100];
for(int i = 0; i < points.length; i++) {
points[i].x = new Random().nextInt(30);
points[i].y = new Random().nextInt(30);
System.out.println(points[i].x + " " + points[i].y);
}
}
}
When you say Point[] points = new Point[100]; it only allocates an array with room for 100 Point references (it doesn't allocate any Point instances). You need to allocate an instance for the index before you can access it, something like
Point[] points = new Point[100];
for(int i = 0; i < points.length; i++) {
points[i] = new Point(); //<-- like so.
Also, it would be better to reuse one Random created outside your array.
Random rand = new Random();
otherwise you reseed (twice) on every iteration. Meaning your numbers won't be very random.
Related
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Java: Why does this swap method not work? [duplicate]
(10 answers)
Closed 4 years ago.
package main;
public class Main {
double radius;
public Main(double newRadius) {
radius = newRadius;
}
public static void main (String [] args) {
Main x = new Main(1);
Main y = new Main(2);
Main temp;
// try to swap first time
temp = x;
x = y;
y = temp;
System.out.println(x.radius + " " + y.radius);
x = new Main(1);
y = new Main(2);
// try to swap second time
swap(x, y);
System.out.println(x.radius + " " + y.radius);
}
public static void swap(Main x, Main y) {
Main temp = x;
x = y;
y = temp;
}
}
Why the first time worked, but the second time didn't? The first one did the swap, but the second one didn't. I'm passing the reference to the function. Why this doesn't work?
Your mistaking how references are passed, your making a scope where references are swapped and then that scope ends.
Try storing the value of the field in the variable e.g. temp = x.radius and then assign to y.radius.
The reason why it works the first time is that the scope is the same.
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 5 years ago.
I am trying to find a way to print the contents of the array, while using a for loop. This is a fairly new section in java to me, as I am a beginner. Any help is appreciate in concerns to my question. My question is would I move the "Random" assessor method into the mutator method or am I just completely wrong and have to do something else.
import java.util.Random;
public class ArrayPractice {
private int[] arr;
private final int MAX_ARRAY_SIZE = 300;
private final int MAX_VALUE = 100;
public ArrayPractice() {
// initialize array
arr = new int[MAX_ARRAY_SIZE];
// randomly fill array with numbers
Random rand = new Random(1234567890);
for (int i = 0; i < MAX_ARRAY_SIZE; ++i) {
arr[i] = rand.nextInt(MAX_VALUE) + 1;
}
}
public void printArray( ) {
}
public static void main(String[] args) {
ArrayPractice ap = new ArrayPractice();
System.out.println("The contents of my array are: ");
ap.printArray();
System.out.println("");
}
}
My question is would I move the "Random" assessor method into the
mutator method or am I just completely wrong and have to do something
else.
You don't have to. Just use a loop to iterate through the array which is already filled in the constructor.
public void printArray( ) {
for (int i = 0; i < MAX_ARRAY_SIZE; ++i) {
System.out.println(arr[i]);
}
}
By the way, with Java 8, you can write less lines of code to achieve the same result:
Arrays.stream(arr).forEach(System.out::println);
public void printArray() {
//Print array
System.out.println(Arrays.toString(arr));
//another method with for loop
for (int i = 0; i < arr.length; i++)
{
System.out.println(arr[i])
}
}
Note there is plenty of other techniques
In terms of writing clean code, it would probably be good to move this bit of code into its own private method within the class, and calling that within the constructor.
public ArrayPractice() {
// initialize array
arr = new int[MAX_ARRAY_SIZE];
populateArray();
}
private void populateArray() {
// randomly fill array with numbers
Random rand = new Random(1234567890);
for (int i = 0; i < MAX_ARRAY_SIZE; ++i) {
arr[i] = rand.nextInt(MAX_VALUE) + 1;
}
}
Then in your printArray() method you can loop through the array and call System.out.println( ) for each item.
public void printArray( ) {
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
If you come from a more functional background, I can show you how to write this more functionally using Java 8 lambdas. Let me know.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I've been trying to work around this NullPointerException issue:
Exception in thread "main" java.lang.NullPointerException
at LinearSearcher.<init>(LinearSearcher.java:12)
at DemoSearches.main(DemoSearches.java:4)
through researching, I found that this exception occurs when you declare a reference type but don't create an object. In my case it is when I am trying to declare LinearSearcher
I've tried to understand this with my code but i'm having difficulties
Code for LinearSearcher:
public class LinearSearcher implements Searcher {
private int[] numbers;
public LinearSearcher() {
numbers[0] = 1; // Line 12 Here
numbers[1] = 10;
numbers[2] = 20;
numbers[3] = 30;
numbers[4] = 40;
numbers[5] = 50;
numbers[6] = 60;
numbers[7] = 70;
numbers[8] = 80;
numbers[9] = 90;
}
public int searchFor(int key) {
for (int i = 0; i < numbers.length; i++){
if (numbers[i] == key) {
return i;
}
}
return NOT_FOUND;
}
public void display() {
for (int i = 0; i < numbers.length; i++){
}
}
}
Class where LinearSearcher is declared:
public class DemoSearches {
public static void main(String args[]) {
LinearSearcher search = new LinearSearcher(); // Line 4 Here
search.display();
search.searchFor(50);
search.searchFor(100);
}
}
numbers is null because you haven't initialized it. You can change
private int[] numbers;
to
private int[] numbers = { 1, 10, 20, 30, 40, 50, 60, 70, 80, 90 };
and eliminate the problem. Other solution, add
numbers = new int[10];
Before your current assignments.
You never initialize the numbers array so when you try to access it in the LinearSearcher constructor you are trying to access a nonexistent array. So an exception is thrown.
You need to do numbers = new int[10]; before doing numbers[0] etc. This will create the object so it can be used.
This question already has answers here:
Why can't I do assignment outside a method?
(7 answers)
Closed 5 years ago.
class example{
int[] quiz = new int[] { 10 , 20 }; //location 1
public static void main(String[] args) {
int[] test = new int[2]; // location 2
test[0] = 2;
test[1] = 3;
// other code
}
The above code run correctly. However the code below causes an error. My reasoning for the error is since quiz is declared outside the method it needs to be initialized immediately. However I am not sure if this is a correct explanation.
class example{
int[] quiz = new int[2]; //location of error
quiz[0] = 10;
quiz[1] = 20;
public static void main(String[] args) {
int[] test = new int[2]; // location 2
test[0] = 2;
test[1] = 3;
//other code
}
You would need an initialization block to do it the second way,
int[] quiz = new int[2];
{
quiz[0] = 10;
quiz[1] = 20;
}
I have a class ConvexHull which I have to implement for my class. One of the instance variables is an array that holds the object Points.
private Points[] points;
When I go to add a Point to the array in the constructor, I'm given a NullPointerException.
public ConvexHull(int n) throws IllegalArgumentException
{
if (n < 1)
throw new IllegalArgumentException();
else {
Random rand = new Random();
for (int i=0; i<n; i++)
{
int x = rand.nextInt(101)-50;
int y = rand.nextInt(101)-50;
Point p = new Point(x,y);
this.points[i] = p; // NullPointerException is thrown.
this.numPoints = points.length;
}
}
}
Basically, I have no idea why this isn't working and need some help.
Please allocate memory for
private Points[] points;
like this..
public ConvexHull(int n) throws IllegalArgumentException
{
if (n < 1)
throw new IllegalArgumentException();
else {
points=new Points[n]; //this is the line that is added
Random rand = new Random();
for (int i=0; i<n; i++)
{
int x = rand.nextInt(101)-50;
int y = rand.nextInt(101)-50;
Point p = new Point(x,y);
this.points[i] = p; // NullPointerException is thrown.
this.numPoints = points.length;
}
}
}
Because you didn't instantiate the array points. You need something like
private Point[] points = new Point[i];
where i is an integer specifying the array's length. Otherwise points is null and a NullPointerException is thrown.
By the way I don't think there is a class called Points. If you create your own class (in fact you probably don't have to), don't name it using a plural noun.
Yeah the problem with your code is that you have declared the array but you have not initialized the array like
points = new Point[sizeOfYourArray];
and it should fix your problem because there is nothing to start with in the first place so when you initialize it it should be fine.
You didn't new an object for field "pointer" like pointer p = new pointer();, so you will get a NullPointerException.