请教两道问题?
/* 创建一个整数数组,数组大小随机产生,数组里面的整数也是随机产生的
1-1000之间的整数。*/
//这道题我怎么也不知道应该如何获得随机数,希望大家多多指点,最好加点注释
public class suijishu {
public static void main(String[] args){
int[] random = new int[];
for(int i=0;i <random.length;i++){
random[i] = (int)(Math.random()*1000) + 1;
System.out.print(random[i] + " ");
}
System.out.println();
}
}
/* 编写一个猜数字的程序,先随机产生一个1-100之间的整数,接着请用户输入猜的数字,如果猜大了就显示:“大了!”,猜小了就显示“小了!”,然后继续猜,直到猜对为止。 */
// 这道题如何让它猜对就截止
mport java.util.Scanner;
public class caidaxiao {
public static void main(String[] args){
int i;
int shu;
int[] random;
do{
System.out.print( "请输入数字: ");
Scanner scan = new Scanner(System.in);
shu = scan.nextInt();
random = new int[100];
for(i = 0;i < random.length;i++){
random[i] = (int)(Math.random()*100) + 1;
if(shu < random[i]){
System.out.println( "小了! ");
break;
}
else if(shu > random[i]){
System.out.println( "大了! ");
break;
}
}
}while(shu == random[i]);
}
}
------解决方案--------------------让电脑傻一傻也可以....
package sunflowerbbs.oicp.net;
import java.io.*;
public class Guess {
public static void main(String[] args) {
int numGiveByPerson = 0;
String str;
boolean error = true;
while (error)
try {
System.out
.println( "type a num,which between 1 and 1024.Then Let me have a guess! ");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
str = br.readLine();
numGiveByPerson = Integer.parseInt(str);
if (numGiveByPerson > = 1 && numGiveByPerson <= 1024) {
error = false;
} else
System.out.println( "the num should be between 1 and 1024! ");
} catch (
NumberFormatException e) {
System.out.println( "invalid format! ");
} catch (Exception e) {
e.printStackTrace();
}
int top = 1;
int bottom = 1024;
int mid = (top + bottom) / 2;
int s = 1;
do {
System.out.println(mid + "!big or small? ");
try {
str = new BufferedReader(new InputStreamReader(System.in))
.readLine();
if (str.toLowerCase().charAt(0) == 'b ')
bottom = mid - 1;
else
top = mid + 1;
mid = (top + bottom) / 2;
s = s * 2;
if (s > 1024) {
System.out.println( "play a joke on me! I 'll Exit! ");
return;
}
} catch (Exception e) {
}
} while (mid != numGiveByPerson);
System.out.println(mid + "? HaHa... ");
System.out.println( "you are right.how clever you are! ");
}
}
------解决方案--------------------第一道题:数组大小和数组里的值都是随机的
int n = (int) (Math.random() * 100);
System.out.println(n);
int[] random = new int[n];
for (int i = 0; i < n; i++) {