Skip to content
Advertisement

A method that I wrote with a scanner class doesn’t seem to end

I wrote a method in order to get the choice of the user for the size of a grid. However, my code doesn’t seem to work after executing the method, as it continues to run without end after I type in the response to console (if it matters, I am on repl.it). What is the issue with the code that prevents it from ending?

public static String createSize() {
    int count = 0;
    String answer = "";
    Scanner sc = new Scanner(System.in);
    System.out.println("How big do you want the grid? (Sizes: 4x4, 5x5, 6x6)");
    String size = sc.nextLine();
    //Checks if user-inputted answer matches possible answers
    while (count < 1) {
      if (size.equals("4x4") || size.equals("5x5") || size.equals("6x6")) {
        count++;
        answer = sc.nextLine();
      }
      else {
        System.out.println("That was not a viable size. Please type a viable size.");
        size = sc.nextLine();
      }
    }
    sc.close();    
    return answer;
  }

Advertisement

Answer

In the first If check in the while loop Change

answer = sc.nextLine();

to

answer = size;

since u do not want the user to input size twice. Your code should work fine now.

Let me know if anything isn’t clear so I can modify and elaborate further

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement