Java核心编程的例题,为什么总报数组下表溢出

chaoliu1024 2011-08-28 06:31:04
第一个程序
public static void main(String[] args) {
if (args[0].equals("-h")) // 这里报错
System.out.print("Hello,");
else if (args[0].equals("-g"))
System.out.print("Goodbye");
for (int i = 1; i < args.length; i++)
System.out.print(" " + args[i]);
System.out.print("!");
}


第二个程序
public static void main(String[] args){
Scanner in = new Scanner(System.in);

System.out.print("How many numbers do you need to draw? ");
int k = in.nextInt();

System.out.print("What is the highest number you can draw? ");
int n = in.nextInt();

int[] numbers = new int[n];
for (int i = 0; i < numbers.length; i++)
numbers[i] = i + 1;

int[] result = new int[k];
for (int i = 0; i < result.length; i++) {
int r = (int) (Math.random() * n);

result[i] = numbers[r];

numbers[r] = numbers[n - 1]; // 这里报错
n--;
}

Arrays.sort(result);
System.out
.println("Bet the following combination. It'll make you rich!");
for (int r : result)
System.out.println(r);
}
}

异常和第一个是一样的,就不截图了。
...全文
66 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
Hello,
**************
How many numbers do you need to draw? 3
What is the highest number you can draw? 3
Bet the following combination. It'll make you rich!
1
2
3
小笨熊 2011-08-28
  • 打赏
  • 举报
回复
第二个没有错误。。。
原来缘来 2011-08-28
  • 打赏
  • 举报
回复
第二题好像没错吧
How many numbers do you need to draw?这句问你像生成多少个数
What is the highest number you can draw?问你这些数中的最大数是多少
然后在后面写上数字(整数)即可
How many numbers do you need to draw? 5
What is the highest number you can draw? 7
Bet the following combination. It'll make you rich!
1
2
3
5
7
TKD03072010 2011-08-28
  • 打赏
  • 举报
回复
public static void main(String[] args) {}
String[] args 是用来接收命令行参数的
楼主没有传参
数组里 当然没值
所以会报错
原来缘来 2011-08-28
  • 打赏
  • 举报
回复
第一题
楼主没有传递参数吧
Eclipse 右击-->run configurations Arguments 在Program arguments里填上几个参数(用空格隔开)
在dos(黑框)下的话 直接 java Message 参数

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