Search code examples
javaarraysstringjtextfieldjtextarea

Java - Finding a certain string in JTextArea


I'm creating a simple program that gets 2 certain strings on an input from a JTextArea. It needs to find a non-integer string then finds an integer. All values matching from the same non-integer string will add and display the result in a JTextField. Like in the example below, all numbers who matches "ax" will be added together and the final result will be displayed in the texfield below the label "AX Box" (25 + 5 = 30)

screenshot

My following code:

    JTextField ax, bx, cx, dx;
    int totalAX, totalBX, totalCX, totalDX;
    String[] lines = textArea.getText().split("\\n"); // split lines
    System.out.println(Arrays.toString(lines)); // convert each line to string
    for (int i = 0; i < lines.length; i++) {
        if (lines.contains("ax") {
            // add each numbers.
            // for example, 25 + 5
            totalAX = totalAX + i;
            ax.setText("Total: " +totalAX);
        }
}

My problem is that the program cannot find the substring "ax", "bx" and so on. What's the best approach in this? I get errors like:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "ax"


Solution

  • I'm not sure that you're actually splitting the array, the escape sequence for a line jump is \n, you have it as \\n.

    You are also only printing the array lines if you need to convert it to String you should be reassigning a value for it like:

    for (int i = 0; i < lines.length; i++) {
         String line = lines[i].toString();
    

    And I'm pretty sure you don't need the toString() as it should come as a String variable from the textBox

    After this you need to find if it contains the "ax" and the index where it is first contained, keep that number and use it to substring the whole line to find the number, so bearing in mind that the number should be in the last place of the string you would be looking at something like this after (inside) the loop:

        if (line.contains("ax") {
          int theIndex = line.indexOf("ax");
          line = line.substring(theIndex);
    }
    

    Or in a oneliner:

     if (line.contains("ax") {
      line = line.substring(line.indexOf("ax"));
    }