Create a sample program using try, catch and finally if the user will input incorrect value (user can enter number, string character, etc...) -
short line of code only
import java.util.Scanner;
public class Q162530 {
/**
* The start point of the program
* @param args
*/
public static void main(String[] args) {
//Create Scanner object
Scanner keyboard = new Scanner(System.in);
try {
//Get input from the user
System.out.print("Enter x: ");
int x=keyboard.nextInt();
//Calculate x^2
x=x*x;
//Display result
System.out.println("x^2 = "+x);
}catch (Exception e) {
//Display error message:
System.out.print("Error: enter a value as a numeric value");
}
//close Scanner
keyboard.close();
}
}
Comments
Leave a comment