Android Question java.lang.NumberFormatException: For input string: [SOLVED]

Tim Chapman

Active Member
Licensed User
Longtime User
The error is from the Return(TableResult) statement at the end of the Sub.

This is the complete text of the error. I am assuming that the problem is because there are commas in the string?
Does anyone know how to fix this error?
Thank you in advance!

java.lang.NumberFormatException: For input string: "NPC CONTINUES +2: The NPC will continue their current Action, or take it to the next level, whichever makes the most sense. Apply a +2 adjustment to their Disposition Score, representing a possible shift in their current attitude. If the NPC has not acted yet in this Scene, then treat the result as a Theme Action +2."

Offending Sub!:
Sub GetTableResult(ResultText As String, TableNum As Short, DiceRolled As Short) As String
    LogColor("GetTableResult Sub started", Colors.Black)
    Private TableLine As String
    Private TextReader1 As TextReader
    Private A As Short
    Private TableResult As String
    Private ExitFlag As Boolean = False
    Private TableName As String
   
    For Each TempTableDetails As TableDetails In TableDetailsList
        If TempTableDetails.TableNum = TableNum Then
            TableName = TempTableDetails.TableName2
            ExitFlag = True
           
            Select  TempTableDetails.ComplexTables

                Case "SS"
                    'Load the Selected Table and get result from it.
                    TextReader1.Initialize(File.OpenInput(TableDir, "Table " &  TableNum & ".txt"))
                    TableLine = TextReader1.ReadLine
       
                    'Find the highest value in the table by getting the first number from the table.  That is the highest.
                    A = TableLine.SubString2(0,TableLine.IndexOf(".")) 'Limit = the last number like if you want from 0 to 100 then limit will be 100
                    'Find the correct result in the table.  This is set up to handle results that are a range or individual numbers for each line in the table.
                    Do While TableLine <> Null
                        If A <= DiceRolled Then
                            TableResult = TableLine.SubString2(TableLine.IndexOf(".") + 1,TableLine.Length)
                            'LogColor(TableName(Table)& " Result: " &  Result, Colors.Blue)
                            Exit
                        End If
                        TableLine = TextReader1.ReadLine
                        A = TableLine.SubString2(0,TableLine.IndexOf(".")) 'Limit = the last number like if you want from 0 to 100 then limit will be 100
                    Loop
                    TextReader1.Close
                Case "CS4"
                    '**This and other complex tables have yet to be figured out.
            End Select
        End If
        DisplayTableResults(TableNum, TableName, DiceRolled, TableResult)
        If ExitFlag = True Then Exit
    Next
   
    For Each TempTableDetails As TableDetails In TableDetailsList
        If TempTableDetails.TableNum = TableNum Then
            TableName = TempTableDetails.TableName2
            Exit
        End If
    Next
    RecordTableResults(ResultText, TableNum, TableName, DiceRolled, TableResult)

    LogColor("GetTableResult Sub done", Colors.Black)
    Return(TableResult)
End Sub
 
Last edited:

emexes

Expert
Licensed User
Interesting. Add these debug lines, see if they give any clue:

B4X:
    LogColor("GetTableResult Sub done", Colors.Black)
    Log((TableResult.As(Object) Is String))
    Log(TableResult.Length)
    Log(TableResult)
    Log(IsNumber(TableResult))
    Return(TableResult)
End Sub
 
Upvote 0

emexes

Expert
Licensed User
The error is from the Return(TableResult) statement at the end of the Sub.

How certain are you that the error is not occurring on "A =" line here:

B4X:
Private A As Short
...
Case "SS"
    'Load the Selected Table and get result from it.
    TextReader1.Initialize(File.OpenInput(TableDir, "Table " &  TableNum & ".txt"))
    TableLine = TextReader1.ReadLine
      
    'Find the highest value in the table by getting the first number from the table.  That is the highest.
    A = TableLine.SubString2(0,TableLine.IndexOf(".")) 'Limit = the last number like if you want from 0 to 100 then limit will be 100
 
Upvote 0

JohnC

Expert
Licensed User
Longtime User
ChatGPT seems to agree with @emexes's hunch:

