java.lang.NumberFormatException: For input string: "9813023219" - java

I'm using serial event to pass rfid tags read from arduino to processing. In the serial event I am parsing and converting the variable to an integer. This working for the most part, only one rfid card keeps throwing an error.
void serialEvent(Serial thisPort)
{
String inString = thisPort.readString();
if(inString != null)
{
Serial connect1 = (Serial) connections.get(0);
if(thisPort == connect1 )
{
Chair chair = (Chair) chairs.get(0);
if(inString.contains("UID Value:"))
{
int p2 = inString.indexOf(":");
String pString = inString.substring(p2+1);
String pString2 = pString.substring (0,10);
//println(pString2);
pString2.trim();
println("String length: " + pString2.length());
chair.setRFID(pString2);
println(pString2);
}
}
}
}
void setRFID(String r)
{
try{
this.rfid = Integer.parseInt(r);
}
catch (Exception e) {
e.printStackTrace();
}
//set position of person to chair
for (Person person : people)
{
//println(this.rfid != chair.rfid);
//println(this.rfid + "," + "person: " + person.ID + "," + person.RFID);
if(this.rfid == person.RFID)
{
person.setPos(this.pos);
this.personID = person.ID;
}
}
}
The try-catch is not working, and this line is causing the problem this.rfid = Integer.parseInt(r);. I thought it might be a malformed string but the strings seems ok. Here the results of checking string consistency:
String length: 10
1811524219
String length: 10
1942302231
String length: 10
1010368230
String length: 10
9813023219

9813023219 is an invalid Integer as it is greater than Integer.MAX_VALUE, which is 2147483647. Use Long instead, who's MAX_VALUE is 9223372036854775807.

You have exceeded the maximum value for an integer. I suggest using a long instead.
Check for this by displaying Integer.MAX_VALUE - no int can exceed this value.
java.long.NumberFormatException is thrown when a given string does not match the expected layout.

The number 9813023219 is out of range for int data type, try changing your data type to long and it should work.

9813023219 is Invalid Integer, You can use Long for your requirement. If RFID is not exceeding Long.MAX_VALUE.

Related

I am getting the error message java.lang.NumberFormatException: For input string: "" and I am not sure why and how to fix it

I am pretty new to Java and I am doing this project. I keep getting the following error message while I click a jButton (submitButton) in the runtime, and I am not sure why as it is not telling which line the problem is at.
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
Below is my code, I was wondering if anybody could help? Maybe help me find the error, or tell me what the error message means. Thank you!
private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {
String fullName = nameText.getText();
String email = emailText.getText();
String address = addressText.getText();
String phoneNumber = phoneText.getText();
// sets either true or false to membershipSelected if a plan is selected
boolean membershipSelected = standardMembership.isSelected() || silverMembership.isSelected() || goldMembership.isSelected();
double total = 0;
// checks if the text entered in phone number text field can be parsed to an integer
// this is only possible if it is a number, if it is a string, then error pop-up appears
try {
int phone = Integer.parseInt(phoneText.getText());
}
catch(Exception e) {
javax.swing.JOptionPane.showMessageDialog(keepStrongMain.this, "This is not a valid phone number, please try again!");
}
// checks if email text field does not contain "#" or a domain
if(!email.contains("#") || !email.contains(".com") && !email.contains(".de") && !email.contains(".co.uk")){
javax.swing.JOptionPane.showMessageDialog(keepStrongMain.this, "This is not a valid email address, please try again!");
}
else {
CardLayout card =(CardLayout)mainPanel.getLayout();
card.show(mainPanel, "card3");
}
// checks if length of phone number is 11, if not shows error pop-up
int phoneLength = Integer.parseInt(phoneText.getText());
if(phoneLength != 11){
javax.swing.JOptionPane.showMessageDialog(keepStrongMain.this, "This phone number is not long enough, please try again!");
}
else {
CardLayout card =(CardLayout)mainPanel.getLayout();
card.show(mainPanel, "card3");
}
// checks if a plan is selected, if not shows error pop-up
if(membershipSelected){
CardLayout card =(CardLayout)mainPanel.getLayout();
card.show(mainPanel, "card3");
}
else {
javax.swing.JOptionPane.showMessageDialog(keepStrongMain.this, "Please select a membership!");
}
// sets the final overview to an empty string that can be added to with selections later
String overview = "";
if (standardMembership.isSelected()){
overview = overview + " " + standardMembership.getText() + '\n';
total = 200;
}
if (silverMembership.isSelected()){
overview = overview + " " + silverMembership.getText() + '\n';
total = 450;
}
if (goldMembership.isSelected()){
overview = overview + " " + goldMembership.getText() + '\n';
total = 600;
}
}
You have two places where you perform Integer.parseInt(phoneText.getText());
At the first time, the parsing is surrounded by a try-catch block and that handles the NumberFormatException that would be thrown in case phoneText.getText() is empty or not a number.
The second time, the parsing is not surrounded by any try-catch. This time the NumberFormatException thrown is unhandled and hence you are seeing the Exception.
You should ideally parse the phoneText.getText() once and have your conditions modified accordingly.

