在运行我正在为个人项目开发的绘图程序时,出现以下错误:
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/