Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measure scanner input length

Tags:

java

char

input

I want a scanner that will ask the user to input a character, however if more than one character is entered it should prompt the user again for only one character.

This is what I have so far:

System.out.print("(Player 2) Guess a letter: ");
Scanner letterScan = new Scanner(System.in);
while(letterScan.nextLine().length()>1)
{
    System.out.print("(Player 2) Please guess only one letter: ");

    //char inputLetter = letterScan.next().charAt(0);
}
char inputLetter = letterScan.next().charAt(0);
System.out.println("letter: " + inputLetter);

The only problem is, this is the output when I run it:

(Player 2) Guess a letter: asfa
(Player 2) Please guess only one letter: a
s
letter: s

You see the third line? It's asking for another prompt. I want to get rid of that and make it so that it uses the letter in the 2nd line from the output instead. Any ideas?

like image 734
Mo2 Avatar asked Jan 13 '23 19:01

Mo2


2 Answers

The line letterScan.next() is reading an additional character after you get your correct line. You need to save the first input of 1 character you receive, like so:

System.out.print("(Player 2) Guess a letter: ");
Scanner letterScan = new Scanner(System.in);
String line = "";
//just check for one character.
while((line=letterScan.nextLine()).length()!=1)
{
    System.out.print("(Player 2) Please guess only one letter: ");
}
char inputLetter = line.charAt(0);
System.out.println("letter: " + inputLetter);

Also change your while loop to just check the input has 1 character, otherwise the player could just press enter and your code would crash as the input would have 0 characters. The code above does this too.

like image 162
William Morrison Avatar answered Jan 21 '23 23:01

William Morrison


its because this line:

char inputLetter = letterScan.next().charAt(0);

remove the above line & change this statement:

while(letterScan.nextLine().length()>1)

to

String line = letterScan.nextLine();
while(line.length()>1)
like image 30
Ankit Avatar answered Jan 21 '23 21:01

Ankit