I have a String array which contains both combination of strings and integers. I need to sort the strings and add the integers at the end. Here is the program I have written. Any optimization would be helpful.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class SortStringandAddIntegerEx { public static void main(String[] args) throws IOException { System.out.println("Enter the characters"); BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); String input = read.readLine(); String[] inputArray = { input }; List<String> result = new ArrayList<String>(); String stringChars = ""; String sortedCharacters = ""; int sum = 0; for (int i = 0; i < inputArray.length; i++) { stringChars = stringChars + inputArray[i]; } for (int j = 0; j < stringChars.length(); j++) { if (Character.isDigit(stringChars.charAt(j))) { sum = sum + Integer.parseInt(stringChars.valueOf(stringChars.charAt(j))); } else { sortedCharacters = sortedCharacters + stringChars.charAt(j); } } char[] chars = sortedCharacters.toCharArray(); Arrays.sort(chars); String sorted = new String(chars); result.add(sorted + " " + sum); for (int k = 0; k < result.size(); k++) { System.out.println("Final output is " + result.get(k)); } } }
Any help would be appreciated.