Search code examples
javastringaveragetokenize

Calculating Average, A String Tokenization Exercise


I've been trying to get this program working for 3 days now. I've been researching on various websites and stackoverflow as well and I am just not having much success.

The goal is this program is to take in a user input that may be seperated by any amount of white space and also a single semicolon. The integers will then be added and the average will be calculated. The trick is however fractions may also be implemented and can be in the following formats : 12/33 or (12/33).

Fractions are percentage scores out of 100.

I was successfully able to eliminate whitespace and the semicolons I am just unsure how I can do the calculation aspect of this code specially dealing with the fractions.

This is my current code:

public static void main(String[] args) {
    System.out.println("Enter a Set of Grades:");
    Scanner messageIn = new Scanner(System.in);
    String store = new String();
    store = messageIn.nextLine();
    store = store.trim().replaceAll(" +", "");
    //store = store.trim().replaceAll("(", "");
    //store = store.trim().replaceAll(")", "");
    String[] dataSet = store.split(";");
    //messageIn.close();
    for (int i = 0; i<dataSet.length; i++) {
        System.out.println(dataSet[i]);
    }
}

Thank you so much for any help

I haven't gotten this far but for example this code be my input:

98;37; 12/33; (33/90); 88; 120/150;

The output would be:

The Average is: 62.67


Solution

  • How about something like this where you check if the individual grade contains a / and deal with that case separately:

    import java.util.Scanner;
    
    class Main{
      public static void main(String[] args) {
        //Initialize scanner object
        Scanner scanner = new Scanner(System.in);
    
        //Prompt user for input
        System.out.print("Enter a Set of Grades:");
        String store = scanner.nextLine();
    
        //Remove all white space and round brackets
        store = store.replaceAll("[\\(\\)\\s+]","");
    
        //Split input into individual grades
        String[] grades = store.split(";");
    
        double sum = 0;
        //Loop over each entered grade and add to sum variable
        for (String grade : grades) {
          if(grade.contains("/")) {
            double numerator = Double.parseDouble(grade.split("/")[0]);
            double denominator = Double.parseDouble(grade.split("/")[1]);
            sum += numerator/denominator * 100;
          } else {
            sum += Double.parseDouble(grade);
          }
        }
    
        System.out.printf("The average is: %.2f\n", sum/grades.length);
      }
    }
    

    Example Usage:

    Enter a Set of Grades: 98;37; 12/33; (33/90); 88; 120/150;
    The average is: 62.67
    

    Try it out here!