The error you are encountering, java.lang.NumberFormatException, occurs when a program attempts to convert a string into a number but the string contains characters that are not suitable for conversion. In your specific case, the issue seems to arise from the line where you are trying to convert a substring of TableLine into a Short data type:
B4X:
A = TableLine.SubString2(0,TableLine.IndexOf("."))
This line attempts to extract a substring from the start of TableLine to the first occurrence of a period (.) and convert it into a number. If TableLine starts with text or has formatted numbers that cannot be directly converted to Short, you'll get a NumberFormatException.

Potential Fix

To address this, you need to ensure that the substring you are extracting can be parsed as a number. Here are a few steps to help debug and potentially fix the issue:

  1. Debugging Output: Add logging to see the actual value of TableLine before the error occurs. This can help you confirm if the format is as expected.
    B4X:
    LogColor("Current TableLine: " & TableLine, Colors.Red)
  2. Validate the Number: Before converting the substring to a number, check if it's a valid number. You can use a regular expression to verify this or handle the exception to avoid crashing.
    B4X:
    Try    A = TableLine.SubString2(0,TableLine.IndexOf("."))
    Catch
        LogColor("Failed to convert to number: " & TableLine.SubString2(0,TableLine.IndexOf(".")), Colors.Red)
        ' You can choose to skip this iteration or handle it differently
        Continue
    End Try
  3. Modify the Parsing Logic: If the format of TableLine varies, adjust the logic to correctly parse the number or handle cases where the line doesn't start with a number.
  4. Consider the Data: Ensure that the text file you are reading from ("Table " & TableNum & ".txt") is formatted correctly, where each line should start with a number followed by a period if that's what your code assumes. If this format can vary, you'll need a more robust way to parse lines.

Advanced Parsing Strategy

If the data lines can start with either numbers or text, and you only need to extract numbers, you might want to use a regular expression to find the first numeric sequence in each line:
B4X:
' Import Regex library at the top
Dim Matcher As Matcher
Matcher = Regex.Matcher("^\d+", TableLine)
If Matcher.Find Then
    A = Matcher.Match
Else
    LogColor("No leading number found in line: " & TableLine, Colors.Red)
End If
This snippet will extract a sequence of digits at the start of TableLine, if present. Adjust the regular expression based on the exact requirements and data format.
Applying these changes should help you resolve the NumberFormatException and ensure that your application handles different data formats more gracefully.
 
Upvote 0

Tim Chapman

Active Member
Licensed User
Longtime User
How certain are you that the error is not occurring on "A =" line here:
The log shows that the error is coming from Line 52.

The original line in the table is "6.NPC CONTINUES +2: The NPC will continue their current Action, or take it to the next level, whichever makes the most sense. Apply a +2 adjustment to their Disposition Score, representing a possible shift in their current attitude. If the NPC has not acted yet in this Scene, then treat the result as a Theme Action +2."

The A = line turns the 6 at the beginning of the line (before the period) to a number for comparison to the DiceRolled.

The line:
TableResult = TableLine.SubString2(TableLine.IndexOf(".") + 1,TableLine.Length)
keeps the rest of the string after the period.

This leaves the string "NPC CONTINUES +2: The NPC will continue their current Action, or take it to the next level, whichever makes the most sense. Apply a +2 adjustment to their Disposition Score, representing a possible shift in their current attitude. If the NPC has not acted yet in this Scene, then treat the result as a Theme Action +2."

This is what shows in the error message.

The first line of the sub specifies that the sub is to return a String. So, why is it trying to convert the string to a number? It should not do so at all. There is no instruction to tell it to convert the string to a number.
 
Upvote 0

William Lancee

Well-Known Member
Licensed User
Longtime User
Whenever I see an error in the return statement, it often has to do with the calling code.
For example, if Dim answer as int = GetTableResult(...) and the result is not convertible to a number.
Just saying...
 
Upvote 1

Tim Chapman

Active Member
Licensed User
Longtime User
Hi William,
That was indeed the problem. Sneaky!
I was trying to assign TableResults to a Byte variable. No good!

Thank you to everyone for your assistance.
 
Upvote 0

emexes

Expert
Licensed User
The first line of the sub specifies that the sub is to return a String. So, why is it trying to convert the string to a number? It should not do so at all.
For line 52, I agree. That is why it was interesting, and why I read through the rest of the supplied code for something that could cause NumberFormatException.

There is no instruction to tell it to convert the string to a number.
B4X:
Private A As Short
...
A = TableLine.SubString2(0,TableLine.IndexOf(".")) 'Limit = the last number like if you want from 0 to 100 then limit will be 100
 
Last edited:
Upvote 0
Top