需要注意的是:nextInt(3) 所返回的值,范围是 0~2

解决方案 »

  1.   

    我把Crow = rand.nextInt(3)-1;   
        Ccol = rand.nextInt(3)-1;改成 Crow = rand.nextInt(4)-1;                       
        Ccol = rand.nextInt(4)-1;还是会抛出异常
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at ComputerPlay.computerPlay(ComputerPlay.java:22)是不是我写的try catch 不对啊~谢啦
      

  2.   

    这个你debug 调试看看就明白了。
      

  3.   

    我把Crow = rand.nextInt(3)-1;   
        Ccol = rand.nextInt(3)-1;改成 Crow = rand.nextInt(4)-1;                       
        Ccol = rand.nextInt(4)-1;还是会抛出异常
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at ComputerPlay.computerPlay(ComputerPlay.java:22)是不是我写的try catch 不对啊~谢啦
    nextInt(n)将返回一个大于等于0小于n的随机数,虽然负数下标可以用,但还是不推荐,对这方面不是很懂,不过推测应该是这个问题
      

  4.   


    rand.nextInt(3) +1 也会有异常。我试了rand.nextInt(2)+1, 就没有异常发生了。
    但是不知道为什么13 和 27行会出现
    Exception in thread "main" java.lang.StackOverflowError
    at java.util.Random.nextInt(Unknown Source)请问你知道如何修改吗?谢啦
      

  5.   

    我把Crow = rand.nextInt(3)-1;   
        Ccol = rand.nextInt(3)-1;改成 Crow = rand.nextInt(4)-1;                       
        Ccol = rand.nextInt(4)-1;还是会抛出异常
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at ComputerPlay.computerPlay(ComputerPlay.java:22)是不是我写的try catch 不对啊~谢啦
    nextInt(n)将返回一个大于等于0小于n的随机数,虽然负数下标可以用,但还是不推荐,对这方面不是很懂,不过推测应该是这个问题楼主是刚开始学java吧,你可以去看下API,nextInt(n)返回是0~(n-1)的一个随机数!所以你取到的数组下标为-1的时候会报异常。
      

  6.   

    我知道了,应该写成nextInt(3)就可以了,谢啦~
      

  7.   

    我把Crow = rand.nextInt(3)-1;   
        Ccol = rand.nextInt(3)-1;改成 Crow = rand.nextInt(4)-1;                       
        Ccol = rand.nextInt(4)-1;还是会抛出异常
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at ComputerPlay.computerPlay(ComputerPlay.java:22)是不是我写的try catch 不对啊~谢啦
    nextInt(n)将返回一个大于等于0小于n的随机数,虽然负数下标可以用,但还是不推荐,对这方面不是很懂,不过推测应该是这个问题楼主是刚开始学java吧,你可以去看下API,nextInt(n)返回是0~(n-1)的一个随机数!所以你取到的数组下标为-1的时候会报异常。谢谢你,问题基本解决了~
      

  8.   


    关键不是 nextInt( n ) 中 n 的取值,因为它永远返回的是 [0, n)关键是后面那个操作是 +1 还是 -1,如果用“-1”,最终取值范围就变成了 [-1, n-1)
      

  9.   


    关键不是 nextInt( n ) 中 n 的取值,因为它永远返回的是 [0, n)关键是后面那个操作是 +1 还是 -1,如果用“-1”,最终取值范围就变成了 [-1, n-1)恩,是的。如果后面有+1,就永远取不到0,如果有-1, 就会异常。所以不用+1或是-1.
    谢谢你啦
      

  10.   


    关键不是 nextInt( n ) 中 n 的取值,因为它永远返回的是 [0, n)关键是后面那个操作是 +1 还是 -1,如果用“-1”,最终取值范围就变成了 [-1, n-1)我试了一下,写不写try catch都可以执行。
    那我throws exception吗? Thanks
      

  11.   

    为啥要try catch?没理解你的意图
      

  12.   


    我的意思是,已经规定了随机输入的范围,就可以不用throws exception了吧?
      

  13.   

    只要控制好随机数的范围,就可以不用。
    Random rand = new Random();
    Crow = rand.nextInt(ChessPad.board.length)+1;
    Ccol = rand.nextInt(ChessPad.board[0].length)+1;