Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumberFormatException for String that appears to be a number

I have a little problem with one JAVA program. I am trying to do a InsertionSort algorithm, but it seems to be the problem with converting String that program gets via stdin. It seems like program is working with few numbers, but it doesn't work with these numbers: https://dl.dropboxusercontent.com/u/57540732/numbers.txt

This is my algorithm:

public class Sort {

    private static ArrayList<String> insertionSort(ArrayList<String> arr) {
        for (int i = 1; i < arr.size(); i++) {
            int valueToSort = Integer.parseInt(arr.get(i).trim());
            int j = i;
            while (j > 0 && Integer.parseInt(arr.get(j - 1).trim()) > valueToSort) {
                arr.set(j, arr.get(j-1));
                j--;
            }
            arr.set(j, Integer.toString(valueToSort));
        }
        return arr;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ArrayList<String> al;
        String inputNumbers = sc.nextLine();
        String[] xs = inputNumbers.split(" ");
        al = new ArrayList<String>(Arrays.asList(xs));
        al = insertionSort(al);
        for (int i = 0; i<al.size(); i++) {
            System.out.print(al.get(i) + " ");
        }
    }
}

It works with few numbers, but not with that files I provided to you. I get following exception:

Exception in thread "main" java.lang.NumberFormatException: For input string: "4531"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at Sort.insertionSort(Sort.java:10)
    at Sort.main(Sort.java:25)

I don't know why I get this exception, because input string is a number (4531). Any suggestions? I can't copy and paste al of the numbers from file to terminal, so I am using this command:

javac Sort.java
java Sort < numbers.txt
like image 296
golobitch Avatar asked Sep 25 '22 21:09

golobitch


1 Answers

You have invisible char in "4531".

How fixed this:

After:

    al = new ArrayList<String>(Arrays.asList(xs));

Write:

    List a2 = new ArrayList<String>(a1.size());
    for(String s: a1) {
       a2.add(s.replaceAll("[^\\d.]", ""));    
    }
    a1 = a2;

How found this char:

After:

    al = new ArrayList<String>(Arrays.asList(xs));

Write:

    List a2 = new ArrayList<String>(a1.size());
    int line = 0;
    for(String s: a1) {
       int i = 0;
       for(char c: str.trim().toCharArray() {
           if(!Character.isDigit(c) {
               System.out.println("In line" + line + " char " + i + " isn't digit")
           }
           i++;
       }  
       line++;    
    }
like image 193
Slava Vedenin Avatar answered Oct 11 '22 13:10

Slava Vedenin