Question:
How can you validate that a scanner input is a character between 'a' and 'z'?
Code:
import java.util.Scanner; public class ReadChar { public static void main(String[] args) { Scanner sc = new Scanner( System.in ); String str = ""; while(true) { System.out.print("Please enter a letter: "); str = sc.nextLine(); if(str.length() == 1) { char c = str.charAt(0); if( (c >= 'a') && (c <= 'z')) { break; } } System.out.println("Try again."); } System.out.println("You entered: " + str); } }
Output:
$ java ReadChar Please enter a letter: A Try again. Please enter a letter: s You entered: s