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
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++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With