Problem with an array

My code compiles ok, but when I run the program the output is always 0. It should be the smallest number in the array.

import java.util.Scanner;

publicclass TestSmallestIndex{

static Scanner console =new Scanner(System.in);

publicstaticvoid main(String[] args){

int arraySize;

System.out.print("Enter the size of the array: ");

arraySize = console.nextInt();

int[] listA =newint[arraySize];

System.out.println();

System.out.print("Enter " + listA.length +" integers: ");

for(arraySize = 0; arraySize < listA.length; arraySize++)

listA[arraySize] = console.nextInt();

System.out.println();

System.out.println("The index of the smallest element in the array is: "

+ smallestIndex(listA, listA.length));

}

publicstaticint smallestIndex(int[] list,int size){

int min = 0;

for(int index = 0; index < size; index++){

if(list[index] < list[min] ){

min = index;

}

}

return min;

}

}

[2182 byte] By [mattvgta] at [2007-11-27 11:00:25]
# 1

error deleted

Message was edited by:

petes1234

petes1234a at 2007-7-29 12:29:33 > top of Java-index,Java Essentials,Java Programming...
# 2

error deleted?

mattvgta at 2007-7-29 12:29:33 > top of Java-index,Java Essentials,Java Programming...
# 3

It works fine for me. Make sure you don't enter values that are already sorted smallest to largest. ie don't enter 1 2 3 but enter 3 1 2.

floundera at 2007-7-29 12:29:33 > top of Java-index,Java Essentials,Java Programming...
# 4

Your code returns the **index** of the smallest item in the array, and that's fine. If you want to return the item itself, simply modify it thusly:

public static int smallestIndex(int[] list, int size)

{

int min = 0;

for (int index = 0; index < size; index++)

{

if (list[index] < list[min])

{

min = index;

}

}

return list[min]; // *************** here *****************

}

Message was edited by:

petes1234

petes1234a at 2007-7-29 12:29:33 > top of Java-index,Java Essentials,Java Programming...
# 5

Excellent. Thanks :).

mattvgta at 2007-7-29 12:29:33 > top of Java-index,Java Essentials,Java Programming...