简体   繁体   中英

Something wrong with string to integer conversion

I make chessboard, where alone king will walk according to the rules of chess. Below it's method to make, it called for 2 times for i and j coordinate of King, I Made input variable String to check if this King's coordinates already exist. Than I try to convert it to integer, seems something wrong with this conversion.

import java.util.*;
public class King {
    int move(String iK){
        Random rand = new Random();
        Integer coordinateKing = Integer.valueOf(iK);
        if (iK == null){           
            coordinateKing = rand.nextInt(8);
        }else{
            int caseI;
            switch(caseI = rand.nextInt(2)){
                case 0: if (coordinateKing < 8){ coordinateKing++; } else {caseI = rand.nextInt(2);}
                break;
                case 1: if (coordinateKing > 0){ coordinateKing--; } else {caseI = rand.nextInt(2);}
                break;
                default: 
                break;
            }           
        }       
        return coordinateKing;
    }
}

I have problem like this:

Exception in thread "main" java.lang.NumberFormatException: null
    at java.lang.Integer.parseInt(Integer.java:454)
    at java.lang.Integer.valueOf(Integer.java:582)
    at chess_engine.King.move(King.java:6)
    at chess_engine.MainClass.main(MainClass.java:12)

Thanks in advance!

You call this

Integer coordinateKing = Integer.valueOf(iK);

but iK can be NULL there. do your null check first

You're attempting to convert iK to an integer before you check to see if it's null . This line is where the exception is thrown:

Integer coordinateKing = Integer.valueOf(iK);

But you check if (iK == null) on the line following that. You should do a null test first. You can fix this by declaring coordinateKing before your if statement and setting its value in the if...else blocks.

Integer coordinateKing = 0;

if (iK == null){           
    coordinateKing = rand.nextInt(8);
} else {
    coordinateKing = Integer.valueOf(iK);
    int caseI;
    ...
}

The exception is pretty self-explanatory. iK is a null String, which can't be converted to an Integer. What Integer do you want when iK is null?

这是一个运行时错误:这里的iK接收到一个null值,一个Integer对象可以存储null,但是方法valueOf()内部使用parseInt()方法,该方法返回一个int值,并且null不能转换为int

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM