JAVA guessing number applet, using exception handling

JAVA guessing number applet, using exception handling

package cn ;

import java.util.Random ; _
import java.util.Scanner ; _

/**
* @author yeqv
* @program A2
* @Classname a1
* @Date 2022/1/14 21:17
* @Email w16638771062@163.com
*/
public class a1 {
//Guess the number applet, using exception handling
public static void main ( String[] args ) {
Random random = new Random( );
Scanner scanner = new Scanner( System.in);
int a = random.nextInt ( 1 , 101 );
int b = 0 ;
while ( true ) {
try {
System.out.println ( "Please enter a number between 1-100: " );
b = scanner.nextInt ();
if (b > a) {
System.out.println ( "Guess the big one" );
} else if (b < a) {
System.out.println ( "Guess is too small" );
} else {
System.out.println ( "guessed it right" );
break ;
}


} catch (Exception e) { // catch an exception here, if the input is not a number it will be caught
System.out.println ( "Incorrect input, please input a number between 1-100" );
scanner.next ();
}
}
}

}

Copyright statement: The content of this article is contributed by Alibaba Cloud real-name registered users. The copyright belongs to the original author. The Alibaba Cloud developer community does not own the copyright and does not assume the corresponding legal responsibility. For specific rules, please refer to the " Alibaba Cloud Developer Community User Service Agreement " and " Alibaba Cloud Developer Community Intellectual Property Protection Guidelines ". If you find any content suspected of plagiarism in this community, fill out the infringement complaint form to report it. Once verified, this community will delete the allegedly infringing content immediately.

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00