java - 拆分字符串并将其解析为整数

标签 java

由于某种原因,我的代码的这一部分有一些逻辑(java.lang.ArrayIndexOutOfBoundsException)错误。我希望用户输入任何内容并将其拆分并解析为整数。如果用户未能这样做,请再次询问他们。如果他们输入类似“g5 3 76h 23”的内容,让程序将其接受为 5 3。或者如果我可以让程序拒绝这一点,直到用户只输入 0 到 9 之间的两个由空格分隔的数字,那就没问题了还有。用户还可以选择输入“q”来退出。 但是,每次我运行它时,似乎没有任何内容被分割到新数组中。我收到错误。

/** 
 * Prompts the user for input
 */
public void promptUser() {

// a Scanner object that uses System.in for input.

    Scanner scan = new Scanner(System.in);

// a prompt for the user, asking them for input.

    System.out.print("Pick a coordinate [row col] or press [q] to quit: ");

//         Get input from the user, checking for errors. If the input is
//         correct (e.g., two numbers that in bounds and have not 
//         already been clicked), then call the click method for desired 
//         coordinates. If the user wants to quit the game then make sure 
//         to update the boolean state variable and print out a message.

    String input = scan.next();
    String del = "[\\s,;\\n\\t]+"; // these are my delimiters
    String[] token = input.split(del); // here i will save tokens

    int val0 = 11, val1 = 11;
    boolean tf = true;
    while(tf)
    {
    if(token[0] == "q")
        {
        isRunning = false;
                    System.out.println("Thank you for playing");
        }
    else
        {
        try
            {
            val0 = Integer.parseInt(token[0], 10);
            }
        catch (NumberFormatException nfe)
            {
            // invalid data - set to impossible
            val0 = 11;
            }
        try
            {
            val1 = Integer.parseInt(token[1], 10);
            }
        catch (NumberFormatException nfe)
            {
            // invalid data - set to impossible
            val1 = 11;
            }
        }
    if( !(((val0 >= 0) && (val0 < rows)) && ((val1 >= 0) && (val1 < cols))) )
        {
        System.out.println("Input Invalid, pick a coordinate [row col] or press [q] to quit: ");
        input = scan.next();
        for(int i=0;i<2;i++)
            {
            token = input.split(del);
            }
                }
            else if(false) //atm
                {

                }
            else
        {
                    tf = false;


                }
    click(val0, val1);
    } //while loop
} // promptUser

最佳答案

您需要验证返回的 token[] 数组的长度,因为可能不会返回“ token ”。即,在没有首先确保它们存在的情况下,您不应尝试访问 token[0]token[1]

示例检查:

if(token.length > 1)

关于java - 拆分字符串并将其解析为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12327094/

相关文章:

java - 为什么我不能将这个 ROOT.war 文件部署到我的远程 Tomcat 服务器中?当我重新启动 Tomcat 时,它会创建一个 "empty"ROOT 目录

java - 计算逗号和java字符串中的任何文本

java - 等到子线程完成,但不要阻塞主线程

java - 从服务异常中检索 Spring Integration 中的消息

java - 从电话号码中删除破折号

java - Apache Phoenix-sqlline.py与sqlline-think.py-有什么区别?

java - 在 TestNG 中运行时,即使对于内置类型,使用反射创建类也会抛出 java.lang.ClassNotFoundException

java - JSP 显示标签排序页面重新加载

java - 如何获取 KieSession 所需的所有全局变量?

java - 使用 Hibernate 的错误 SchemaExport