import java.io.FileReader;
import java.util.Scanner;



public class diverScores
{


	public static void main(String[] args)
    {

		Scanner kb = new Scanner(System.in);
		double [] score = new double [8];
		double totalScore = 0.00;

		Scanner fileScanner=null;
		try{
		fileScanner= new Scanner(new FileReader("divingdata.txt"));
	    }catch(Exception e)
	    {
			System.out.println("Input file not found");
			System.exit(1);
	    }
	    while(fileScanner.hasNext())
	    {
			String fileLine = fileScanner.nextLine();
			String diverName = fileLine.substring(0,fileLine.indexOf("-"));
			String strScore = fileLine.substring(fileLine.indexOf("-")+2, fileLine.length());
			String strScoreArray[] = strScore.split(" ");

			for(int i =0; i<strScoreArray.length; i++)
			{
				score [i] = Double.parseDouble(strScoreArray [i]);
		    }
		    totalScore = calculateScore(score,8);
		    totalScore = totalScore - highScore(score, 8) - lowScore(score, 8);

		    System.out.printf((diverName) +" - "+ (totalScore%.2f) + "points\n");
	    }

    }


private static double highScore(double[] score, int maxCount)
{

         double highScore = 0;
         highScore = score[0];
         for(int i=0;i<maxCount;i++)
         {

               if (score[i] > highScore) {
                    highScore = score[i];
               }
         }
         return highScore;
}

     private static double lowScore(double[] score, int maxCount)
     {
         double lowScore = 0;
         lowScore = score[0];
         for(int i=0;i<maxCount;i++)
         {

                 //Compare the current score with the high score.


               if (score[i] < lowScore) {
                    lowScore = score[i];
               }
          }
         return lowScore;
     }


      //calculateScore function for calculating the score from the array

     private static double calculateScore(double [ ] score,int maxCount)
     {


           // Sum the scores,

          double total = 0.00;
          for (int i = 0; i < maxCount; i++) {
                 total = total + score[i];
          }
          return total;
     }

}

Dani AI

Generated

Most likely cause: fileLine.indexOf("-") is returning -1 and you call substring(0, -1), which throws "String index out of range: -1". spotted the hyphen-missing case; 's request for more info is also on point (knowing the exact offending line helps). The fix is to validate the line format before taking substrings and to make the parsing robust to blank or malformed lines.

A straightforward, safe approach is to skip empty lines, check indexOf('-') first, trim the parts, split on one-or-more spaces, and keep a real count of parsed scores (don't assume 8 every time). Example pattern:

int lineNo = 0;
while (fileScanner.hasNextLine()) {
    lineNo++;
    String fileLine = fileScanner.nextLine();
    if (fileLine.trim().isEmpty()) continue;
    int dash = fileLine.indexOf('-');
    if (dash == -1) {
        System.err.printf("Skipping line %d (no '-'): \"%s\"%n", lineNo, fileLine);
        continue;
    }
    String name = fileLine.substring(0, dash).trim();
    String scorePart = fileLine.substring(dash + 1).trim();
    String[] tokens = scorePart.split("\\s+");
    int n = Math.min(tokens.length, score.length);
    for (int i = 0; i < n; i++) {
        score[i] = Double.parseDouble(tokens[i]);
    }
    // use 'n' when calling helpers and printing
}

Also adapt the helper methods to accept the actual number of scores (n) and initialize min/max safely (for example, double low = Double.POSITIVE_INFINITY; then take Math.min). Reset or overwrite the score array entries beyond n (or use an ArrayList) so leftover values don't affect calculations. Finally, use a proper printf format string, e.g. System.out.printf("%s - %.2f points%n", name, total);.

These small checks — validate the dash, trim, split with \\s+, track the parsed count, and add line-number diagnostics — will eliminate the runtime exception and make the parser resilient to malformed input.

Recommended Answers

All 2 Replies

Can you provide some more information, Like,

What you did
When you got this exception i.e. while compiling or at runtime?

These thigs will help us to understand your problem easily and help you quickly.

String diverName = fileLine.substring(0,fileLine.indexOf("-"));
String strScore = fileLine.substring(fileLine.indexOf("-")+2, fileLine.length());

Guess what happens if there is no "-" in any particular line. ;-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.