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.
Related
This question already has answers here:
Creating random numbers with no duplicates
(20 answers)
Generating 10 random numbers without duplicate with fundamental techniques
(10 answers)
How to generate random numbers from 0 to 100 without duplicates when user enters the size of the array in Java?
(5 answers)
Closed last month.
I have a problem in generating the non-duplicate numbers. I tried to do the do-while loop but it seems not working. How do I fix it?
import java.util.Arrays;
public class Assignment2_Q2 {
public static void main (String[] args){
int[] myList = new int[10];
number(myList);
sortedOrder(myList);
display (myList);
}
public static void number(int[] list){
int random;
random = (int)(Math.random() * 21);
list[0] = random;
for (int i = 1; i < list.length; i++){
do{
random = (int)(Math.random() * 21);
list[i] = random;
}while(list[i] == list[i-1]);
}
}
public static void sortedOrder(int[] list){
java.util.Arrays.sort(list);
}
public static void display(int[] list){
System.out.println("The array in the sorted order:\n" + Arrays.toString(list) + "\n");
}
}
Example output:
The array in the sorted order:
[0, 0, 6, 7, 13, 16, 16, 18, 19, 20]
As you can see, 0 and 16 come twice each. They are duplicates. I have also seen a number coming three times in one run.
Generate a list of numbers 1-20, then shuffle the list, then take the first 10.
List<Integer> nums = IntStream.rangeClosed(1, 20).boxed().collect(toList());
Collections.shuffle(nums);
nums = nums.subList(0, 10);
Your problem is in while(list[i] == list[i-1]) This isn't checking that the list doesn't contain the random number you generated. It's checking that the last 2 generated numbers aren't the same You're not checking that the previous numbers didn't match. The right way to do this is:
for (int i = 0; i < list.length; i++){
bool found = false;
do{
random = (int)(Math.random() * 21);
for(int j=0; j<i; j++) {
if(list[j] == random) {
found = true;
}
}
}while(found = false);
list[i] = random;
}
public static void main(String[] args) {
int[] myList = new int[10];
number(myList);
}
public static void number(int[] list) {
int random;
Set<Integer> used = new HashSet<>();
for (int i = 0; i < list.length; i++) {
do {
random = (int) (Math.random() * 21);
} while (used.contains(random)); // check if the number has been used before
list[i] = random;
used.add(random);
}
}
This question already has answers here:
Find first element by predicate
(8 answers)
Closed 5 years ago.
I have tried with the below code. Please help me to get the output.
I want simple code that I can understand.
Suppose that number is 40:
public class PositionofElementinArray {
public static void main(String args[]) {
int arr[] = {10, 20, 30, 40, 50};
int value = 40;
for(int i=0; i < arr.length; i++)
if(arr[i]==value){
System.out.print(arr[i]);
}
else{
System.out.print("no element found");
}
}
}
if(arr[i]==value) here you are checking the value.
And i is the index/position
This code will print the value and its position.according to your example value is 40 position is 3.
class Test
{
public static void main (String[] args)
{
int arr[] = {10, 20, 30, 40, 50};
int value = 40;
for(int i=0; i < arr.length; i++)
{
if(arr[i]==value){
System.out.print("value is"+arr[i]+" "position is"+i);
}
}
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am storing sum of all pairs of an array element to pairSum[] array.
For this I have created PairSum class which store two elements and their sum.
But I am getting null Pointer Exception on line pairSum[k].sum = v
I have created array as
PairSum[] pairSum = new PairSum[val];
What am I doing wrong?
public class test {
class PairSum{
int first;
int second;
int sum;
}
public static void findElements(int arr[], int n){
int val = (n*(n-1))/2;
PairSum[] pairSum = new PairSum[val];
int k=0;
for(int i=0;i<n-1;i++){
for (int j=i+1;j<n;j++){
int v = arr[i] + arr[j];
System.out.println("sum..." + v);
pairSum[k].sum = v;//NullPointerException here
System.out.println("valll.." + pairSum[k]);
pairSum[k].first = arr[i];
pairSum[k++].second = arr[j];
}
}
}
public static void main(String[] args) {
int arr[] = {10, 20, 30, 40, 1, 2};
int n = arr.length;
findElements (arr, n);
}
}
As of now, you have only created an array that can hold objects of type PairSum. You need to instantiate every PairSum object individually:
pairSum[k] = new PairSum();
Before accessing any PairSum in your pairSum array.
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.
I'm trying to learn Java and I am currently writing a program that will split an array of integers into two sub-arrays, one containing the positive values and the other the negative values.
Due to the fact that the sizes of the two sub-arrays can not be specified from the start (because this program should work on any array of integers) I wrote two methods which will calculate the sizes of the two sub-arrays (maxNeg and maxPos). Afterwards, the two sub-arrays (arrayNegative and arrayPositive) are initialized having the the two corresponding sizes.
The problem is that, when I try to populate the two arrays using the arraySorter(), the compiler gives me the ArrayIndexOutOfBoundsException: 0 error right at the first iteration inside the arraySorter() method.
Note 1: The issue doesn't occur when values are assigned to the maxNeg and maxPos variables from the start.
Note 2: I know this type of problem is usually solved using ArrayLists for storing the positives and negatives, but my assignment's requirements force me to do this using only arrays.
public class sortMethod {
public int max; // max = main array length
public int maxNeg; // the length of the final array that will store the
// negative integers
public int maxPos; // the length of the final array that will store the
// positive integers
public int[] intArray = new int[max];
public int getMaxNeg() {
for (int i = 0; i < max; i++) {
if (intArray[i] < 0) {
maxNeg++;
}
}
return maxNeg;
}
public int getMaxPos() {
for (int i = 0; i < max; i++) {
if (intArray[i] >= 0) {
maxPos++;
}
}
return maxPos;
}
public int[] negativeArray = new int[maxNeg];
public int[] positiveArray = new int[maxPos];
public int negIndex = 0;
public int posIndex = 0;
public void arraySorter() {
for (int a = 0; a < max; a++) {
if (intArray[a] < 0) {
negativeArray[negIndex] = intArray[a];
negIndex++;
// System.out.println(negativeArray[0]);
} else {
positiveArray[posIndex] = intArray[a];
posIndex++;
}
}
}
public sortMethod(int[] y, int z) {
this.intArray = y;
this.max = z;
}
Can someone explain why I'm keep getting the NullPointerException when using formulas to calculate the sizes of the two sub-arrays and why I don't get the error when values are assigned to 2 variables upon declaring them.
This is the main method where I created the test object:
public class ArraySort {
public static void main(String[] args) {
int[] array = { -12, 23, -22, 0, 43, -545, -4, -55, -43, -12, 0, -999};
int z = array.length;
sortMethod arrayTest = new sortMethod(array, z);
arrayTest.getMaxNeg();
arrayTest.getMaxPos();
arrayTest.arraySorter();
}
Thanks and please excuse me if my question's formating is not compliant with the site's standards, it's my first and I will try to improve in the future.
When this code is executed
public int[] negativeArray = new int[maxNeg];
public int[] positiveArray = new int[maxPos];
maxNeg and maxPos is equal to 0, so it is normal to have an out of bound exception.
To get it to works, you could initialize the arrays directly in the method so your code would become :
public int[] negativeArray;
public int[] positiveArray;
public int negIndex = 0;
public int posIndex = 0;
public void arraySorter() {
negativeArray = new int[maxNeg];
positiveArray = new int[maxPos];
for (int a = 0; a < max; a++) {
if (intArray[a] < 0) {
negativeArray[negIndex] = intArray[a];
negIndex++;
} else {
positiveArray[posIndex] = intArray[a];
posIndex++;
}
}
}
Another part of your code that is wrong is the constructor of sortMethod. You give the array length to the maximum bound, but the maximum bound is actually length - 1. so change this.max = z; to this.max = z - 1;
Also, your algorithm does not sort numbers, it simply separate negatives of positives... If you want to sort an array of number you can simplify it in one line :
Arrays.sort(array);
The order in which you define variables and methods in Java is not important. Your instance variables (e.g. your negativeArray and positiveArray) are created as soon as the class instance is created (and before the constructor is called). You therefore initialize both arrays with a size of 0.