Results 1 to 9 of 9
Thread: Return smallest value
 06052011, 06:55 PM #1Member
 Join Date
 May 2011
 Posts
 29
 Rep Power
 0
Return smallest value
Hi I have an error with my code but I do not know what it is, here are my codes:
Java Code:public class Q2 { public static void main(String[] args) { int[] numbers={1,2,4,5,10,100,2,22}; int mostSmall= find(numbers); System.out.println(mostSmall); } public static int find(int[] numbers){ int smallest=0; for(int i=0;i<numbers.length;i++){ if(numbers[i]<=numbers[i+1]){ smallest= numbers[i]; } else{ smallest= numbers[i+1]; } } return smallest; } }
 06052011, 07:16 PM #2
 Join Date
 Sep 2008
 Location
 Voorschoten, the Netherlands
 Posts
 14,414
 Blog Entries
 7
 Rep Power
 25
Most readers here aren't psychic; I am so I knew an ArrayIndexOutOfBounds error was thrown. Suppose your array length is 10; variable i goes from 0 to 9 (inclusive) but you are trying to access numbers[9+1] which goes kaboom. You have to fix that. b.t.w. you don't have to compare two consecutive numbers in the array to find the smallest number in the array.
kind regards,
JosBuild a wall around Donald Trump; I'll pay for it.
 06052011, 07:49 PM #3Member
 Join Date
 May 2011
 Posts
 29
 Rep Power
 0
Java Code:import java.math.*; public class Q2 { public static void main(String[] args) { int[] numbers={1,2,4,5,10,100,2,22}; int mostSmall= find(numbers); System.out.println(mostSmall); } public static int find(int[] numbers){ int smallest=0; for(int i=0;i<numbers.length;i++){ smallest= Math.min(numbers[7], numbers[i]); } return smallest; } }
 06052011, 07:51 PM #4Member
 Join Date
 May 2011
 Posts
 29
 Rep Power
 0
Thanks for the tips.
 06052011, 08:25 PM #5
 Join Date
 Sep 2008
 Location
 Voorschoten, the Netherlands
 Posts
 14,414
 Blog Entries
 7
 Rep Power
 25
 06062011, 03:29 PM #6Member
 Join Date
 May 2011
 Posts
 29
 Rep Power
 0
It means comparing all the numbers in the array with the last number of the array to get the smallest value. Why do you ask?
 06062011, 03:52 PM #7
 Join Date
 Sep 2008
 Location
 Voorschoten, the Netherlands
 Posts
 14,414
 Blog Entries
 7
 Rep Power
 25
 06062011, 03:57 PM #8Member
 Join Date
 May 2011
 Posts
 29
 Rep Power
 0
Well based on my question paper(college), yeah this particular question contains only eight numbers. But I get what you mean :)
 06062011, 06:11 PM #9
Similar Threads

smallest number java program
By elmo in forum New To JavaReplies: 9Last Post: 11182010, 10:29 PM 
Array[] get smallest/largest value
By bobocheez in forum New To JavaReplies: 13Last Post: 09092010, 11:16 PM 
Return Smallest Index
By Gamerpro in forum New To JavaReplies: 4Last Post: 02252009, 03:31 AM 
Finding largest and smallest integer
By mlhazan in forum New To JavaReplies: 2Last Post: 01122008, 11:30 PM 
Getting smallest possible Double value
By Java Tip in forum Java TipReplies: 0Last Post: 12062007, 03:15 PM
Bookmarks