In: Computer Science
Please write in java: Write a fragment that reads a sequence of strings and inserts each string that is not numeric at the front of a deque and each string that is numeric at the rear of a deque. Your fragment should also count the number of strings of each kind. Display the message "Strings that are not numeric" followed by the nonnumeric strings and then the message "Strings that are numbers" followed by the numeric strings. Do not empty the deque.
Here NonNumericAndNumericCollection is the fragment which stores the string that is not numeric at the front of a deque and each string that is numeric at the rear of a deque
NonNumericAndNumericCollection.java:
import java.util.LinkedList; /** * DeQue that stores non numeric string in the start and numeric strings at the end */ public class NonNumericAndNumericCollection { public LinkedList<String> deQue = new LinkedList<>(); private int numberOfNonNumericStrings = 0; private int numberOfNumericStrings = 0; public LinkedList<String> getDeQue() { return deQue; } /** * * @return Number of non numeric strings */ public int getNumberOfNonNumericStrings() { return numberOfNonNumericStrings; } /** * * @return Number of numeric strings */ public int getNumberOfNumericStrings() { return numberOfNumericStrings; } /** * If the string is non numeric then add it to the start. Otherwise add it at the end * * @param s String to be added */ public void add(String s) { try { Double.parseDouble(s); //raises NumberFormatException if the string is not numeric deQue.addLast(s); //adds the non numeric string at end numberOfNumericStrings++; } catch (NumberFormatException e) { deQue.addFirst(s); //adds the non numeric string at first numberOfNonNumericStrings++; } } /** * Prints the strings of the DeQue */ public void printNonNumericAndNumericCollection() { System.out.println("There are " + getNumberOfNonNumericStrings() + " strings that are not numeric:"); for (int i = 0; i < numberOfNonNumericStrings; i++) System.out.println(i + 1 + ". " + deQue.get(i)); System.out.println("There are " + getNumberOfNumericStrings() + " strings that are numeric:"); for (int i = numberOfNonNumericStrings; i < deQue.size(); i++) System.out.println(i - numberOfNonNumericStrings + 1 + ". " + deQue.get(i)); } }
Main.java:
/** * Driver class to test the fragment */ public class Main { public static void main(String[] args) { NonNumericAndNumericCollection collection = new NonNumericAndNumericCollection(); collection.add("Rob"); collection.add("1"); collection.add("John"); collection.add("George"); collection.add("2"); collection.add("Bill"); collection.add("3"); collection.printNonNumericAndNumericCollection(); } }
Output:
Please comment if you want any tweaks or clarification in the code