Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

taking user input in array in java using constructor

/**Write a class named TestScores. The class constructor should 
 * accept an array of test scores as its argument. The class should 
 * have a method that returns the average of the test scores. If any
 * test score in the array is negative or greater than 100, the class
 * should throw an IllegalArgumentException. Demonstrate the class in a program.
*/

public class TestScores {

   private double testScores[];
   ScoresDemo TD = new ScoresDemo();

    public TestScores(double scores[]) {
        testScores = scores;
        try {
            for(int i = 0; i < testScores.length; i++) {
                if(scores[i] < 0 || scores[i] > 100) {
                    throw new IllegalArgumentException("Test scores must be between 0 and 100");
                }
                else {
                    testScores[i] = scores[i];
                }
            }
        }catch(IllegalFormatException ex) {
            System.out.println(ex);
        }
   }

    public double averageScores() {
        double average = 0;
        int count = testScores.length;
        int sum = 0;
            for(int i = 0; i < testScores.length; i++) {
                sum += testScores[i];
            }
         average = sum / count;
         return average;
    } 
}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #user #input #array #java #constructor
ADD COMMENT
Topic
Name
8+4 =