绘图程序的 Java parseInt 错误

标签 java

在运行我正在为个人项目开发的绘图程序时,出现以下错误:

Exception in thread "main" java.lang.NumberFormatException: For input string: "100,"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at InputExample.main(InputExample.java:35)

我知道这个错误意味着什么,但是由于我刚刚开始学习 Java,所以我并不 100% 知道如何修复它。到目前为止,这是我的代码:

import java.util.Scanner;

public class Input {

    public final static void main(String[] args) {

        GraphicsScreen g = new GraphicsScreen();
        Scanner s = new Scanner(System.in);
        int param1 = -1;
        int param2 = -1;
        String line;
        String command;
        String[] sut;
        System.out
                .println("Please enter your commands here. A list of commands is below to help you get started.");

        do {
            System.out.println("Circle, Move, Draw");
            line = s.nextLine();
        } while(line.equalsIgnoreCase("help") == true);

        sut = line.split(" ");

        command = sut[0];

        if(sut.length > 1) {
            param1 = Integer.parseInt(sut[1]);

            if(sut.length > 2) {
                param2 = Integer.parseInt(sut[2]);
            }
        }

        if(command.equals("Move") == true) {
            g.move(param1, param2);
        }
        else if(command.equals("Draw") == true) {
            g.draw(param1, param2);
        }
        else if(command.equals("Circle") == true) {
            g.circle(param1);
        }
        else {
            System.out
                    .println("The commands you have entered are invalid. Please try again.");
        }
    }
}

因此,我将整数转换为数值,并将它们传递给 IF 语句以在屏幕上绘制形状。我猜错误消息非常简单。

最佳答案

看起来您需要在分割的分隔符中包含逗号 - 也许可以使用 ?:

将其设为可选逗号
sut = line.split(",? ");

另一种选择是在解析之前删除逗号:

sut[1] = sut[1].replaceAll(",$", "")

关于绘图程序的 Java parseInt 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13121966/

相关文章:

java - 在 Java 中实例化一个新对象会重置该对象其他实例中的所有数据

java - 如何将一个对象序列化为java中同一对象内的方法?

java - 发生异常时不会调用 ResponseEntityExceptionHandler

java - JdbcTemplate 空指针异常

java - 客户端-服务器应用程序。总是打开套接字

java - paint() 不会在 JLabel 动画中被调用

java - 使用计时器的多线程图形?

java - BroadcastReceiver onReceive 方法内的异步任务未运行?

具有事件处理功能的 Java Swing

java - 查看我们从 jar 文件导入的类内部有什么