1

Hi I am trying to solve a Kata(coding practice exercise) in CodeWars which is called "Your order, please" (there is a BIG chance that my code won't solve it but I am really just trying to get rid of the error..and there's a link to the exercise at the end in case you want to check it out)

Either way what the Kata basically says is that you will be given a String such as

"4of Fo1r pe6ople g3ood th5e the2" 

and you have to order the words by getting the int and returning in the correct order so

"Fo1r the2 g3ood 4of th5e pe6ople"

Now what I coded is supposed to go through each element and get the number to then order it, so I tried to use parseInt and it did not work. I read on another article that trim() would get rid of...

java.lang.NumberFormatException: For input string: "4of" //trim did not fix it

I am not sure whether I did not implement trim() correctly or parseInt() or what is wrong, any help would be very much appreciated and thank you for taking your time to read this. Without further ado here's the code.

public class Kata {
public static String order(String words) {
    String[] unordered = words.split(" ");
    String[] order = new String[unordered.length];
    System.out.println(unordered.length);
    
    for(int i = 0; i < unordered.length; i++){
        int correctIndex = (Integer.parseInt(unordered[i].trim())) -1;
        order[correctIndex] = unordered[i];
        System.out.println(unordered[i]);
    }
    
    return "I will return order concatenated";
  }

  public static void main(String[] args) {
      System.out.println(order("4of Fo1r pe6ople g3ood th5e the2"));
  }

}

And the error... (6 is the output before it)

6
Exception in thread "main" java.lang.NumberFormatException: For input string: "4of"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.base/java.lang.Integer.parseInt(Integer.java:652)
    at java.base/java.lang.Integer.parseInt(Integer.java:770)
    at Kata.order(Kata.java:8)
    at Kata.main(Kata.java:17)

https://www.codewars.com/kata/55c45be3b2079eccff00010f/train/java (the link to the Kata)

3
  • 1
    Yes, because 4of is not an int and you have written no code to remove any non-number characters from it
    – luk2302
    Commented Nov 19, 2020 at 7:39
  • 1
    trim() removes white space at the beginning and end of the String. It doesn't remove letters. And "4of" cannot be parsed as an int. You should extract the digit from the String.
    – Eran
    Commented Nov 19, 2020 at 7:39
  • You need to remove all non-digits.
    – Sweeper
    Commented Nov 19, 2020 at 7:43

3 Answers 3

0

4of is not an integer string and therefore, you can not parse it into an int. You can replace its non-digit characters (\D) with "" and then you can parse it to an int. Learn more about regex patterns from the documentation of java.util.regex.Pattern.

The problem can be solved in the following simple steps:

  1. Split the sentence on space (which you have already done).
  2. Create an int[] original and populate it with embedded numeric values from the resulting, String[] unordered.
  3. Create a clone of original[] and sort the same. Let's say this clone is int[] order.
  4. Populate a String[] ordered based on order[].
  5. Join the elements of ordered[] on space.

Demo:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String words = "4of Fo1r pe6ople g3ood th5e the2";
        String[] unordered = words.split(" ");
        String[] ordered = new String[unordered.length];
        int[] original = new int[unordered.length];

        // Populate order with embedded numeric values
        for (int i = 0; i < unordered.length; i++) {
            original[i] = Integer.parseInt(unordered[i].replaceAll("\\D", ""));
        }

        // Create a clone of original[] and sort it
        int[] order = original.clone();
        Arrays.sort(order);

        // Populate ordered[] based on order[]
        for (int i = 0; i < order.length; i++) {
            for (int j = 0; j < original.length; j++) {
                if (order[i] == original[j]) {
                    ordered[i] = unordered[j];
                    break;
                }
            }
        }

        // Join the elements of ordered[] on space
        String result = String.join(" ", ordered);

        System.out.println(result);
    }
}

Output:

Fo1r the2 g3ood 4of th5e pe6ople
1
  • You are too kind I was having trouble with join() since in javascript it is used differently THANK YOU. Commented Nov 19, 2020 at 8:24
0

Just remove all non-numeric characters (by using regex replacement) and then parse the resulting value to an integer.

for (int i = 0; i < unordered.length; i++){
    String wordNum = unordered[i].trim().replaceAll("\\D+", "");
    int correctIndex = (Integer.parseInt(wordNum)) - 1;
    order[correctIndex] = unordered[i];
}
1
  • That makes vey much a LOT of sense I thought that the replace just somehow happened automatically thank you, not forgetting this. Commented Nov 19, 2020 at 8:26
0

NumberFormatException is thrown when

  1. The input string provided might be null. Example-

     Integer.parseInt(null);
    
  2. The input string might be empty. Example-

     Integer.parseInt("");
    
  3. The input string might be having trailing space. Example-

     Integer.parseInt("123 ");
    
  4. The input string might be having a leading space. Example-

     Integer.parseInt(" 123");
    

The input string may be alphanumeric.Example-

    Long.parseLong("b2");

There are other reasons also. You are trying to pass unordered[i] in parseInt.

int correctIndex = (Integer.parseInt(unordered[i].trim())) -1;

It is an alphanumeric String. So the compiler gives NumberFormatException.

Try using this function to calculate the index instead.

    //Method to find the correctIndex
    static int findIndex(String s)
    {
        char ch;
   
        //Access all the characters of the String and the find the digit
        for (int i = 0;i < s.length();i++)
        {
            ch = s.charAt(i);
        
            if (Character.isDigit(ch))
            {
                return ch-49;     //Convert the character to index
            }
        }
    
        return -1;
     }
1
  • thank you for explaining everything that can go wrong with parseInt() it cleared up the kind of parameter I can pass in. Commented Nov 19, 2020 at 8:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.