Skippy February 2016

Initialize right variable for while loop

I wrote a program to count the number of integers that are positive, negative or zero until you enter q to stop the program. I was asking if this is the correct way to set up the while loop if you are using the character "q" to terminate the program?

int number = 0;
    int count = 0;
    int total = 0;
    int positive = 0;
    int negative = 0;
    int zero = 0;
    boolean validInput = true;


while(validInput == true){
    System.out.printf("Number (q to quit): ");
    if(input.hasNextInt()){
        number = input.nextInt();
        count++;
        total += number;
    }
    else if (number > 0){
        positive++;
    }
    else if (number < 0){
        negative++;
    }
    else if (number == 0){
        zero++;
    }
    if (validInput == false) {
        input.next();
    }

Answers


Dallen February 2016

Your problem was that you were not dealing with the user input properly, I fixed up the code and it now runs as described:

int number = 0;
int count = 0;
int total = 0;
int positive = 0;
int negative = 0;
int zero = 0;
boolean validInput = true;

Scanner input = new Scanner(System.in); //Scans for user input, I assume you had this in your original code

while(validInput == true){
    System.out.printf("Number (q to quit): ");
    String enteredValue = input.nextLine();
    try { //test is value is an integer
        number = Integer.parseInt(enteredValue); 

        count++;
        total += number;
        if (number > 0){
            positive++;
        }
        else if (number < 0){
            negative++;
        }
        else if (number == 0){
            zero++;
        }
    } 
    catch(NumberFormatException e) { //if it is not an integer:
        validInput = !enteredValue.equals("q");
    }
}

Post Status

Asked in February 2016
Viewed 2,341 times
Voted 4
Answered 1 times

Search




Leave an answer