Why output is -1? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why output is -1?

Hello, this is my little program, that reads array "times" and prints the winner name. But the winner index = -1, why?! I'm sorry, if i don't correctly write in English, I'm working on it:) Program will be finalized, I know, that it is not very well written, but I need to solve the problem. Program code: public static void main(String[] args) { String[] names = {"John", "David", "Charlotte", "Sergey", "Rob", "Fill"}; int[] times = {50, 45, 67, 21, 48, 38}; int fasterTime = 0; for(int t : times) { if (t>fasterTime) { fasterTime=t; } else if(t<fasterTime) { fasterTime = fusterTime; } else if(t==fasterTime) { fasterTime=t; } } int indexFasterTime = Arrays.asList(times).indexOf(fasterTime); System.out.println(indexFasterTime); // String nameFaster = names[indexFasterTime]; // System.out.println(nameFaster+" win!");

23rd Jul 2019, 6:35 PM
Sergey Chernikov
Sergey Chernikov - avatar
2 Answers
+ 1
this returns weird object with size=1, List timelist = Arrays.asList(times); System.out.println(timelist.size() ); // 1 it not works properly because it is defined with Collection and Object not with primitive int. you can solve it with Integer[] array instead int[] Integer[] times = ... or do it with other for loop (or stream) int indexFusterTime=0; for (int t: times) if (t==fusterTime) indexFusterTime = t; or rewrite your search algorithm with index int fusterTime=0, indexFusterTime=0; for(int i=0; i<times.length; i++) { if (times[i] > fusterTime) { fusterTime = times[i]; indexFusterTime = i; } } System.out.println(indexFusterTime);
24th Jul 2019, 6:35 AM
zemiak
0
Okay, thank you very much!
24th Jul 2019, 6:45 AM
Sergey Chernikov
Sergey Chernikov - avatar