user2899245
user2899245

Reputation: 27

String and Int arrays not being initialized to right values

So what I'm trying to do here is initialize my strings to an empty string and my ints to 0. The display report is kind of a debugger at the moment, and when I run the program that calls displayReport, it only displays my ints and strings as null. It has to be something in my for loop, but I can't seem to figure out what I am doing wrong.

EDIT: To be clear, I HAVE to use private void initializeString(String[] s) and private void initializeInt(int[] a). And my constructor has these guidelines

public constructor: Initializes arrays holding soft drink name and ID to hold all empty strings (calls intitializeString twice to perform the tasks). Initializes arrays holding starting inventory, final inventory, and the counts of the number of transaction to zero (calls initializeInt three times to perform the tasks).

import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class SoftDrinkInventory {

    static final int MAXSIZE = 100;      // maximum size of 100
    private String[] names;             // softdrink names
    private String[] ids;               // softdrink identifications
    private int[] startingInventory;    // starting inventory of the softdrinks
    private int[] finalInventory;       // final inventory of the softdrinks
    private int[] transactionCounts;    // number of transactions per softdrink
    private int trueSize;               // total number of softdrinks

    /**-----------------------------------------------------------------------
     * constructor  
     * 
     * Initializes arrays holding soft drink name, ID number to the
     * empty string. Initializes starting inventory, final inventory,
     * and transaction counts are to zero.
     */
    public SoftDrinkInventory() {

        initializeString(names);
        initializeString(ids);
        initializeInt(startingInventory);
        initializeInt(finalInventory);
        initializeInt(transactionCounts);

    }

    /**-----------------------------------------------------------------------
     * displayReport  
     * 
     * Displays a report including soft drink name, ID, starting inventory,
     * final inventory, and number of transactions processed.
     */

    public void displayReport() {
       System.out.printf("%-22s %-16s %-23s %-23s %s %n", "Soft Drink", "ID",
                         "Starting Inventory", "Final Inventory",
                         "# transaction");
       for(int i = 0; i < 10; i++) {
           System.out.printf("%-22s %-16s %-23f %-23f %f %n", names, ids,
                             startingInventory, finalInventory, 
                             transactionCounts);

       }

    }

    /**-----------------------------------------------------------------------
     * initializeInt 
     * 
     * Takes an int array parameter and initializes its array values to zero.
     * @param a int array
     */
    private void initializeInt(int[] a) {

        a = new int[MAXSIZE];

        for(int i = 0; i < a.length; i++) {
            a[i] = 0;
        }

    }

    /**-----------------------------------------------------------------------
     * initializeString 
     * 
     * Takes a String array parameter and initializes its array values to 
     * the empty string.
     * @param s string array
     */
    private void initializeString(String[] s) {

        s = new String[MAXSIZE];


        for(int i = 0; i < s.length; i++) {
            s[i] = "";

        }


    }

}

Upvotes: 1

Views: 634

Answers (5)

Vishal K
Vishal K

Reputation: 13066

Because you are initializing the arrays local to those initializing methods. Instead of passing argument to the methods, simply create and initialize a new array within the methods and return those arrays to respective instance variables. For example change your initializeString(String[]) to public String[] initializeString() and within this method write.:

String[] names = new String[MAXSIZE]; 
for(int i = 0; i < names.length; i++) { names[i] = "";} return names;

And then call this method within your constructor as follows

names =  initializeString();

Upvotes: 2

pablochan
pablochan

Reputation: 5715

You can't overwrite a reference, that was passed as an argument to a method, inside that method. When you're doing a = new int[MAXSIZE]; you are creating an array that is visible only to that method. What you need to do is return the created array. You might consider doing something like this:

private int[] initializeInt(int size) {
    ...
}
...
startingInventory = initializeInt(MAXSIZE);

Upvotes: 2

Melquiades
Melquiades

Reputation: 8598

Of course there are better ways to do this (such as using List of Objects, as suggested by Peter Lawrey), but since this is in the specs you have, you can try this: when you declare your arrays, also allocate memory for them :

private String[] names = new String[MAXSIZE];             // softdrink names
private String[] ids = new String[MAXSIZE];               // softdrink identifications
private int[] startingInventory = new int[MAXSIZE];    // starting inventory of the softdrinks
private int[] finalInventory = new int[MAXSIZE];       // final inventory of the softdrinks
private int[] transactionCounts = new int[MAXSIZE];    // number of transactions per softdrink

Then, in your functions, you can simply assign values to 0 and empty String:

private void initializeInt(int[] a) {
    for(int i = 0; i < a.length; i++) {
        a[i] = 0;
    }
}

and

private void initializeString(String[] s) {
    for(int i = 0; i < s.length; i++) {
        s[i] = "";
    }
}

Please note that you have an error in your displayReport() function too. You are using %f to display int values (%f is used for floats). Instead, change it to %d. Also, in your for loop, you are not actually looping through your arrays. Just use i as an index when iterating. Another thing is that you are displaying only 10 entries, whereas your MAXSIZE, which you use to initialise arrays is 100, so if you want to display all array elements, change 10 to MAXSIZE:

public void displayReport() {
   System.out.printf("%-22s %-16s %-23s %-23s %s %n", "Soft Drink", "ID",
                     "Starting Inventory", "Final Inventory",
                     "# transaction");
   for(int i = 0; i < MAXSIZE; i++) {
       //change "%-22s %-16s %-23f %-23f %f %n" to the below
       //and names etc. to names[i] etc.
       System.out.printf("%-22s %-16s %-23d %-23d %d %n", names[i], ids[i],
                         startingInventory[i], finalInventory[i], 
                         transactionCounts[i]);

   }
}

Upvotes: -1

Rick Falck
Rick Falck

Reputation: 1778

There are Java functions that take an array as a parameter, put data in the array, and it is available to you.

For example:

 BufferedReader.read(char[] cbuf, int off, int len)

However, you must first create the array, and it just fills it. So you must first do this before calling that function:

 char[] cbuf = new char[100];

Since your methods are initializing arrays in the same class, you can just do Vishal K said, and not pass the arrays to the methods. In situations where you are calling methods elsewhere, you can pass objects as parameters to methods in other classes as long as you create the object first. The callee can use the passed reference to modify your object.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533580

Java uses pass by value. This means the references you pass in are being modified, not the originals. The simplest solution is to return the array you want.

names = initialiseString(100);

However, a better approach is to use a List of Objects like

private final List<Item> items = new ArrayList<>();

// to add
items.add(new Item("name", "id", 1234, 10, 1224));

// you can add any size 0 up to 2 billion.
int actualSize = items.size();


class Item {
    private String name;             // softdrink name
    private String id;               // softdrink identification
    private int startingInventory;   // starting inventory of the softdrink
    private int finalInventory;      // final inventory of the softdrink
    private int transactionCount;
} 

Upvotes: 3

Related Questions