Java Method to find a match in ArrayList

I have the following method in a program of mine that allows a user to enter a unique ID that is associated with a laptop in an ArrayList.
The desired output is as follows:
If the ID entered by the user matches an ID in the ArrayList, the laptop and its specifications will print out.
If the ID does not match, it will print out "Invalid ID".
I am very close to achieving this; however I can only figure out how to get it to print whether or not it matches for each laptop in the list. So for example, if the ID entered by the user matches one of three laptops in the list it will print as follows:
Acer Predator Helios 300 CPU: Intel i7-9750h GPU: NVIDIA GTX1660ti Memory: 16GB ID: 1234567
Invalid ID.
Invalid ID.
So my question is: how do I get it to print ONLY the single match or "Invalid ID" while still being able to loop through the entire list to check for a match? Not necessarily asking you to spoon feed me the fix, but at least help point me in the right direction or help with the logic. I thank you in advance for any help!
My method is as follows:
private static void findLaptop(ArrayList arr) {
//Prompt user to input an ID.
System.out.println("Input ID: ");
System.out.println();
//Scan for user input.
Scanner keyboard = new Scanner(System.in);
int inputId = keyboard.nextInt();
//Loop through ArrayList and check for a match.
for(int i=0; i<arr.size(); i++) {
//If entered ID matches, print laptop information.
if(inputId == ((Laptops) arr.get(i)).getId()) {
System.out.println(((Laptops)arr.get(i)).getModel() + " CPU: " + ((Laptops)arr.get(i)).getCpu() + " GPU: " +
((Laptops)arr.get(i)).getGpu() + " Memory: " + ((Laptops)arr.get(i)).getMemory() + "GB ID: " +
((Laptops)arr.get(i)).getId());
}
//If entered ID does not match, print invalid ID.
else if(inputId != ((Laptops) arr.get(i)).getId()) {
System.out.println("Invalid ID.");
}
}
}
Use below code:
//Create a boolean
boolean found= false;
for(int i=0; i<arr.size(); i++) {
//If entered ID matches, print laptop information.
if(inputId == ((Laptops) arr.get(i)).getId()) {
System.out.println(((Laptops)arr.get(i)).getModel() + " CPU: " + ((Laptops)arr.get(i)).getCpu() + " GPU: " +
((Laptops)arr.get(i)).getGpu() + " Memory: " + ((Laptops)arr.get(i)).getMemory() + "GB ID: " +
((Laptops)arr.get(i)).getId());
//set boolean true and break
found = true;
break;
}
}
//Out side the look check If entered ID does not match, print invalid ID.
if(!found) {
System.out.println("Invalid ID.");
}
You can do this using a return statement that is used after printing a match
for(int i=0; i<arr.size(); i++) {
//If entered ID matches, print laptop information.
if(inputId == (arr.get(i)).getId()) {
System.out.println((arr.get(i)).getModel() + " CPU: " + (arr.get(i)).getCpu() + " GPU: " +
(arr.get(i)).getGpu() + " Memory: " + (arr.get(i)).getMemory() + "GB ID: " +
(arr.get(i)).getId());
return;
}
}
// outside loop
System.out.println("Invalid ID.");
edit
If you have you ArrayList set up properly as ArrayList<Laptop> then you would not need all those crazy casts.
edit2
If you a foreach loop it would be even cleaner
for (Laptop lt : arr) {
if (iputId == lt.getId()) // etc
Supposing you have a class called Laptop as follows:
public class Laptop {
private String id;
private String manufacturer;
// other fields
// getters and setters
}
You can find matches with an id using Java 8 Streams:
List<Laptop> laptops = ...
String idToSearch = "something";
Optional<Laptop> result = laptops.stream() // convert into stream for easier handling
.filter(l -> l.getId().equals(idToSearch)) // find only laptops with a matching id
.findFirst(); // find the first one, if present
The variable result is an Optional<Laptop>, meaning it may or may not contain a Laptop value. You can consume this result as follows:
Laptop laptop = result.get(); // throws an exception if no value present, not reccomended
Laptop laptop = result.orElse(null); // returns null if no value present
result.ifPresent(laptop -> {
doSomething(laptop); // this function is only called if a value is present
})

How do I parse the data I achieved through splitting a string into Int values in Java?

I split a string which is a password entered by the user to only return back digits. I need to make sure those digits they entered aren't certain digits. But first, I need to take the data that comes back and turn them into an int so I can compare.
public static boolean checkPassword(String password){
String digitsRegrex = "[a-zA-Z]+";
int upPass;
String [] splitPass = password.split("[a-zA-Z]+");
for(String pass : splitPass){
try{
upPass = Integer.parseInt(pass);
}
catch (NumberFormatException e){
upPass = 0;
}
System.out.println(upPass);
}
return true;
}
When I run the program I get back the 0 (and the digits in the string password) in the catch, so the try isn't working I guess?
In your code, you set upPass to 0 when you encounter a substring that do not contain any digits. These are empty strings. This happens when the password does not start with a digit.
You should be ignoring it as you need only digits.
Example: abcd12356zz33 - when you split using the regex [a-zA-Z]+ you get "", "123456", and "33". When you attempt to convert the first empty string to a number, you get a NumberFormatException.
for(String pass : splitPass){
if (!pass.isEmpty()) {
try {
upPass = Integer.parseInt(pass);
System.out.println(upPass);
//Validate upPass for the combination of numbers
} catch (NumberFormatException e) {
throw e;
}
}
}
checkPassword("abcd12356zz33")
prints
12356
33

What does this NumberFormatException mean?

java.lang.NumberFormatException: For input string: ":"
What does this mean?
I get the above error if I run the code (below).I am a beginner here.
and..
stacktrace:[Ljava.lang.StackTraceElement;#e596c9
the code:
try
{
Class.forName("java.sql.DriverManager");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/bvdb","root","enter")
Statement stm=con.createStatement();
String m="-",t="-",w="-",th="--",f="-",st="--",s="-",runson;
if(jCheckBox1.isSelected()==true){
m="m";}
if(jCheckBox2.isSelected()==true){
t="t";}
if(jCheckBox3.isSelected()==true){
w="w";}
if(jCheckBox4.isSelected()==true){
th="th";}
if(jCheckBox5.isSelected()==true){
f="f";}
if(jCheckBox6.isSelected()==true){
st="st";}
if(jCheckBox7.isSelected()==true){
s="s";}
runson= m + t + w + th + f + st + s ;
int h1=Integer.valueOf(jTextField10.getText().substring(0,2)
int mins1=Integer.valueOf(jTextField10.getText().substring(3,5));
int h2=Integer.valueOf(jTextField12.getText().substring(0,2));
int mins2=Integer.valueOf(jTextField12.getText().substring(2,3));
Boolean x=jTextField10.getText().substring(2,3).equals(":");
Boolean y=jTextField12.getText().substring(2,3).equals(":");
String time1=jTextField10.getText().substring(0,2)+jTextField10.getText().substring (2,3)+jTextField10.getText().substring(3,5);
String time2=jTextField12.getText().substring(0,2)+jTextField12.getText().substring(2,3)+jTextField12.getText().substring(3,5);
String tfac1=jTextField13.getText();
String tfac2=jTextField14.getText();
String tfac3=jTextField15.getText();
String tfsl=jTextField16.getText();
if(Integer.valueOf(jTextField3.getText())==0){
tfac1="0";
if(Integer.valueOf(jTextField4.getText())==0){
tfac2="0";}
if(Integer.valueOf(jTextField5.getText())==0){
tfac3="0";}
if(Integer.valueOf(jTextField6.getText())==0){
tfsl="0";}
if(y==true&&x==true&&jTextField1.getText().trim().length()<=6&&jTextField2.getText().trim().length()<=30&&h1<=24&&h2<=24&&mins1<=59&&mins2<=59){
String q="INSERT INTO TRAININFO VALUE ("+jTextField1.getText()+",'"+jTextField2.getText()+"','"+jTextField9.getText()+"','"+time1+"','"+jTextField11.getText()+"','"+time2+"','"+runson+"',"+tfac1+","+tfac2+ ","+tfac3+","+tfsl+","+jTextField3.getText()+","+jTextField4.getText()+","+jTextField5.getText()+","+jTextField6.getText()+");";
stm.executeUpdate(q);
JOptionPane.showMessageDialog("ADDED");
}
}
catch (Exception e){
e.printStackTrace();
}
that means you can not convert the String ":" to Number like integer or double
see below link
http://docs.oracle.com/javase/7/docs/api/java/lang/NumberFormatException.html
According to java docs
Thrown to indicate that the application has attempted to convert a
string to one of the
numeric types, but that the string does not have the appropriate format.
It means you want to convert ":" to a number which is not allowed. Hence you are getting the exception. Better show your code
The best way you get responses faster & answered your question is posting your code.
You cannot convert String to number.
As others have said Java can't convert "15:" into a number because ":" is not a digit. And the most probable cause for this is a line like this one:
int h1 = Integer.valueOf(jTextField10.getText().substring(0,2));
where you are splitting a time string at the wrong index which is why you have ":" in it.
UPDATE
Better way of splitting a time string like "12:35:09" is by using String.split():
String timeString = "12:35:09";
String[] parts = timeString.split(":");
boolean validTimeString = parts.length == 3;
The code above will result in the following values:
timeString = "12:35:09"
parts[0] = "12"
parts[1] = "35"
parts[2] = "09"
validTimeString = true
String.split(DELIMITER) will split the string into N + 1 strings where N is the number of occurences of the DELIMITER in target string.

java: 'string index out of range: -1' exception using indexOf()

Weird problem. I run this (very elementary) procedure to find a username and password in a file, and the program should compare the password entered to the password saved. Every time, however, i get a strange String index out of range: -1 exception. I've suffered a similar problem before, however this time the indexOf('.') call is returning -1; which it doesn't like. Why is indexOf() returning -1 if it causes an error? Here's the source:
public String loginToClient() throws FileNotFoundException, IOException {
//decryptUsers();
int tries;
tries = 5;
while (tries > 0) {
System.out.println("LOGIN");
String usnm = c.readLine("Username: ");
char [] passwd = c.readPassword("Password: ");
users = new FileInputStream("users.fra");
DataInputStream dis = new DataInputStream(users);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String logindat = br.readLine();
System.out.println(logindat);
if (logindat.contains(usnm) == null) {
System.err.println("Username not recognised, please try another or create user.");
usnm = "INV";
return usnm;
}
else {
int startUsnm = logindat.indexOf(usnm);
System.out.println("startUsnm: " + startUsnm);
String logdat = logindat.substring(startUsnm, logindat.indexOf("."));
System.out.println("logdat: " + logdat);
int endUsnm = logdat.indexOf(':');
System.out.println("endUsnm: " + endUsnm);
int usnmend = endUsnm - 1;
System.out.println("usnmend: " + usnmend);
int startPass = endUsnm + 1;
System.out.println("startPass: " + startPass);
int endPass = logdat.indexOf('.');
System.out.println("endPass: " + endPass);
String Usnm = logdat.substring(0, usnmend);
System.out.println("Usnm: " + Usnm);
int passend = endPass - 1;
System.out.println("passend: " + passend);
String Pass = logdat.substring(startPass, passend);
System.out.println("Pass: " + Pass);
char [] Passwd = Pass.toCharArray();
if (usnm.equals(Usnm)) {
if (Arrays.equals(passwd,Passwd)) {
System.out.println ("Logged in. Welcome, " + usnm + ".");
String data = "LOGIN: " + usnm;
printLog(data);
//encryptUsers();
return usnm;
}
else {
System.out.println ("Incorrect password, please try again.");
String data = "PASWFAIL: " + usnm;
printLog(data);
tries -= 1;
}
}
else {
System.out.println ("Username not recognised.");
printLog("USNAMFAIL");
usnm = "INV";
return usnm;
//encrytUsers();
}
}
}
//encryptUsers();
System.exit(2);
return usnm;
}
And here's some input/output:
Startup initiated.
Logfile exists.
Users file exists.
New user? n
ELSE
LOGIN
Username: rik
Password:
rik:55.
startUsnm: 0
endUsnm: 3
startPass: 4
endPass: -1
Usnm: rik
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -5
at java.lang.String.substring(String.java:1949)
at client0_0_2.loginToClient(client0_0_2.java:103)
at client0_0_2.general(client0_0_2.java:209)
at client0_0_2.<init>(client0_0_2.java:221)
at client0_0_2.main(client0_0_2.java:228)
EDIT : SOLUTION FOUND!
For some reason, indexOf() does not want to find a '.'- when replaced with a hyphen('-'), however, it runs perfectly, seemingly!
I think the error is in this line:
String Pass = logdat.substring(startPass, passend);
For some reason (you'll have to determine why), you compute passend by searching for . in the string. If . isn't present, indexOf returns -1 as a sentinel. This isn't the line that causes the exception, though. I think it's the above line, since if you try to compute a substring ending at passend when passend is -1, you would get the above error.
Try determining why your string doesn't contain a . in it.
Hope this helps!
When indexOf() returns -1, it means that the value couldn't be found in the String. So, in this case, you're searching a String for '.' which doesn't exist in the String.
I would recommend that you always check the values of indexOf() after the call, and handle the -1 properly. For many cases, its probably sufficient to set it to either 0 or string.length(), depending on how you will use it later in your code.
Regardless, if you're expecting a '.' to exist and there isn't one, you'll need to debug through your code to find out what the value is, and where the '.' is missing.
indexOf() returns -1 if the specified string can't be found.
The problem is in the Line:
String Pass = logdat.substring(startPass, passend);
because of negative index.

Categories

Resources