JAVA练习题

猜数字游戏。存取 5 个随机的 1~20 之间的数据
public class Test2 {
public static void main ( String [] args ) {
int [] arr = new int [ 5 ];
for ( int i = 0 ; i < arr . length ; i ++ ) {
int tmp = ( int ) ( Math . random () * 20 + 1 );
if ( exists ( arr , tmp )) {
i -- ;
} else {
arr [ i ] = tmp ;
}
}
System . out . println ( Arrays . toString ( arr ));
int target = - 1 ;
Scanner sc = new Scanner ( System . in );
while ( true ) {
System . out . println ( " 请输入所猜想的数值 " );
target = sc . nextInt ();
boolean bb = exists ( arr , target );
if ( bb ) {
System . out . println ( " 猜对了 !" );
break ;
} else {
System . out . println ( " 请继续努力 " );
}
}
sc . close ();
}
public static boolean exists ( int [] arr , int target ) {
if ( target < 1 || target > 20 )
return false ;
boolean res = false ;
for ( int tmp : arr ) {
if ( tmp == target ) {
res = true ;
break ;
}
}
return res ;
}
}

你可能感兴趣的:(java,算法)