SRL Archive - Java Help and Tutorials

Arrays


JPHamlett

2011-01-11 10:48:18

Ok, so I'm in a computer programming class at school, and were doing arrays. Here's the assignment

http://www.district196.org/evhs/academics/apcomputerscience/labs/ch6/AddingtoandRemovingFromanIntegerList1.htm

Here's my code so far.

Main Class

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package addingtoandremovingfromarrays;

import cs1.Keyboard;

public class Main{

static IntegerList list = new IntegerList(10);

//-------------------------------------------------------
// Create a list, then repeatedly print the menu and do what the
// user asks until they quit
//-------------------------------------------------------
public static void main(String[] args)
{
printMenu();
int choice = Keyboard.readInt();
while (choice != 0)
{
dispatch(choice);
printMenu();
choice = Keyboard.readInt();
}
}


//-------------------------------------------------------
// Do what the menu item calls for
//-------------------------------------------------------
public static void dispatch(int choice)
{
int loc;
switch(choice)
{
case 0:{
System.out.println("Bye!");
break;
}
case 1:{
System.out.println("How big should the list be?");
int size = Keyboard.readInt();
list = new IntegerList(size);
list.randomize();
break;
}
case 2:{
list.selectionSort();
break;
}
case 3 :{
System.out.println("What number?");
int number = Keyboard.readInt();
list.addElement(number);
break;
}
case 4:{
list.print();
break;
}
default:
System.out.println("Sorry, invalid choice");
}
}


//-------------------------------------------------------
// Print the user's choices
//-------------------------------------------------------
public static void printMenu()
{
System.out.println("\n Menu ");
System.out.println(" ====");
System.out.println("0: Quit");
System.out.println("1: Create a new list (** do this first!! **)");
System.out.println("2: Sort the list using selection sort");
System.out.println("3: Increase array size.");
System.out.println("4: Print array");
System.out.print("\nEnter your choice: ");
}


}




Construer Class

package addingtoandremovingfromarrays;



// ****************************************************************
// IntegerList.java
//
// Define an IntegerList class with methods to create, fill,
// sort, and search in a list of integers.
//
// ****************************************************************


public class IntegerList{

int[] list; //values in the list
int arraySize;

//-------------------------------------------------------
//create a list of the given size
//-------------------------------------------------------
public IntegerList(int size)
{
list = new int[size];
arraySize = size;
}


//-------------------------------------------------------
//fill array with integers between 1 and 100, inclusive
//-------------------------------------------------------
public void randomize()
{
for (int i=0; i<list.length; i++)
list[i] = (int)(Math.random() * 100) + 1;
}

public void increaseSize(){
int[] temp = new int[arraySize];
temp = list;
list = new int[arraySize + 1];
for (int i = 0; i < temp.length; i++)
list[i] = temp[i];
list[list.length] = -1;

}

public void addElement(int elem){
if (list[list.length - 1] != -1)
increaseSize();
list[list.length - 1] = elem;
}


//-------------------------------------------------------
//print array elements with indices
//-------------------------------------------------------
public void print()
{
for (int i=0; i<list.length; i++)
System.out.println(i + ":\t" + list[i]);
}


//-------------------------------------------------------
//return the index of the first occurrence of target in the list.
//return -1 if target does not appear in the list
//-------------------------------------------------------
public int search(int target)
{
int location = -1;
for (int i=0; i<list.length && location == -1; i++)
if (list[i] == target)
location = i;
return location;
}


//-------------------------------------------------------
//sort the list into ascending order using the selection sort algorithm
//-------------------------------------------------------
public void selectionSort()
{
int minIndex;
for (int i=0; i < list.length-1; i++)
{
//find smallest element in list starting at location i
minIndex = i;
for (int j = i+1; j < list.length; j++)
if (list[j] < list[minIndex])
minIndex = j;

//swap list[i] with smallest element
int temp = list[i];
list[i] = list[minIndex];
list[minIndex] = temp;
}
}


}

This is the debug


Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at addingtoandremovingfromarrays.IntegerList.increaseSize(IntegerList.java:44)
at addingtoandremovingfromarrays.IntegerList.addElement(IntegerList.java:50)
at addingtoandremovingfromarrays.Main.dispatch(Main.java:57)
at addingtoandremovingfromarrays.Main.main(Main.java:24)
Java Result: 1

I cant seem to get IncreaseSize() to work, any help?

Nava2

2011-01-11 10:59:11

 for (int i = 0; i < temp.length; i++)
list[i] = temp[i];
list[list.length] = -1;

You never increase arraySize nor does the entry list[list.length] exist. You want list[list.length-1]. :)

dapatel

2011-07-13 03:16:04

Hi,
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You've seen an example of arrays already, in the main method of the "Hello World!" application…..

Coh3n edit: link removed.

TRiLeZ

2011-07-13 05:18:03

Ahh! In-efficiency in the original source. :p

Suggestions:
Instead of calling System.out.println(..) 7 times, call it once, with '\n' separating the lines.
For increasing the length of an array, use: Arrays.copyOf(list, size++).
Instead of using list.length, use arraySize.
In the search method, make it return the index when it finds it, and return -1 if it doesn't.

I think that's all the suggestions I have at the moment, and Nava2 already answered your question.

One last thing… does your teacher know about the ArrayList class? :p

Richard

2011-07-13 05:44:41

From: TRiLeZ
One last thing… does your teacher know about the ArrayList class? :p


I was going to suggest ArrayLists! So much easier for creating dynamic arrays, you'd save yourself a hell of a lot of code using them: http://download.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html

JPHamlett

2011-07-13 12:25:15

This post was from 01-11-2011, that's over 6 months ago. haha.


I know the problem as I a solved it later that day. My teacher did know of arraylists, but I had to use arrays

TRiLeZ

2011-07-13 12:46:06

From: JPHamlett
This post was from 01-11-2011, that's over 6 months ago. haha.


I know the problem as I a solved it later that day. My teacher did know of arraylists, but I had to use arrays


Oh, oops. I forgot to check the post dates. :p

noidea

2011-07-13 14:27:00

From: dapatel
Hi,
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You've seen an example of arrays already, in the main method of the "Hello World!" application…..


Unless he was advertising I dont see why he has a ban. One of my first posts was grave digging a thread that was a year old. I dont think he deserves a ban for grave digging. It was probably a mistake :/

Dgby714

2011-07-13 15:57:33

From: noidea
Unless he was advertising I dont see why he has a ban. One of my first posts was grave digging a thread that was a year old. I dont think he deserves a ban for grave digging. It was probably a mistake :/


He prob had links in his signature.

Smarter Child

2011-07-13 18:29:15

From: noidea
Unless he was advertising I dont see why he has a ban. One of my first posts was grave digging a thread that was a year old. I dont think he deserves a ban for grave digging. It was probably a mistake :/


He was of the SpamBot race.

noidea

2011-07-13 20:35:00

From: Smarter Child
He was of the SpamBot race.


Thats unfortunate.

Coh3n

2011-07-16 09:45:39

Yes, he was a spam bot, sorry for the confusion.