OOP Inventory program - java

The error I'm receiving is an Array index out of bounds exception, but I don't know why it's happening where it is.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Inventory
{
//Maximum amount of objects
private static int MAX_ITEMS = 100;
//Iteration from item to item
private int d_nextItem = 0;
//Array for the different objects
private Stock[] d_list = new Stock[MAX_ITEMS];
public static void main(String[] args) throws FileNotFoundException
{
Inventory inventory = new Inventory();
inventory.loadList(args[0]);
//Costs printing out,rough draft, toString not made
System.out.println("COSTS");
inventory.getTotalCost();
//Total Selling price printing out
System.out.println("SELLINGP");
inventory.getTotalSellingPrice();
System.out.println("SAMOUNT");
}
The specific error is Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Inventory.main(Inventory.java:27) which points towards the inventory.loadList method in main. The error only comes up when run the program, and I don't know why its happening.
This is the loadList method, and the iteration doesn't look wrong, so how is an Array exception happening when the array is storing a reference to the objects information, not all the different strings, int and doubles.
public void loadList(String fileName) throws FileNotFoundException
{
fileName = "stock1.txt";
Scanner input = new Scanner(new File(fileName));
String newLine = null;
String name = null;
String identifier = null;
int quantity = 0;
double cost = 0.0;
double price = 0.0;
while (input.hasNextLine() && d_nextItem < MAX_ITEMS)
{
if(input.hasNext())
{
name = input.next();
}
if(input.hasNext())
{
identifier = input.next();
}
if(input.hasNextInt())
{
quantity = input.nextInt();
}
if(input.hasNextDouble())
{
cost = input.nextDouble();
}
if(input.hasNextDouble())
{
price = input.nextDouble();
}
d_list[d_nextItem]= new Stock(name,identifier,quantity,cost,price);
newLine = input.nextLine();
d_nextItem += 1;
}
}

That error means that you're not passing a parameter to the program.
args is an array containing the parameters passed to the program, the fact that index 0 is out of bounds means there are no parameters.
How exactly to do this would depend on how you're running the program.

The args[] array is special in that, when you're using it, you're invoking your program with more info, typically from the command line.
The appropriate way to populate args[] would be as follows:
java Inventory classname.txt
This way, Java will pull classname.txt into args[0].

From what I see, the code you have pasted here looks fine. So the problem might be elsewhere.
However a couple of quick changes may fix your problem.
use lists instead of an array for stock:
List stocklist = new ArrayList();
stocklist.add(...);
and make d_nextItem a local variable and initialize it before the while loop.

Related

entering multiple values in link list in java

Using LinkedList I want to access the data members of the class StudData. StudData should have an array of object. This code doesn't show errors but doesn't execute successfully either.
import java.util.LinkedList;
import java.util.Scanner;
public class StudData {
public int roll_no;
public String name;
private Scanner sc;
void enter() {
sc = new Scanner(System.in);
System.out.println("enter:");
sc.nextInt(roll_no);
sc.next(name);
}
public static void main(String[] args) {
StudData p= new StudData();
LinkedList <StudData> ll=new LinkedList<StudData>();
for (int i=0; i<20; i++) {
p.enter();
ll.add(p);
}
}
}
The code shared should compile ideally. But there would be a possible exception at:
sc.nextInt(roll_no); // roll_no is 0 by default
Hence this would throw an java.lang.IllegalArgumentException: radix:0. In case you want to take roll_no as an input from user, you can change the code to:
roll_no = sc.nextInt();
It looks to me like you made a mistake (although I am on the train working with my phone)
sc.nextInt(roll_no);
sc.next(name);
Should be:
roll_no = sc.nextInt();
name = sc.next();
The variables can't be set by passing them as arguments, because a String is immutable and an int is a primitive.

NullPointerException error, converting string[] to int[]

I'm running out of patience and needs this problem fixed. This program is intended to retrieve data from two text files as two string arrays, then use a mergesort algorithm to sort the results. My issue is during the conversion to an integer array. I return the array I created, and see that there is data stored. However, when running an loop and checking if any index is null, I find that the program believes them all to be null.
import java.io.IOException;
import java.nio.file.Files;
import java.io.File;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.*;
public class MergeInventories
{
public static File inv1 = new File("H:\\Senior Year\\CompSci\\Projects\\storeOneInv.txt");
public static File inv2 = new File("H:\\Senior Year\\CompSci\\Projects\\storeTwoInv.txt");
//the two text files I'm retrieving data from
public static String[] store1; //string array in question
public static String[] store2;
public static void header()
{
System.out.println("Keenan Schmidt");
System.out.println("AP Computer Science");
System.out.println("Merge Inventories");
System.out.println("...finally...");
}
public static void main() throws FileNotFoundException
{
header();
readFiles(inv1,store1); //converts file to string array
sort(); //converts string[] to int[]
//System.out.print(readFiles(inv1,store1));
//System.out.print(readFiles(inv2,store2);
}
public static String[] readFiles(File file, String[] store)
{
try {
Scanner scanner = new Scanner(file);
int i = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner = new Scanner(file);
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
i++;
}
store = new String[i];
i = 0;
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
store[i] = line;
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return store;
}
public static int[] sort()
{
int[] items = new int[store1.length];
for(int i = 0; i < store1.length; i++)
{
if(store1[i] != null) //this is the line where the error occurs
{
try{
items[i] = Integer.parseInt(store1[i].replaceAll("[^0-9]"," "));
} catch (NumberFormatException nfe) {};
}
}
return items;
}
private void mergeSort(String[] arr1, String[] arr2)
{
}
private void merge(int low, int med, int hi)
{
}
}
As azurefrog mentions in a comment, Java arrays are pass by value (the reference to the array) so that when you reassign the store variable in the method, the original array you passed in doesn't get the new reference assignment.
Since you want to re-use this method multiple times to make different arrays, I would suggest making a new array everytime inside the method. No need to pass it in.
static String[] readFiles(File file){
String[] store =null;
//rest of method this same
}
Then in your calling code:
store1 = readFiles(inv1);
store2 = readFiles(inv2);
You are getting a NullPointerException when trying to access store1 because you never give store1 a value other than null, because Java is pass-by-value.
You create a new array, but you only assign it to store, which is a local variable in readFiles(), and that assignment has no effect on the store1 variable.
You do return that value from your method, but you neglected to assign it in the invoking code.
Replace
readFiles(inv1,store1); //converts file to string array
with
store1 = readFiles(inv1,store1); //converts file to string array and saves it in store1
so that the created array is assigned to store1.
As dkatzel points out, this means that there is no longer any point in passing store1 into the method in the first place. It would be a good idea to follow his advice on cleaning up the method.
You can use a List at first because the file could be of unknown size, then convert the List to an Array (using toArray), and then you will know the length to which you should initialize the int array and your code can proceed as expected.
either change to this: store1 = readFiles(inv1,store1);
or in readFiles() use this.store1 instead

Copy and array to greater size array then return to original size array

Hi for my program I trying to make an array bigger by creating another array to copy the array to and then returning those values back to the original array.
import java.util.Scanner;
import java.util.Arrays;
public class Bank {
public static void main(String[] args) {
Scanner command = new Scanner(System.in);
BankAccount [] arrayAcc = new BankAccount[1];
BankAccount [] arrayAcc1 = new BankAccount[arrayAcc.length + 1];
for(int z = 0; z < arrayAcc.length; z++){
arrayAcc[z] = arrayAcc1[z];
}
arrayAcc = arrayAcc1;
System.out.println("Enter new account number: ");
int accNum = command.nextInt();
arrayAcc[count++].setAccountID(accNum);
}
}
When I later try to get an object from this array it is giving me an error:
Exception in thread "main" java.lang.NullPointerException
at Bank.main(Bank.java:47)
You copy items from arrayAcc1 to arrayAcc while should be conversely.
Should be:
arrayAcc1[z] = arrayAcc[z];
BTW, why not to use List<BankAccount> accs = new ArrayList<BankAccounts>()?
You don't need the for loop, because Arrays.copyOf already does the work for you. You also don't need the cast, because the method returns an array of the same type as its argument.
The NullPointerException is thrown when you try to access an array index that has not had a value assigned to it. You haven't filled your array with any BankAccount objects, so when you execute arrayAcc[count++].setAccountID(accNum);, there is not a BankAccount to set the account ID of. To add an account to the list, call the constructor after the array has been resized, and add the object to the last index. The code should be similar to this:
BankAccount []arrayAcc1 = Arrays.copyOf(arrayAcc, arrayAcc.length + 1);
arrayAcc = arrayAcc1;
arrayAcc[arrayAcc.length - 1] = new BankAccount(/*arguments here*/);

Return multiple arrays to the main method

My program is suppose to take a text file, read the first four names, create a random number between 1-4, and then assign the names to 4 different teams based on what the random number was. For instance, if the number was 3, then the first name would go to team 3, second name to team 4, etc. etc.(repeat process until there are no more names) I believe I have all of the code for that correct, the problem is I can't figure out how to return all the names I have put into the arrays that were brought into the method. Here is my code:
public static void main(String args[]) throws IOException
{
BufferedReader girlFile = new BufferedReader(new FileReader("girls40.txt"));
PrintWriter teamFile = new PrintWriter(new FileWriter("xxxxxxx-teamlist.txt"));
String team1[] = new String[20];
String team2[] = new String[20];
String team3[] = new String[20];
String team4[] = new String[20];
int n;
n = loadTeams(team1,team2,team3,team4,girlFile);
girlFile.close();
teamFile.close();
}
public static String[] loadTeams(String team1[],String team2[],String team3[],String team[],BufferedReader girlFile)
{
int n;
int random;
String name1;
String name2;
String name3;
String name4;
while((name1=girlFile.readLine())!=null)
{
name2=girlFile.readLine();
name3=girlFile.readLine();
name4=girlFile.readLine();
random = 1 + (int)(Math.random() * 4);
if(random==1)
{
team1[n]=name1;
team2[n]=name2;
team3[n]=name3;
team4[n]=name4;
}
if(random==2)
{
team1[n]=name4;
team2[n]=name1;
team3[n]=name2;
team4[n]=name3;
}
if(random==3)
{
team1[n]=name3;
team2[n]=name4;
team3[n]=name1;
team4[n]=name2;
}
if(random==4)
{
team1[n]=name2;
team2[n]=name3;
team3[n]=name4;
team4[n]=name1;
}
n++;
}
return team1[],team2[],team3[],team4[];
}`
The main method was given to me, so it cannot be changed.
If there is more code in main method than you've posted here. You'll have to mention what is the variable n and how is it being used else follow the answer.
main Method can't be changed
In your main method,
int n;
n = loadTeams(team1,team2,team3,team4,girlFile);
girlFile.close();
teamFile.close();
} // End of Main Method
You have not used returned value n for nothing. So it really doesn't matter what you return from method loadTeams() as long as it is an int.
Also, here loadTeams() returns an String[] which can't be assigned be int n, you'll have to change return type of loadTeams() to int as
public static int loadTeams(String team1[],String team2[],String team3[],String team[],BufferedReader girlFile) {
/*
...
*/
return 0; // whatever, it isn't being used
}
This the solution if you can't change the main method.
The call to loadTeams() expects a return value of type int. Not an array or multiple arrays. If you can't change the main method then loadTeams should return an integer.
// ...
int n;
n = loadTeams(team1,team2,team3,team4,girlFile);
// ...
you don't have to return anything, arrays created in main() will be passed to your method by reference, you can fill them there, and after execution of your method, values will be kept in these arrays
The loadTeams should return an int and not String[].
There is no need to return arrays. Changes made in the arrays in the loadTeams methods will be reflected back to the array in main method.

Assigning a String to an ArrayList pulled from file

I imported a List of Strings from a file and put them into an arrayList. I am trying to chop of the end of these arrays, so I'm putting them into a separate String format
Here is where i set x
x = new ArrayList<BankAccounts>();
try {
Scanner reader;
reader = new Scanner( new File("F:\\myCreditUnion.txt") );
while ( reader.hasNext() )
{
String inputLine = reader.nextLine();
first = inputLine.substring(0, 3);
second = Double.parseDouble(inputLine.substring(5, inputLine.length()));
x.add(new BankAccounts(first, second));
}
reader.close();
}
and this is where i try to chop off the end
double howmuch;
for(int i = 0; i < x.size(); i++)
{
list.equals(x.get(i));
howmuch = Double.parseDouble(list.substring(5, list.length()));
}
// x is the list
I am getting a nullpointerexception. Wondering how to fix this, as I am pretty new to programming.
Document i am importing contains a combinations of # and letters such as, 101s 583.58
To assign a value to list you have use list = x.get(i); instead of list.equals(x.get(i));
Update:
equals() does not assign values it only checks if two objects are equal.
The value returned by x.get(i) will be a BankAccount so you can't assign it to list (which is a String)
You have to either turn the BankAccount into a String by using toString() or you have to get a String out of it by calling one of the BankAccount methods before assigning it to list, how this works depends on the methods provided by the BankAccount class.
If you are getting a NullPointerException in the above code, either list or x is null. Check where you are setting their value, or include that part of the code in the question.
Regarding your code: you probably have some sort of declaration similar to: String line = null; somewhere before your last piece of code pasted and you get get a NullPointerException at the list.equals(x.get(i)); line. This is because your list object is not initialized. However you don't need to do that. See below.
In order to do what you want you should use the following code:
The class definition for BankAccounts:
class BankAccounts {
public String account;
public Double value;
public BankAccounts(String account, Double value)
{
this.account = account;
this.value = value;
}
}
And rewrite your code like this:
List<BankAccounts> x = new ArrayList<BankAccounts>();
try {
Scanner reader;
reader = new Scanner( new File("F:\\myCreditUnion.txt") );
while ( reader.hasNext() )
{
String inputLine = reader.nextLine();
first = inputLine.substring(0, 3);
second = Double.parseDouble(inputLine.substring(5, inputLine.length()));
x.add(new BankAccounts(first, second));
}
reader.close();
}
It seems to me that your input files contains line of the form ABC 10.324. You are parsing this properly into BankAccounts objects (each one containing a String representing the account name and a Double representing the amount) when you are reading them from file. So there is no need to reparse that again.
The code to iterate and look at the amounts is below;
// x is the list
double howmuch = 0;
for(int i = 0; i < x.size(); i++)
{
BankAccounts accounts = x.get(i);
howmuch = accounts.amount; // there is no need to cast since unboxing will occur here.
// here howmuch will contain the amount for each account
}

Categories