Display the highest score from an arrayList from a txt file

Tags:



I’ve been trying to display the highest score from the URL file and have been able to display the entire score list but I cant get it to display the maximum or it throws an error. I was able to display the scores separately

import java.net.URL;
import java.util.Scanner;

public class Q3 {
    public static void main(String[] args) throws Exception {
        String URLString = "https://itec-java.s3.us-east-2.amazonaws.com/scores.txt";
        URL theURL = new URL(URLString);
        Scanner urlReader = new Scanner(theURL.openStream());

        int highest = -1;
        String winner = "";
        while (urlReader.hasNext()) {
            String line = urlReader.nextLine();
            String[] nameScoreArray = line.split(",");

            for (String nameScore : nameScoreArray) {

                String[] finalData = nameScore.split(":");
                    
                if (Integer.parseInt(finalData[1]) > highest) {
                    system.out.println(finalData[1]);
                        }
                    }
                }

            }
        }
    }
}

but when I tried to add this to the if statmeny instead of the system.out.println(finalData[1]); It failed

int max = finalData.length;
                    for(int num : finalData){
                        if ( num > max){
                            max = num;
                        }

Answer

finalData is Strig array, so you can iterate it by using String object only. You can use this code:

int max = finalData.length;
                    for(String numString : finalData){
                       int num = Integer.parseInt(numString);
                        if ( num > max){
                            max = num;
                        }


Source: stackoverflow