I want a class, that take in a possitive integer and produce a iterator that let me iterate through all possible of permutation of a list of possitive numbers under the positive integer.
eg. permulator p = paermulator(3)
p.next() -> [0,1,2]
p.next() -> [0,2,1]
p.next() -> [1,0,2]
p.next() -> [1,2,0]
...
which is 6 possible permutations in this case.
I have designed a class, but it is incredibly slow, I want to make iterate faster.
This is my design:
(I am doing it pruely for that sake that it seems possible. )
package Mathematica.complexity;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
/**
* Tthis will be a class that demonstrate what we call:
* a factorial complexity algorithm
* it's going to print all the possible permutations of some sort of collection
* in java.
* <br>
* A recursive data structure that resembles the process of permutating.
* #author dashie
*
*/
public class FactorialComplexity implements Iterator<List<Integer>>
{
private List<Integer> G_Data;
// sub recursive structure of the class.
private FactorialComplexity G_next = null;
private int G_ChoosenIndex = 0;
private boolean G_canProduceNextElement= true;
public static void main(String[] args)
{
}
public FactorialComplexity(int NumbersofElements)
{
if(NumbersofElements <0)throw new AssertionError();
this.G_Data = new LinkedList<>();
for(int i =0; i< NumbersofElements;i++)this.G_Data.add(i);
this.prepareSubStructure();
}
protected FactorialComplexity(List<Integer> argIn)
{
this.G_Data = argIn;
this.prepareSubStructure();
}
/**
* Using the internal index to return the current element it is
* pointing at.
* <br></b>I doesn't increment the internal pointer. </b>
* #return
*/
public Integer getChoosenElement()
{
//if(this.G_Data.size() == 0)return null;
return this.G_Data.get(this.G_ChoosenIndex);
}
/**
* This function serves for the iterator.
* #return
*/
public List<Integer> getPermutation()
{
// two of the base case.
if(this.G_Data.size()==0)
{
return new LinkedList<>();
}
if(this.G_Data.size()==1)
{
List<Integer> temp = new LinkedList<>();
temp.add(this.G_Data.get(0));
return temp;
}
return this.getPermutation_part1(new LinkedList<Integer>());
}
private List<Integer> getPermutation_part1(List<Integer> argIn)
{
argIn.add(getChoosenElement());
argIn.addAll(this.G_next.getPermutation());
return argIn;
}
/**
* <ol>
* <li>If the sub-structure has next element, increment the sub structure.
* <li>If not, increment the index in this instance and recreate sub structure.
* <li>be careful about the base case please.
* </ol>
*
* #return
* if this, including sub structure should be incremented.
*
*/
protected boolean increment()
{
if(this.G_next!= null)
{
boolean temp = this.G_next.increment();
int pointer = this.G_ChoosenIndex;
if(this.G_ChoosenIndex+1<this.G_Data.size())
{
if(temp)
{
this.G_ChoosenIndex++;
this.prepareSubStructure();
}
return false;
}
else
{
return (this.G_ChoosenIndex+1 == this.G_Data.size())&&temp;
}
}
else
{
//empty means not choice can make.
return true;
}
}
#Override
/**
* All the nodes are at its last index.
*/
public boolean hasNext()
{
if(!this.G_canProduceNextElement)return false;
if(this.isAllPointingAtLastIndex())this.G_canProduceNextElement=false;
return true;
}
/**
* This index in this class instance and
* all its sub structure are pointing at the last index?
* #return
*/
boolean isAllPointingAtLastIndex()
{
if(this.G_Data.size()<=1)
{
return true;
}
return this.G_ChoosenIndex+1
==
this.G_Data.size()&&this.G_next.isAllPointingAtLastIndex();
}
#Override
public List<Integer> next()
{
List<Integer> result = this.getPermutation();
this.increment();
return result;
}
public String toString()
{
String s = new String();
s+= this.G_Data+":"+this.G_ChoosenIndex+"->";
if(this.G_next!= null)s+= this.G_next.toString();
return s;
}
/**
* <ol>
* <li>Base case: the list in this instant is empty.
* <li>Make a copy of the local collection, excluding the
* element the pointer is pointing to
* <li>Make connect the this object to its sub structure and recurse.
* </ol>
*/
protected void prepareSubStructure()
{
if(this.G_Data.size() == 0)return;
List<Integer> temp = new LinkedList<>();
temp.addAll(this.G_Data);
temp.remove(this.G_ChoosenIndex);
this.G_next = new FactorialComplexity(temp);
this.G_next.prepareSubStructure();
}
public static int factorial(int n)
{
if(n<0)return 0;
if(n<=1)return 1;
return n*factorial(n-1);
}
}
To summarize:
The class is recursive like a linked list, each node contains the an index that indicate the element it is pointing at and a list of all the element got passed from the previouse node.
How Naive is this approach? How can I make it faster?
This is a better solution, inspired by https://stackoverflow.com/a/10117424/312172
To achieve, instead of getting a list of elements that are jumbled, we focus on the choices we make when deducting elements from the list.
give the function a size, and a number that is smaller than factorial(size); it will return a sequence of choices we need to make to get the permutation.
for example:
getTheIndexOfSelection(100,5)-> for a list of 5 elements, we want the 100th permutation.
it should output: [4, 0, 2, 0, 0]
it means, remove the element at index 4, for the list that got removed, remove element at 0 ....
if the list is[1,2,3,4,5]; this will be the procujure:
[1,2,3,4,5] remove index 4 -> 5
[1,2,3,4] remove index 0 -> 1
[2,3,4] remove index 2 -> 4
[2,3] rovmove index 0 -> 2
[3] remove index 0 -> 3
all the element we removed sequentially is the permutation.
/**
* Feed this function a number, it gives you a sequence of choices
* to make a permutation.
* <br>
* if this return [0,0,0,0]
* it means remove element at 0, and then remove again... until
* reaches the end.
* #return
*
* #param
* len: the length of the list
* n: the number that got match to a certain permutation.
*/
public static int[] getTheIndexOfSelection(int n, int size)
{
int[] lst = new int[size];
return getTheIndexOfSelection( n, size, 0, lst);
}
private static int[] getTheIndexOfSelection(int n, int size, int index, int[] lst)
{
if(size==1)
{
int[] result = {0}; // a list of one element, you can only choose the one that is in it
// which is at index 0;
return result;
}
if(n >= factorial(size))return null; // This is not possible to do.
size-=1;
int firstchoice = n/factorial(size);
lst[index] = firstchoice;
n = n-firstchoice*factorial(size);
if(size>1)return getTheIndexOfSelection(n ,size, index+1, lst);
return lst;
}
This is a better solution because:
The speed really depends on the factorial function, assume factorial is super fast, this will be o(n).
It matches numbers to permutation, making the expandable for things like map and iterator.
It is not the full solution, the part that is left to solve do is pretty much trivial by now.
An implementation using Heap's Algorithm. It compute next permutations on the fly. And have only one array copying
import java.util.Arrays;
import java.util.Iterator;
class Permutator<E> implements Iterator<E[]>{
E[] arr1 = null;
E[] arr2 = null;
int size;
int[] stack = null;
int index = 0;
public Permutator( E[] arr ){
if( arr.length > 0 ){
arr1 = arr;
size = arr1.length;
arr2 = Arrays.copyOf(arr1, size);
stack = new int[size];
Arrays.fill(stack, 0);
}
}
#Override
public boolean hasNext() {
return (null != arr1 && arr1.length > 0);
}
#Override
public E[] next() {
// start computing.
// We will return original array as value of last permutation.
// This is to make "hasNext() " implementation easy.
updateValue();
return arr2;
}
protected void updateValue(){
boolean bret = false;
for( ; index < size ; ){
if( stack[index] < index ){
if( index %2 == 0 ){
swap(0, index);
}else{
swap(stack[index], index);
}
stack[index]++;
index = 0;
bret = true;
break;
}else{
stack[index] = 0;
index++;
}
}
if( !bret ){
// No more permutation available.
// Set the original array as return value.
// Also set arr1 = null , so that hasNext() will return false for next test
arr2 = arr1;
arr1 = null;
}
}
private void swap (final int i, final int j) {
E temp = arr2[i];
arr2[i] = arr2 [j];
arr2[j] = temp;
}
}
Usage:
public static void main(String[] args) {
Permutator<Integer> perm = new Permutator<Integer>(new Integer[]{1,2,3, 4, 5});
int count = 0;
while(perm.hasNext()){
System.out.println(Arrays.toString(perm.next()));
count++;
}
System.out.println("total: " + count);
}
Related
I have an arraylist that looks like this:
public static ArrayList<ArrayList<String[]>> x = new ArrayList<>();
I store groups of 2 persons in a pair. For example:
[Person1, Person2]
[Person3, Person4]
The algorithm I use right now still makes duplicates, I've tried out hashmaps and iterating through them with for loop but they just give me back the original list.
This is the code:
package com.company;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
public class createGroups
{
public static ArrayList<ArrayList<String[]>> x = new ArrayList<>();
public static void main(String[] args){
//Define names
String[] names = {"Person1", "Person2", "Person3", "Person4"};
try
{
//Create combinations. In a try catch because of the saveFile method.
combination(names, 0, 2);
//Print all the pairs in the Arraylist x
printPairs();
} catch (IOException e)
{
e.printStackTrace();
}
}
static void combination(String[] data, int offset, int group_size) throws IOException
{
if(offset >= data.length)
{
//Create new Arraylist called foo
ArrayList<String[]> foo = new ArrayList<>();
//Create a pair of 2 (data.length = 4 / group_size = 2)
for(int i = 0; i < data.length / group_size; i++)
{
//Add the pair to foo.
foo.add(Arrays.copyOfRange(data, 2 * i, 2 * (i + 1)));
}
//Add foo to x
x.add(foo);
//saveFile(foo);
}
for(int i = offset; i < data.length; i++){
for(int j = i + 1; j < data.length; j++){
swap(data, offset, i);
swap(data, offset + 1, j);
combination(data, offset + group_size, group_size);
swap(data, offset + 1, j);
swap(data, offset, i);
}
}
}
public static void printPairs(){
//Print all pairs
for(ArrayList<String[]> q : x){
for(String[] s : q){
System.out.println(Arrays.toString(s));
}
System.out.println("\n");
}
}
private static void swap(String[] data, int a, int b){
//swap the data around.
String t = data[a];
data[a] = data[b];
data[b] = t;
}
}
The output right now is this:
Output
Every group of 4 names is a 'list' of pairs (Not really a list but that's what I call it)
And this is the desired output:
Desired output
But then you can see that the first and the last list of pairs are basically the same how do I change that in my combination method
The question:
How can I change my combination method so that it doesn't create duplicate groups.
And how can I make the list smaller (The desired output) when printing the created lists.
If I wasn't clear enough or if I didn't explain what I want very well, let me know. I'll try to make it clearer.
Create an object similar to this. It takes 4 strings (2 pairs). Puts the strings into array and sorts this array. That means any combination of strings you put in will be converted into one sorted combination, but the object internaly remembers which person is person1, person2, ...
private class TwoPairs {
private final String person1;
private final String person2;
private final String person3;
private final String person4;
private final String[] persons;
TwoPairs(String person1, String person2, String person3, String person4) {
this.person1 = person1;
this.person2 = person2;
this.person3 = person3;
this.person4 = person4;
persons = new String[4];
persons[0] = person1;
persons[1] = person2;
persons[2] = person3;
persons[3] = person4;
// if we sort array of persons it will convert
// any input combination into single (sorted) combination
Arrays.sort(persons); // sort on 4 objects should be fast
// hashCode and equals will be comparing this sorted array
// and ignore the actual order of inputs
}
// compute hashcode from sorted array
#Override
public int hashCode() {
return Arrays.hashCode(persons);
}
// objects with equal persons arrays are considered equal
#Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
TwoPairs other = (TwoPairs) obj;
if (!Arrays.equals(persons, other.persons)) return false;
return true;
}
// add methods which you might need
// getters for individual persons
// String getPerson1() { return person1; }
// or perhaps pairs of persons
// String[] getPair1() { return new String[] {person1, person2}; }
// add sensible toString method if you need it
}
Your ArrayList x will change like this
ArrayList<TwoPairs> x = new ArrayList<TwoPairs>();
before adding new TwoPairs object into x check if this list already contains this object.
if (!x.contains(twoPairsObject)) {
x.add(twoPairsObject);
}
I'm currently working on a university assignment which involves implementing sorting algorithms. I believe I have correctly implemented the quicksort algorithm, however in the test class the method just prints out the array being read in without sorting it. Below is the code from the test class, and the code for the actual quicksort(which is in a seperate class called 'sort').
Has anyone got any idea what I'm doing wrong?
import java.io.*;
import java.text.*;
import java.util.*;
public class Sort {
/** Array of integers to sort **/
private int[] A;
/** Size of the array **/
private int size;
/** Number of elements actually used in array **/
private int usedSize;
/** Global variables for counting sort comparisons **/
public int compIS;
/** Global comparison count for Insertion Sort **/
public int compQS;
/** Global comparison count for Quicksort **/
public int compNewS;
/** Global comparison count for new sort **/
/*****************/
/** Constructor **/
/*****************/
Sort(int max) {
/** Initialiase global sort count variables **/
compIS = 0;
compQS = 0;
compNewS = 0;
/** Initialise size variables **/
usedSize = 0;
size = max;
/** Create Array of Integers **/
A = new int[size];
}
public int getRightElement() {
return usedSize - 1;
}
public int getLeftElement() {
return A[0];
}
/*********************************************/
/*** Read a file of integers into an array ***/
/*********************************************/
public void readIn(String file) {
try {
/** Initialise loop variable **/
usedSize = 0;
/** Set up file for reading **/
FileReader reader = new FileReader(file);
Scanner in = new Scanner(reader);
/** Loop round reading in data while array not full **/
while (in.hasNextInt() && (usedSize < size)) {
A[usedSize] = in.nextInt();
usedSize++;
}
} catch (IOException e) {
System.out.println("Error processing file " + file);
}
}
/**********************/
/*** Display array ***/
/**********************/
public void display(int line, String header) {
/*** Integer Formatter - three digits ***/
NumberFormat FI = NumberFormat.getInstance();
FI.setMinimumIntegerDigits(3);
/** Print header string **/
System.out.print("\n" + header);
/** Display array data **/
for (int i = 0; i < usedSize; i++) {
/** Check if new line is needed **/
if (i % line == 0) {
System.out.println();
}
/**
* Display an ar ray element
**/
System.out.print(FI.format(A[i]) + " ");
}
}
public void quick(int L, int R) {
/* ensure there is more than one element in array */
if (R > L) {
/* split array in two */
int pLoc = partition(L, R);
/* sort left half */
quick(L, pLoc - 1);
/* sort right half */
quick(pLoc + 1, R);
}
System.out.println("\n\nAfter QuickSort: ");
for (int i = 0; i < usedSize; i++) {
System.out.println(A[i] + " ");
}
}
/* partitions array for quicksort */
public int partition(int L, int R) {
/* Select pivot */
int pivot = A[R];
/* initialise scanning pointers */
int pR = R;
int pL = L;
/* repeat until pointers cross */
while (pL < pR) {
compQS++;
/* move left pointer */
while (A[pL] < pivot) {
pL++;
}
/* move right pointer */
while ((A[pR] >= pivot) && (pR > L)) {
pR--;
//compQS++;
}
/* swap elements */
//compQS++;
if (pL < pR) {
swap(pL, pR);
L++;
R--;
}
}
/* put pivot in correct position */
swap(pL, R);
/* return pivot position */
return pL;
}
/* swaps elements in quicksort */
public void swap(int i, int j) {
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
public class TestSort
{
public static void main(String[] args)
{
Sort sortTest = new Sort(100);
/** Read in test data into array **/
sortTest.readIn("test1.txt");
/** Display array **/
sortTest.display(10,"Input Array 1");
/*apply insertion sort to array*/
//sortTest.insertion();
//sortTest.readIn("test1.txt");
sortTest.quick(sortTest.getLeftElement(), sortTest.getRightElement());
sortTest.newSort();
/** Display comparison counters **/
System.out.println("Quicksort comparison counter: " + sortTest.compQS);
System.out.println("\n\nInsertion sort comparison counter: " + sortTest.compIS);
}
One of your problems is that getLeftElement() is returning the value at position 0 within your array instead of just returning 0. In situations in which the value of the first element in the array is greater than the size of the array, no sorting will be done.
Also, I believe that your implementation of the method quick is incorrect. Within the method you recursively invoke quick(L, pLoc - 1)
and quick(pLoc + 1, R). By invoking in this manner, you do not traverse all indices of the array in your array. (Ex if L is 0, R is 10, and pLoc is 5, then you do not involve the index 5 in the sorting of your array.)
I am doing a Java class and I cannot figure it out where I am wrong.
I have a class called ArrayMethods and a method that I must use to see if my arrays are sorted or not. This is my code:
public class ArrayMethods
{
String[] list; //instance variable
/**
* Constructor for objects of class ArrayMethods
*/
public ArrayMethods(String[] list)
{
// initialise instance variables
this.list = list;
}
/**
* Determines if the array is sorted (do not sort)
* When Strings are sorted, they are in alphabetical order
* Use the compareTo method to determine which string comes first
* You can look at the String compareTo method in the Java API
* #return true if the array is sorted else false.
*/
public boolean isSorted()
{
boolean sorted = true;
// TODO: Write the code to loop through the array and determine that each
// successive element is larger than the one before it
for (int i = 0; i < list.length - 1; i++){
if (list[i].compareTo(list[i + 1]) < 0){
sorted = true;
}
}
return sorted;
}
}
And then I have a tester for this arrays that goes like this:
public class ArrayMethodsTester {
public static void main(String[] args) {
//set up
String[] animals = {"ape", "dog", "zebra"};
ArrayMethods zoo = new ArrayMethods(animals);
//test isSorted
System.out.println(zoo.isSorted());
System.out.println("Expected: true");
String[] animals2 = {"ape", "dog", "zebra", "cat"};
zoo = new ArrayMethods(animals2);
System.out.println(zoo.isSorted());
System.out.println("Expected: false");
String[] animals3 = {"cat", "ape", "dog", "zebra"};
zoo = new ArrayMethods(animals3); ;
System.out.println(zoo.isSorted());
System.out.println("Expected: false");
}
}
For the first array I do get true as it is normal, the problem is that I get true for the other 2 and it is clearly that this is false. What is it that I do not get?
could make it a little simpler by directly returning false inside of the loop
for (int i = 0; i < list.length - 1; i++) {
if (list[i].compareTo(list[i + 1]) > 0) {
return false;
}
}
return true;
public class ArrayMethods
{
String[] list; //instance variable
/**
* Constructor for objects of class ArrayMethods
*/
public ArrayMethods(String[] list)
{
// initialise instance variables
this.list = list;
}
/**
* Determines if the array is sorted (do not sort)
* When Strings are sorted, they are in alphabetical order
* Use the compareTo method to determine which string comes first
* You can look at the String compareTo method in the Java API
* #return true if the array is sorted else false.
*/
public boolean isSorted()
{
boolean sorted = true;
// TODO: Write the code to loop through the array and determine that each
// successive element is larger than the one before it
for (int i = 0; i < list.length - 1; i++){
if (list[i].compareTo(list[i + 1]) > 0){
sorted = false;
break;
}
}
return sorted;
}
}`
You could also do it with Java 8 streams if you like their syntax (though it is not a perfect use case for them because you need two elements of the stream for your operation):
public static boolean isSorted(final String[] array) {
return !IntStream.range(1, array.length)
.mapToObj(i -> new Pair<String>(array[i - 1], array[i])).parallel()
.anyMatch(t -> t.first.compareTo(t.second) > 0);
}
The code uses a small helper class Pair
public static final class Pair<T> {
final T first;
final T second;
private Pair(final T first, final T second) {
this.first = first;
this.second = second;
}
}
This solution could also run parallel which would make it faster when running on large arrays.
Credits to Collect successive pairs from a stream for accessing a Pair of elements with streams
import.util.Arrays;
public class AList<T> implements ListInterface<T>{
private T[] list;
private int numberOfEntries;
private static final int DEFAILT_INI_CAPACITY=25;
public AList()
{
this(DEFAILT_INI_CAPACIT);
}
public AList
{
numberOfEntries = 0;
// the cast is safe because the new array contains null entries
#SuppressWarnings("unchecked")
T[] tempList = (T[])new Object[initialCapacity];
list = tempList;
}
public void add(T newEntry) {
ensureCapacity();
list[numberOfEntries] = newEntry;
numberOfEntries++;
} // end add
public int getLength() {
return numberOfEntries;
} // end getLength
public boolean isEmpty() {
return numberOfEntries == 0; // or getLength() == 0
} // end isEmpty
public T[] toArray() {
// the cast is safe because the new array contains null entries
#SuppressWarnings("unchecked")
T[] result = (T[])new Object[numberOfEntries];
for (int index = 0; index < numberOfEntries; index++) {
result[index] = list[index];
} // end for
return result;
} // end toArray
Prolbems from Data Strucutre and Algorithum in Java by Frank.
On chapter 13 exercise 12 I'm stuck on the following:
the following method Reduce the size of the array:
private boolean isTooBig()
This method return true if the number if entries in the list is less than half the size of the array and the size of the array is greater than 20.
The second new method creates a new array that is three quarters the size of the current array and then copies the object in the list of the new array:
private void reduceArray()
My Attempt:
private boolean isTooBig()
{
int half = (2 / getLenght());;
return ((numberOfEntries < half) && (numberOfEntries > 20));
}
private void reduceArray()
{
private T[] list2;
stuck...
}
My question: I do not know what is The array that I am reducing.
After I reduce the array. I do not know how to copy an ArrayList to another ArrayList.
Also I am stuck on Main project one.
1) Write a program that thoroughly tests the class AList.
My attempt:
public class test {
public static void main(String[] args)
{
AList<integer> listOfInt = new AList<integer>();
listOfInt.add(1);
listOfInt.add(2);
System.out.println(listOfInt);
}
The output is the address of listOfInt, but I want the literal value 1,2 to be printed.
I'm using BlueJ to create an array. The array is of 10 objects inherited from another class.
Now, my problem is that every time I try to find an object within the array (using the findInventoryItem, I get a java.lang.NullPointerException: null error. Now the "inventoryItem" object comes from another class. I am using inventoryItems as the actual array name. the objects that go into it are the inventoryItem of class InventoryItem
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
/**
* THIS IS THE MODIFIED VERSION OF THE ARRAY LIST MANAGER CLASS
*
* #author RAGEED A BASRAWI
* #version VERSION 1
*/
public class HomeInventoryManagerARRAYClass
{
private InventoryItem inventoryItem;
private InventoryItem[] inventoryItems;
/**
* Initialise the home inventory manager.
*/
public HomeInventoryManagerARRAYClass()
{
InventoryItem inventoryItem;
inventoryItems = new InventoryItem[10];
}
/**
* Add an inventory item to the list.
*
*/
public void addInventoryItem(InventoryItem inventoryItem)
{
Random random = new Random();
inventoryItems[random.nextInt(9 - 0 + 1) + 0] = inventoryItem;
}
/**
* Try to find an inventory item in the inventory list with the given partNumber.
*
*/
public InventoryItem findInventoryItem(int partNumber)
{
for(int index = 0; index < 9; index ++)
{
if (inventoryItem.getPartNumber() == partNumber)
{
return inventoryItem;
}
if (inventoryItem.getPartNumber() != partNumber)
{
System.out.println("The entry " + partNumber + " does not exist. Pleast try again.");
}
}
return inventoryItem;
}
/**
* Locate an inventory item with the given partNumber, and return how
* many of this item are in inventory. If the partNumber does not
* match any item, return zero.
*/
public int numberInInventory(int partNumber)
{
InventoryItem inventoryItems = findInventoryItem(partNumber);
if(inventoryItems != null)//There aren't too many ways to write a statement to be NOT NULL. Its kind of annoying... -___-
{
return inventoryItems.getQuantity();
}
else
{
return 0;
}
}
/**
* Return the total number of items in inventory.
*
*/
public int numberInInventoryList()
{
return inventoryItems.length;
}
/**
* Print details of all the home inventory items.
*/
public void printInventoryList()
{
int index = 0;
while(index < inventoryItems.length)
{
System.out.println(inventoryItem = inventoryItems[index]);
index ++;
}
}
public int totalNumberInInventory()
{
int index = 0;
int absoluteInventory = 0;
while (index < inventoryItems.length)
{
InventoryItem inventoryItem = inventoryItems[index];
absoluteInventory += inventoryItem.getQuantity();
index ++;
}
return absoluteInventory;
}
}
inventoryItems[random.nextInt(9 - 0 + 1) + 0] = inventoryItem;
if you initialize the array with the line above, how do you make sure that all elements of the array are initialized? It's generating a random number and doesn't guarantee all elements between 0 to 9 are initialized.
Remember that with this line:
inventoryItems = new InventoryItem[10];
you are initializing your array, not its elements. When running functions again each array's element you should be sure that you have initialized the element itself.
For example :
InventoryItem[i].getPartNumber()
this line of code should be executed before
InventoryItem[i] = new InventoryItem();
As #Jahoy has mentioned, it's likely that the elements in the array that you are accesing are null. It is essential firstly to check if an element exists in the first place.
Your FindInventoryItem function should be like this I think:
public InventoryItem findInventoryItem(int partNumber)
{
for(int index = 0; index < 9; index ++)
{
InventoryItem tempItem = inventoryItems[index]; // ADD THIS LINE HERE
if(tempItem != null)
{
if (tempItem.getPartNumber() == partNumber)
{
return tempItem;
}
if (tempItem.getPartNumber() != partNumber)
{
System.out.println("The entry " + partNumber + " does not exist. Please try again.");
}
}
}
// at this stage you've got no result, I dont really know what you want to return
return inventoryItem;
}