How to add an element in a null array in java? - java

I have created a function that takes an array and outputs another array. So I have declared the result array (which will be the output) as null cause the size varies and depends on the inputted array. (for eg. if I enter an array of integers and then I want to output the array containing even numbers from that array). So I will be using for or while loops and I want to know that how I can add the integer to that null array. I tried but I get a null pointer exception that says cannot store to int array cause "array" is null.
sorry but I can't use more advanced techniques cause I am new to java (I need to make this without using arraylist library as I am learning coding I found those type of questions which tries to make you perfect in i specific topic and then they take you to next step so u can be more prepared)
I am using this code and I want to know that add an element to my result array or should I initialized it as null or something else cause the size depends on inputted array in this code I am getting null pointer exception
public static int[] even(int[] numbers) {
int[] result = null;
int even = 0;
int i = 0;
int a = 0;
while (i < numbers.length) {
if (numbers[i] % 2 == 0) {
even = numbers[i];
result[a] = even;
a++;
}
i++;
}
return result;
}

The array's size needs to be initialized. If you want dynamic storage , read about List and Collection.
Here, if you still want to use array, you need the count.
int a = 0;
while (i < numbers.length) {
if (numbers[i] % 2 == 0) {
a++;
}
i++;
}
Then after this, you can initialize it as int[] result = new int[a];

public static int[] even(int[] numbers) {
int[] result = null;
int j = 0;
int a = 0;
while (i < numbers.length) {
if (numbers[j] % 2 == 0) {
a++;
}
j++;
}
result = new int[a];
int even = 0;
int i = 0;
int b = 0;
while (i < numbers.length) {
if (numbers[i] % 2 == 0) {
even = numbers[i];
result[b] = even;
b++;
}
i++;
}
return result;
}

Related

