I get the following error when running a drawing program I am working on for a peersonal project:
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)
I know what the error means, however since I am just starting out on learning Java I am not 100% how to fix it. Here’s my code so far:
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.");
}
}
}
So I’ve converted the integer’s to numerical values and passed them through an IF statement to draw shapes on the screen. I’m guessing the error message is something really simple.
It looks like you need to include the comma in the delimiter for your split – and perhaps make it an optional comma by using
?:Another alternative is to remove the comma before parsing: