Ask coding questions

← Back to all posts
guess my number
nessamahi (2)

Can anyone help me with this? I'm getting and string out of bounds error.
class Main {
public static void main(String[] args) {
// Implement Guess My Number here
Scanner input = new Scanner(;
int n;
char response;
System.out.println("Enter n : ");
n = input.nextInt();
System.out.println("Enter a positive integer for n : ");
n = input.nextInt();
System.out.println("Welcome to Guess My Number! ");

	n = n-1;
	int start = 0;
	System.out.println("Please think of a number between " + start + " and " + n + " . ");
          int guess = (start+n)/2;
          System.out.println("Is your number : " + guess + " ?");
//ask user input
       System.out.println("Please enter C for correct, H for too high and L for too low ");

   response = getResponse(input);

  if (response == 'H'){
	  System.out.println("Your guess is too high");
	n = guess - 1 ;
 if(response == 'L') {
	System.out.println("Your guess is too low");
    start = guess + 1;
 if (response == 'C') {
	System.out.println("you're right");


          guess = start+n/2;

System.out.println("Thank you for playing Guess My Number");

private static char getResponse(Scanner input){
System.out.println("Enter your response (H/L/C) : ");
String r = input.nextLine().charAt(0);



mwilki7 (186)

Exception in thread "main" java.util.NoSuchElementException: No line found at java.base/java.util.Scanner.nextLine( at Main.getResponse( at Main.main( exit status 1

This tells you where in Main it happened (line 26)

This tells you where in getResponse it happened (line 53)

Line 53 is return sc.nextLine().charAt(0);

Input is a tricky thing sometimes because some functions like "nextLine" "nextInt" "next" do different things to your input. Luckily, someone on stackoverflow also had a similar problem:

Short answer:

return sc.nextLine().charAt(0);

Longer answer

This answer comes from stackoverflow:

You're reading three ints using scanner.nextInt(). Since nextInt does not
consume any whitespace or newline after the read token, that means that if the
user enters a number and presses enter, there's still a linebreak in the stream.

So when you call nextLine later it just reads that linebreak and returns the
empty string.

Since calling charAt on an empty string will cause an out of bounds error, you
get the error you get.

To fix this, either use next instead of nextLine, which will read the next word
(consuming any whitespace before it), instead of the next line, or call nextLine
twice. Once to consume the linebreak and once to read the actual line.

You should still check whether the user enters an empty line though.