user3478800
user3478800

Reputation: 11

Can't figure why my program doesnt work

import java.util.Scanner;
public class pointSystem {

static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {
    int points;
    int total = 0;
    final int judges = 5;

    System.out.println("Give points: ");
    for(int i=0;i<judges;i++)
    {
        System.out.println("Give judge's "+ (i+1) + " points: ");
        points = scanner.nextInt();
    if(points<0 || points>20) {

            System.out.println("You can only give points between 0-20");
            System.out.println("Judge "+ (i+1) + " points: ");
        points = scanner.nextInt();
        }

        total+=points;
    }

    System.out.println("Total points are "+total);

}

}

So it's totally a simple program where it asks the user to input points for 5 judges in total and then sums up the points at the end. But points can only be inserted between 0-20, if it goes outside of the range, it gives an error telling us to input again and continues to do so until we have give a valid input.

Now the program works pretty well except for a point that if I enter "22" for example, it asks again like intended but if I enter "22" once again, it lets it pass and skip to next judge.

How can I make it to keep asking until I have given a valid input before it moves to next judge? Please give a small explanation if you fix my code.

Also I'm supposed to make a small edit that when it sums up the points at the end, it minus the highest and lowest score away, summing up only the points between. So if the points are "3,5,8,9,20" it will take "3 and 20" away and only sums up "5,8 and 9" making it 22.

Upvotes: 1

Views: 63

Answers (1)

Kyle Spencer
Kyle Spencer

Reputation: 323

In your code, you have an if statement to check the input, but if your input doesn't pass your program will accept your next input without checking it.

To fix this, don't progress your program until your input is valid using a while loop, like this:

while(points<0 || points>20) {
        System.out.println("You can only give points between 0-20");
        System.out.println("Judge "+ (i+1) + " points: ");
        points = scanner.nextInt();
    }
    total+=points;
}

Upvotes: 1

Related Questions