Answer to Question #162530 in Java | JSP | JSF for Ge

Question #162530

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


1
Expert's answer
2021-02-10T01:08:09-0500
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();
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog