Hello All,

OK I have a nagging question that I need to put to rest right away, or else I am going to go amok.

In Visual Basic you can declare an array without knowing its size, and then redim the array again once the array size is known.

Now I can declare an array of 1000 elements, but that is not elegant, and a total waste.

I want to do this:

If the user provides any command line arguments for main, then I can test the length of the args array and that would give me the size of my array.

But if the user does not provide any command line arguments, then I will ask the user to enter numbers using a while loop, that would go on until the user enters -1 and that would be the value that would stop the while loop. In this case, I will not know the EXACT number of entries the user will want, and thus I can not declare my array.

What would be the most appropriate and elegant solution for this?

Thanks for any help.

Recommended Answers

All 10 Replies

I think an ArrayList would be beneficial to you. Read up on them, see if they sound they like would work for what you are trying to do.

This is what I tried-

import java.io.*;
public class MyArray {

    public static void main(String[] args) throws Throwable {
        int[] a;
        int no;
        BufferedReader buff;
        
        if(args.length==0)
        {   //You can use your -1 logic here if you wish to
            System.out.println("Enter the number of array elements: ");
            buff=new BufferedReader(new InputStreamReader(System.in));
            no=Integer.parseInt(buff.readLine());
            a=new int[no];
            
            for(int i=0;i<no;i++)
            {
                 System.out.println("Enter element: ");
            buff=new BufferedReader(new InputStreamReader(System.in));
            a[i]=Integer.parseInt(buff.readLine());
            }
            
            
        }
        
        else
        {
            no=Integer.parseInt(args[0]);
            a=new int[no];
            for(int i=0;i<no;i++)
            {
            System.out.println("Enter element: ");
            buff=new BufferedReader(new InputStreamReader(System.in));
            a[i]=Integer.parseInt(buff.readLine());
            }
            
        }


        for(int j=0;j<no;j++)
        {System.out.print(a[j]+ " ");
        }

        }
    }

Hope it helps.

jasimps suggestion of using a List is generally the best way to handle a collection like that where the number of elements in unknown.

This is what I tried-

System.out.println("Enter the number of array elements: ");

Hope it helps.

YES!!! It did help and I studied it well.

But the line above is what I need to substitute for the While iNum != -1 loop where iNUm is an input from the user, and an element in the array.

What I mean by the above is that I want the user to enter numbers, and not the array size. The array will grow as the user enters numbers, and once he enters -1, then the while loop will terminate and the array will be built by whatever the user entered.

I am also having a rough time passing array arguments to methods.

I have a method called fnSumOfElements, which should accept an array and sum up its elements. I have:

public static int fnSumOfElements(int iOriginal[])

iOriginal is the array that holds the values the user enters via the while loop above.

I call this method in this way:

else if (iChoice == 6)
{
iSum = fnSumOfElements(iOriginal);
}
But this does not seem to work, do I need [] like iSum = fnSumOfElements(iOriginal[]);

Or what is wrong with this line?

Thanks for any help.

Waseemn

I think an ArrayList would be beneficial to you. Read up on them, see if they sound they like would work for what you are trying to do.

Thank you for your reply. I did read up on the ArrayList, and unfortunately I am not allowed to use them due to the insistence of the instructor about not using anything not covered in class. I know where he is coming from, but again that limits us to what ever he teaches us as far as the homework assignments go. Once we finish the class we will be free to read up on other things in the not so good book provided.

Having said that, I have tried building an initialization string, but ran into data type issues. Then I thought of changing the data type of the initialization string but then I ran into index issues. Index being the number I am looking for, the one that would decribe the array size. Then I thought of splitting the initialization string into an array and then test the length of that array, and then I ran into trouble of what gets into the array.

So no matter what I do to emulate the ArrayList functionality, I end up with trouble.

I am going to have to write a whole lot of code just to emulate the dimentioning an array the same size as the user input.

Any suggestions?

Thanks a Million in advance.

Thank you for your reply. I did read up on the ArrayList, and unfortunately I am not allowed to use them due to the insistence of the instructor about not using anything not covered in class. I know where he is coming from, but again that limits us to what ever he teaches us as far as the homework assignments go. Once we finish the class we will be free to read up on other things in the not so good book provided.

Having said that, I have tried building an initialization string, but ran into data type issues. Then I thought of changing the data type of the initialization string but then I ran into index issues. Index being the number I am looking for, the one that would decribe the array size. Then I thought of splitting the initialization string into an array and then test the length of that array, and then I ran into trouble of what gets into the array.

So no matter what I do to emulate the ArrayList functionality, I end up with trouble.

I am going to have to write a whole lot of code just to emulate the dimentioning an array the same size as the user input.

