Menu Close

Write a Java program to detect key presses …FTC

If the user pressed number keys( from 0 to 9), the program will tell the number that is pressed, otherwise, program will show “”Not allowed”.

Input:  9

Output:
You pressed 9
import java.lang.*;
import java.util.*;
public class temp
{
  public static void main(String[] args){
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter any digit:  ");
    String str = sc.next();//.charAt(0);
    if (str.length() >1){
      System.out.println("\nNot allowed"); return;
    }
    char c=str.charAt(0);
    boolean b1;

    b1 = Character.isDigit(c);

    if(b1) System.out.println("\nYou pressed "+c);
    else
    System.out.println("\nNot allowed");
    }
}

INPUT_1:
Enter any digit:
9

OUTPUT:
You  pressed  9


INPUT_2:
Enter any digit:
11

OUTPUT:
Not  allowed


INPUT_3:
Enter any digit:
a

OUTPUT:
Not  allowed


INPUT_4:
Enter any digit:
5
OUTPUT:
You  pressed  5


ILLUSTRATION

Executed using javac in linux terminal