Topic: 运行这个程序出问题,为什么啊??(ArrayIndexOutOfBoundsException)

  Print this page

1.运行这个程序出问题,为什么啊??(ArrayIndexOutOfBoundsException) Copy to clipboard
Posted by: ybyt530
Posted on: 2005-11-06 12:10

下面是源代码,<JAVA核心技术>一卷上的源代码,我绝对没写错!

import java.util.*;
import javax.swing.*;

public class LotteryDrawing
{
public static void main(String[] args)
{
String input=JOptionPane.showInputDialog
("How many numbers do you need to draw?");
int k=Integer.parseInt(input);

input=JOptionPane.showInputDialog
("What is the highest number you can draw");
int n=Integer.parseInt(input);

//file an array with numbers 1 2 3 4...n
int[] numbers=new int[n];
for(int i=0;i<numbers.length;i++)
numbers[i]=i+1;

//draw k numbers and put them into a second array
int[] result=new int[k];
for(int i=0;i<result.length;i++)
{
//make a randm index between 0 and n-1
int r=(int)(Math.random()*n);

//pick them element at the random location
result[i]=numbers[r];

//move the last element into the random location
numbers[r]=numbers[n-1];
n--;
}

//print the sorted array
Arrays.sort(result);
System.out.println
("Bet the following combination.It'll make you rich!");
for(int i=0;i<result.length;i++)
System.out.println(result[i]);
System.exit(0);

}
}

编译时没问题
运行时出现问题:

java.lang.ArrayIndexOutOfBoundsException: -1
  at LotteryDrawing.main(LotteryDrawing.java:44)

这是怎么回是?
这样的问题我看不懂啊?只好劳烦大家帮看看了,浪费大家点时间,这种运行问题我怎么才能知道是哪里出问题呢?看不懂怎么办.我想以后能自立点这样的问题不到处问了,呵呵.如果有办法的话告诉我哦.小弟谢谢了!

2.Re:运行这个程序出问题,为什么啊??(ArrayIndexOutOfBoundsException) [Re: ybyt530] Copy to clipboard
Posted by: why
Posted on: 2005-11-06 19:24

Please let us know which line is line 44.

You could use a debugger to trace what has happened.

3.Re:运行这个程序出问题,为什么啊??(ArrayIndexOutOfBoundsException) [Re: ybyt530] Copy to clipboard
Posted by: phoenixdx
Posted on: 2005-11-06 21:48

问题出在这个循环中:
for (int i = 0; i < result.length; i++) {
int r = (int) (Math.random() * n);
result[i] = numbers[r];
numbers[r] = numbers[n - 1];
n--;
}
先输入的数必须小于等于第二个输入的数.否则上面的循环中n就会减小到-1,这时再就会出现异常了.


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923