Any suggestions?

Thanks a Million in advance.

It may be a pain but you could write a class that simply does array-manipulation for you.

I guess it would be like an "ArrayList" but it would be defined your way using methods that you have learned in your class.

Before going this approach, please give us in detail what you have learned in class so far (chapters, concepts, etc) and we can go from there.

Before going this approach, please give us in detail what you have learned in class so far (chapters, concepts, etc) and we can go from there.

Hi Alex

Thanks for your suggestion. I should have thought about it myself.

OK being a summer class, 6 weeks long, we have covered Data Types, If, while, and for statements. a bit about arrays, Classes, and methods, try and catch blocks, and now we are talking about applets.

My immediate questions as I work on a class that manipulate arrays are:

1) Access to the args array is strictly for main, or can any method in the class see it?

2) How does one pass an array of Integers or String to a method, and how does a method return an array of Integers or String to its caller?

3) An example of a Try and Catch block that would work for any exception.

By the way talking about try and catch blocks, does the error get handled in the try section or the catch section?

Thanks for any help.

Use an ArrayList or Vector [synchronized though]

Use an ArrayList or Vector [synchronized though]

It has already been explained that he's not allowed to use API's outside of what they've covered in class.


To the original poster--

I think I will write an example program that performs some of the operations you need using strictly what you've learned so far, then try and answer your questions within the code supplied.

It took me some time but I managed to whip up this simplified SizeableArray class that should answer most/all of your questions.

/**
// Hi Alex

// Thanks for your suggestion. I should have thought about it myself.

// OK being a summer class, 6 weeks long, we have covered Data Types, If, while, and for statements. a bit about arrays, Classes, and methods, try and catch blocks, and now we are talking about applets.

// My immediate questions as I work on a class that manipulate arrays are:

// 1) Access to the args array is strictly for main, or can any method in the class see it?
//    [ access to the args array is locally scoped for the main method. If it were possible for main to return a type such as object, then it may
//     be possibly to retreive that array but instead it returns void. There are ways around this, but for simplicity I'll say "not likely" ]

// 2) How does one pass an array of Integers or String to a method, and how does a method return an array of Integers or String to its caller?
//   [ see the below example Constructors/methods]

// 3) An example of a Try and Catch block that would work for any exception. [ implemented]

// By the way talking about try and catch blocks, does the error get handled in the try section or the catch section?

// [The error is handled/resolved (usually) in the catch block. Sometimes the error is more handled with a finally definition just after the error is caught.]

// Thanks for any help.
//*/

/**
 * This example is provided to use types of Integer and String. It can easily be modified for generic types, but I'm
 * assuming that you have not gone over Erasure types (Generics) yet so I will save that for later.
 *
 * This example has also been simplified to only append arguments to the end of an Array. Methods to set particular
 * elements can easily be implemented.
 */
public class SizeableArray{

	private Integer theIntegerArray[];
	private String theStringArray[];
	private boolean hasIntegerValue[], hasStringValue[];


	public static void main(String... args){

		SizeableArray sa = new SizeableArray(0);
		System.out.println("Current size of Integer array: " + sa.getIntegerArrayLength());
		sa.append(new Integer(5));
		System.out.print("Displaying elements of Integer Array: ");
		sa.displayIntegerElements();
		System.out.println("New size of Integer array is : " + sa.getIntegerArrayLength());
		sa.append(new Integer(3));
		System.out.print("Displaying elements of Integer Array: ");
		sa.displayIntegerElements();
		System.out.println("New size of Integer array is : " + sa.getIntegerArrayLength());

	}

	/**
	 * Creates a SizeableArray class that initializes the Integer array with the initialArray argument.
	 * The String array is of size 0.
	 */
	public SizeableArray(Integer initialArray[]) throws Exception{
		if(initialArray != null){
			theIntegerArray = initialArray;
			hasIntegerValue = new boolean[theIntegerArray.length];

			for(int i = 0; i < theIntegerArray.length; i++)
				hasIntegerValue[i] = true;

			theStringArray = new String[0];
			hasStringValue = new boolean[theStringArray.length];
		}
		else throw new Exception("Initial Array cannot be null!");
	}

	/**
	 * Creates a SizableArray class that initializes the  String array with the initialArray argument.
	 * The Integer array is of size 0.
	 */
	public SizeableArray(String initialArray[]) throws Exception{
		if(initialArray != null){
			theStringArray = initialArray;
			hasStringValue = new boolean[theStringArray.length];

			for(int i = 0; i < theStringArray.length; i++)
				hasStringValue[i] = true;

			theIntegerArray = new Integer[0];
			hasIntegerValue = new boolean[theIntegerArray.length];

		}
		else throw new Exception("Initial Array cannot be null!");
	}

