0

Need some help with my code. I'm trying to modify written code to ask a user for "yes" or "no" in order for the loop to continue. I'm supposed to use a prime read and a while loop to display an error message if the user inputs anything other than "yes" or "no".

public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  //declare local variables
  String endProgram = "no";
  boolean inputValid;

  while (endProgram.equals("no")) {
    resetVariables();
    number = getNumber();
    totalScores = getScores(totalScores, number, score, counter);
    averageScores = getAverage(totalScores, number, averageScores);
    printAverage(averageScores);
    do {
      System.out.println("Do you want to end the program? Please enter yes or no: ");
     input.next();
     if (input.hasNext("yes") || input.hasNext("no")) {
       endProgram = input.next();
     } else {
       System.out.println("That is an invalid input!");
     }
  }
  while (!(input.hasNext("yes")) || !(input.hasNext("no")));
 }
}
1
  • This is what i have so far but it's not working properly I'm trying to see what the error is. Commented Nov 6, 2015 at 4:59

1 Answer 1

1

The hasNext method call doesn't take any parameters. Have a look at the docs.

Therefore you should get the value of the input first:

String response = input.next();

And then test the response:

!response.equalsIgnoreCase('yes') || !response.equalsIgnoreCase('no')

You could put this test into a method as you are checking the same thing multiple times.

It may be easier to see the logic of your program by changing endProgram to a boolean. Perhaps even rename it to running;

boolean running = true;
...
while (running) {
  ...
  String response;
  boolean validResponse = false;

  while (!validResponse) {
    System.out.println("Do you want to end the program? Please enter yes or no: ");
    response = input.next();
    running = isContinueResponse(response);
    validResponse = isValidResponse(response);

    if (!validResponse) System.out.println("That is an invalid input!");
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.