![](/img/trans.png)
[英]Why am I getting the "wrong number of arguments" exception when call invoke method (JAVA)
[英]Not sure why I am getting an exception when trying to call my method
好的,我应该使用例外情况将战舰放置在板上,以确保没有违反规则。 但是,当我尝试调用该函数时,却得到了以下信息:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type Exception
at BattleshipBoard.main(BattleshipBoard.java:135)
如果你们可以确定出什么问题是错误的,则不是100%肯定我做错了什么,而我显然违反的相关规则将受到高度赞赏。
这是相关代码:
public void placeShip(int startCol, int startRow, int endCol, int endRow)
throws Exception {
if(startCol > numCols) {
throw new Exception("0");
}
if(startCol < 0 ) {
throw new Exception("Out of bounds, less than 1(startCol)");
}
if (startRow > numRows) {
throw new Exception("Out of bounds, Greater then numRows");
}
if (startRow < 0) {
throw new Exception("Out of bounds, less than 1 (startRow)");
}
if((startCol != endCol) && (startRow != endRow)){
throw new Exception("Diag");
}
if(board[i][j] == 1){
throw new Exception("Overlap");
}
if (startCol == endCol){
for (i = startCol; i <= endCol; i++ ){
board[i][j] = 1;
}
}
if (startRow == endRow){
for(j = startRow; j <= endRow; j++){
board[i][j] = 1;
}
}
}
public static void main(String args[]) {
// You may leave this empty
BattleshipBoard b = new BattleshipBoard(10, 10);
b.placeShip(0, 0, 3, 0);
}
您没有处理placeShip可能引发的异常。 您应该将placeShip调用放在try块内
try{
b.placeShip(0, 0, 3, 0);
}
catch(Exception x){
// take some action
}
这样,如果placeShip引发异常,则您的程序不仅会崩溃。
Java已经检查了异常。 使这个:
try {
b.placeShip(0, 0, 3, 0);
} catch(Exception e) {
System.err.println("error: "+e.getMessage());
}
但是,使用Exception
不是一个好主意。 更好地创建自己的扩展Exception
的异常,这样您就可以相应地处理不同的规则违例。
已检查的异常应被捕获或重新抛出。 因此,您有2个选择
为什么需要这些for循环?
if (startCol == endCol){
for (i = startCol; i <= endCol; i++ ){
board[i][j] = 1;
}
}
if (startRow == endRow){
for(j = startRow; j <= endRow; j++){
board[i][j] = 1;
}
}
如果初始值等于最终值,则循环将只执行一次。 做就是了:
board[startCol][j] = 1;
board[i][startRow] = 1;
我还怀疑在代码的这一部分中您将获得“索引数组超出范围的异常”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.