	/**
	 * Creates a SizeableArray class that initalizes both arrays to the initialSize argument
	 */
	public SizeableArray(int initialSize){
		int myInt = 0;

		try{
			if(initialSize < 0){
				myInt = 0;
				throw new Exception("Error - integer value less than zero, setting array size to 0");
			}
			else if (initialSize > Integer.MAX_VALUE){
				myInt = Integer.MAX_VALUE;
				throw new Exception("Error - integer value too long, setting array size to Integer.MAX_VALUE");
			}
			else myInt = initialSize;
		}
		catch(Exception e){
			System.out.println(e);
		}
		finally{
			initializeSize(myInt);
		}
		// boolean values should be auto-set to false for the above boolean arrays
	}

	/*
	 * Private helper method that simply initializes the size of the arrays
	 */
	private void initializeSize(int initialSize){
			theStringArray = new String[initialSize];
			theIntegerArray = new Integer[initialSize];
			hasIntegerValue = new boolean[initialSize];
			hasStringValue = new boolean[initialSize];
	}

	/**
	 * Appends the argument Integer to the end of theIntegerArray
	 */
	public void append(Integer additionalInteger){
		Integer temp[] = new Integer[theIntegerArray.length + 1]; // creating a new Array that is bigger by 1 slot
		boolean temp2[] = new boolean[hasIntegerValue.length + 1];

		for(int i = 0; i < theIntegerArray.length; i++){
			temp[i] = theIntegerArray[i]; // copying the values from our current array to the temp array
			temp2[i] = hasIntegerValue[i]; // this is ok because the boolean array length should always be the adjacent array length
		}

		temp[theIntegerArray.length] = additionalInteger; // adding the newly desired value to the end of the temp array
		temp2[hasIntegerValue.length] = true; // stating that this element now holds

		theIntegerArray = temp; // forces our current array to now point to the new array
		hasIntegerValue = temp2;
	}

	/**
	 * Appends the argument String to the end of theStringArray
	 */
	public void append(String additionalString){
		String temp[] = new String[theStringArray.length + 1]; // creating a new Array that is bigger by 1 slot
		boolean temp2[] = new boolean[hasStringValue.length + 1];

		for(int i = 0; i < theStringArray.length; i++){
			temp[i] = theStringArray[i]; // copying the values from our current array to the temp array
			temp2[i] = hasStringValue[i];
		}

		temp[theStringArray.length] = additionalString; // adding the newly desired value to the end of the temp array
		temp2[hasStringValue.length] = true;

		theStringArray = temp; // forces our current array to now point to the new array
		hasStringValue = temp2;
	}

	/**
	 * Returns the String Array
	 */
	public String[] getStringArray(){
		return theStringArray;
	}

	/**
	 * Returns the length of the String Array
	 */

	 public int getStringArrayLength(){
	 	return theStringArray.length;
	 }

	 /**
	  * Displays the String elements currently allocated to the Array.
	  * If a particular boolean element is false for the cooresponding String indice it means
	  * that the element was "not set" and will be viewed as "<N/A>"
	  */
	 public void displayStringElements(){
	 	for(int i = 0; i < theStringArray.length; i++){
	 		if(hasStringValue[i] == true)
	 			System.out.print(theStringArray[i]);
	 		else System.out.print("<N/A>");
	 		System.out.print(" ");
	 	}
	 	System.out.println();
	 }

	 /**
	  * Displays the Integer elements currently allocated to the Array.
	  * If a particular boolean element is false for the cooresponding Integer indice it means
	  * that the element was "not set" and will be viewed as "<N/A>"
	  */
	  public void displayIntegerElements(){
	 	for(int i = 0; i < theIntegerArray.length; i++){
	 		if(hasIntegerValue[i] == true)
	 			System.out.print(theIntegerArray[i]);
	 		else System.out.print("<N/A>");
	 		System.out.print(" ");
	 	}
	 	System.out.println();
	  }

	/**
	 * Returns the Integer Array
	 */
	 public Integer[] getIntegerArray(){
		return theIntegerArray;
	 }

	/**
	 * Returns the length of the Integer Array
	 */
	 public int getIntegerArrayLength(){
	 	return theIntegerArray.length;
	 }
}

For reasons to be explained later I forcibly added the boolean arrays to check if an indice has been set or not.

For your purpose, either apply an array (of type String or Integer) when creating a new SizeableArray object OR simply supply the number 0 such that you will always append a valid String/Integer to the array without erroneous data.

commented: Nice. Very helpful for the poster. +7
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.