方法1:
public class Taks02 {
public static void main ( String [ ] args) {
int x, target;
Scanner sc = new Scanner ( System . in) ;
Random random = new Random ( ) ;
target = random. nextInt ( 100 ) ;
System . out. print ( "输入一个[1, 100]的整数:" ) ;
x = sc. nextInt ( ) ;
while ( x != target) {
if ( x > target) {
System . out. println ( "朋友,你猜高了~继续猜吧" ) ;
} else {
System . out. println ( "朋友,你猜低了~继续猜吧" ) ;
}
System . out. print ( "输入一个[1, 100]的整数:" ) ;
x = sc. nextInt ( ) ;
}
System . out. println ( "恭喜你猜对了,游戏结束~" ) ;
}
}
结果:
方法2:
public class Taks02 {
public static void main ( String [ ] args) {
int target, x;
Scanner sc = new Scanner ( System . in) ;
Random random = new Random ( ) ;
target = random. nextInt ( 100 ) ;
while ( true ) {
System . out. print ( "输入一个[1, 100]的整数:" ) ;
x = sc. nextInt ( ) ;
if ( x > target) {
System . out. println ( "朋友,你猜高了~继续猜吧" ) ;
} else if ( x < target) {
System . out. println ( "朋友,你猜低了~继续猜吧" ) ;
} else {
break ;
}
}
System . out. println ( "恭喜你猜对了,游戏结束!" ) ;
}
}