Summing two int arrays of different lengths into one int array. Java [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 4 years ago.
I've got a project that requires me to write a method to sum two integer arrays into a single integer array. The requirements are that each value of the array may only have one numeral in it. For example "1" but not "11" and the original two arrays may be different lengths. The idea behind the project is that these arrays are supposed to have lengths longer than the allowed length for an integer variable. We are supposed to create this new array so we can print out each position, essentially doing math with large numbers without using longs.
This is what I currently have.
public static int[] add ( int[] arr1, int[] arr2) {
int length;
if (arr1.length >= arr2.length) {
length = arr1.length;
}
else {
length = arr2.length;
}
int[] smallAr = new int [length];
int[] bigAr = new int [length];
if (arr1.length > arr2.length) {
for (int i = 0; i < length; i++) {
smallAr[i] = arr2[i];
bigAr[i] = arr1[i];
}
}
else {
for (int i = 0; i < length; i++) {
smallAr[i] = arr1[i];
bigAr[i] = arr2[i];
}
}
int[] addition = new int[length];
for (int i = 0; i < length; i++) {
if (i > smallAr.length -1) {
addition[i] = bigAr[i];
}
else {
addition[i] = bigAr[i] + smallAr[i];
}
}
return addition;
}
This currently gives an out of bounds error when ran. I also understand that this would not properly work if the array needed an extra space for a carry. Any help on this would be great!
Step one, create a new array of sufficient length - find the maximum of arr1.length and arr2.length. Step two, assign the sum of each valid index from the two arrays to the output array - default the value to zero if the array length is greater than or equal to the current index. Step three, return the new array. Like,
public static int[] add(int[] arr1, int[] arr2) {
int[] r = new int[Math.max(arr1.length, arr2.length)];
for (int i = 0; i < r.length; i++) {
r[i] = (i < arr1.length ? arr1[i] : 0) + (i < arr2.length ? arr2[i] : 0);
}
return r;
}

Compare element of int array to an int

Hi I'm seeking to understand in java how you can take an int array and then in an if statement compare one single element from the int array against just a declared int. I want to just simply compare two ints against each other but one is inside of an int array. The == I guess doesn't work?
for (int count = 5; count >= 0; count--) {
if (gameBoardTokens[count] == 0) {
if (playerOneTurn) {
gameBoardTokens[count] = 1;
count = 0;
} else {
gameBoardTokens[count] = 2;
count = 0;
}
}
}
you need to change this (count < -1) for this (count > -1)
because at first 5 > -1 not -1 > 5.
gameBoardTokens[count] == 0 works. The thing that makes your code unfunctional is that the code in the for-loop is never executed, because count is initially 5, for which count < -1 is false. So the loop immediately aborts.

Excluding duplicate values in an array (Java) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
For an assignment I must read values from a file, and print them on the screen unless they are duplicate values. My approach was to create two arrays with the same values, then somehow compare them and if they are not equal, it would not print. Here is what I have:
import java.io.*;
import java.util.Scanner;
public class Set8_Prog4
{
public static void main (String[] args) throws IOException
{
FileReader i = new FileReader("Set8_Prog4 numbers.txt");
Scanner j = new Scanner(i);
int length = 0;
while (j.hasNextInt())
{
length++;
}
int[] values = new int[length];
int[] values2 = new int[length];
int k = 0;
while (j.hasNextInt())
{
values[k] = j.nextInt();
k++;
}
k = 0;
while (j.hasNextInt())
{
values2[k] = j.nextInt();
k++;
}
k = 0;
int m = 0;
while (values[k] != values2[m] && k < values.length)
{
while (m < values.length)
{
m++;
}
System.out.println(values[k]);
k++;
}
j.close();
}
}
It compiles, but you can probably tell it doesn't get the job done. I have been frying my brain trying to figure out how to get it to work. I could use some help. Oh and we can't use things like Array Lists, Hashsets, or anything like that. Just arrays.
UPDATED CODE:
import java.io.*;
import java.util.Scanner;
public class Set8_Prog4
{
public static void main (String[] args) throws IOException
{
FileReader i = new FileReader("Set8_Prog4 numbers.txt");
Scanner j = new Scanner(i);
int length = 0;
while (j.hasNextInt())
{
length++;
}
int[] values = new int[length];
int[] values2 = new int[length];
int k = 0;
while (j.hasNextInt())
{
values[k] = j.nextInt();
k++;
}
k = 0;
while (j.hasNextInt())
{
values2[k] = j.nextInt();
k++;
}
int m;
for (k = values.length; k >= 0; k--)
{
boolean found = false;
for (m = 0; m < values.length; m++)
{
if ((values[k] == values2[m]) && (k != m))
{
found = true;
continue;
}
if (!found)
{
System.out.println(values[k]);
}
}
}
}
}
I get nothing when I run it. No errors though.
You can add values to the array as you print them and each time you print the next value check an make sure it is not already in the array if it is don't print if it is not print and add the value to the array. You should only need one array for this.
Basically, you're never comparing values[k] with values2[m] properly, because when you do, m always equals values.length().
Change your nested while loops to the below:
for (int k=0; k < values.length; k++) {
boolean found = false;
for (int m=0; m < values.length; m++)
if ((values[k] == values2[m]) && (k != m)) {
found = true;
continue;
}
if (!found)
System.out.println(values[k]);
}
Or, for more efficient code (and better marks), check if the integer is present in the array when it is read from the file. If the integer is already there, don't add it to the array, otherwise, do. As the other answer states, this approach would only require 1 array, and is more memory efficient as a result.
Another tip to increase your marks - think about your variable names (values and values2 aren't brilliant names)
Ok, so here is a sample method that will add values to an array, only if they don't already exist in it:
// int[] array containing values
// value currently being added
// index where the value is currently being added
void addValueWithoutDuplication(int[] array, int value, int index) {
for(int i = 0; i < index; i++) { // iterate over all the values that are currently in the array
if(array[i] == value) { // if the value we are adding is a duplicate of a value in the array
return; // return out of this method and don't add the value
}
}
array[index] = value; // if we reached this point, value is not a duplicate and we can add it to the array at the index
}
If you add each value using this method, your array will not contain any duplicates and then you can just iterate over the array and print the values.
Since values and values2 have the exact same contents and you set k = 0 and m = 0 you will never actually get into your while loop while (values[k] != values2[m] && k < values.length). Also(if you continue using your current approach), once you figure out what you need to iterate over for that while loop, consider the fact that once you do get into that loop, m goes from the index that gets you into the array all the way to values.length which may or may not throw an index of bounds exception when you test while (values[k] != values2[m] && k < values.length) the next time :) Since this is homework, I'll let you figure the rest out.

Loop runs 2 times, then Array index out of bounds exception

I'm making a class that deletes an element at a specific position in an Integer array. It runs perfectly the first 2 times, but then for some reason it decides that the ArrayIndexOutOfBoundsException should be thrown.
my code:
public class Arraydeletion {
public static int[] delete (int[] a, int delValPos){
int[] newArray = new int[a.length-1];
for (int i = 0; i < newArray.length; i++) {
if(a[i]!=a[delValPos]){ //<--- ArrayIndexOutOfBoundsException points here
newArray[i] = a[i];
}
else if(a[i] == a[delValPos]){
newArray[i] = a[delValPos+=1];
}
}
return newArray;
}
}
You never check that delValPos is a valid index within the input array a. Your method must validate it before doing anything else, and throw an exception if an invalid delValPos is supplied.
Working code would look like this :
public class Arraydeletion {
public static int[] delete (int[] a, int delValPos){
if (delValPos < 0 || delValPos >= a.length)
throw new SomeException(); // TODO decide which exception to throw
int[] newArray = new int[a.length-1];
int index = 0;
for (int i = 0; i < a.length; i++) {
if (i!=delValPos) {
newArray[index] = a[i];
index++;
}
}
return newArray;
}
}
This makes the code much simpler. It copies all the elements except a[delValPos] to the output array. Note that you can't use the same index i for reading elements from the input array and writing elements to the output array, because after you pass the deleted element, each i'th element in the input array would be written to the (i-1)'th place in the output array.
I tested your code and i retrieve outOfBoundException only if delValPos == a.length, so you can check this before loop.
However your code is pretty strange, it seems you want to clone an array except for one element in a certain position, if so this will work better:
public static int[] delete (int[] a, int delValPos){
int delValPos = 0;
int[] a = {1,2,3,4,5,6,7,8,9};
int[] newA = new int[a.length - 1];
if(a.length > delValPos) {
for(int i = 0 ; i < newA.length ; i++) {
if(delValPos < i && delValPos != 0) {
newA[i] = a[i];
}
else
newA[i] = a[i + 1];
}
}
return newA;
}

Why am I receiving an ArrayIndexOutofBoundsException?

In my JAVA code, I am given a data and I have to find the mode. Everything successfully compiled, and every method works. However, when I try to access the mode, I get an java.lang.ArrayIndexOutOfBoundsException: 987 in my terminal window. The highlighted portion is in the following method, which is one of my max methods. The data array, by the way, is just int [] data.
public int maxOfData(int [] oa)
{
int max = oa[0];
for (int i = 1; i < size; i++)
{
if (oa[i] > max)
max = oa[i];
}
return max;
}
The exception is on the line if(oa[i] > max)
And the mode code is this:
public int[] modeOfData()
{
int[] tally = new int[maxOfData() + 1];
for( int i = 0; i < size; i++)
{
tally[data[i]]++;
}
//max contains frequency of modes
int max = maxOfData (tally);
int count = 0;
for( int i = 0; i < tally.length; i++)
{
if( tally[i] == max )
count++;
}
//count occurence of maxValue in tally (for)
//that determines how many modes there are
//declare another int called modes
int[] modes = new int[count];
//size of array should be count
//loop through tally and extract modes: it's the index value.
int pos = 0;
for( int i = 0; i < tally.length; i++)
{
if(tally[i] == count)
modes[pos++] = i;
}
return modes;
//modes are where the values are == max
}
My other max for data is the same but data instead of oa. I need both max methods, just like that, according to my teacher. So what do I do? How do I fix this?
I think the line
for (int i = 1; i < size; i++)
should be
for (int i = 1; i < oa.length; i++)
ArrayIndexOutOfBound Exception is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array. Whenever you iterate an Array object. you need to iterate while checking the index is always lesser than its length
for example,
for(int i=1;i<array.length;i++){
//access array content in ith position
System.out.println(array[i]);
}
Your size variable has the value of an illegal array index. that's the problem
Look at the number stored into size and then check to see what size you declared oa[] to be. If size is bigger than the size of oa[] then you have a problem.
Problem is in this part of code
int max = oa[0];
for (int i = 1; i < size; i++)
{
if (oa[i] > max)
max = oa[i];
}
rewrite the method maxOfData(int [] oa) with proper checks like this
public int maxOfData(int[] oa) {
if (oa == null) {
throw new IllegalArgumentException("Input array is null");
}
int max=oa[0];
for (int i = 1; i < oa.length; i++) {
if (oa[i] > max)
max = oa[i];
}
return max;
}
if input array is null it should not be processed.

Categories

Resources