Create a class called StreamStats with one constructor and two methods Given an
ID: 3695712 • Letter: C
Question
Create a class called StreamStats with one constructor and two methods Given an InputStream input for which you will process some statistics read the entire InputStream supplied in the constructor. While reading the stream determine what types of input you are consuming number of booleans in the stream number of doubles in stream number of ints in the stream number of strings (any token that does not classify as boolean, double or int) example: 'This is a 2 true 3.14 13.45" one boolean two doubles one int three Strings return a vector of statistics in the stream seen in the stream. [# of Boolean, # of double, # of int, # of String] (the order is the alphabetical order the types.) if consume () has not been invoked, the vector returned should be all zeros. Example: the vector returned in the example above would be [1, 2, 1, 3]Explanation / Answer
import java.io.IOException; import java.io.InputStream; import java.util.Scanner; class StreamStats{ InputStream is; int bools =0, ints = 0, doubles =0, strs = 0; public StreamStats(InputStream is) { this.is = is; } public void consume() throws IOException { Scanner s = new Scanner(is).useDelimiter("\A"); String str = s.hasNext() ? s.next() : ""; String[] arr = str.split(" "); for(String st : arr){ if(st.equalsIgnoreCase("true")||st.equalsIgnoreCase("false")){ bools++; continue; } try{ int i = Integer.parseInt(st); ints++; continue; }catch (NumberFormatException e){ } try{ double d = Double.parseDouble(st); doubles++; continue; }catch (NumberFormatException e){ } strs++; } System.out.println("Boolean :"+bools); System.out.println("integers :"+ints); System.out.println("doubles :"+doubles); System.out.println("Strings :"+strs); } public int[] stats(){ int[] arr = new int[4]; arr[0] = bools; arr[1] = doubles; arr[2] = ints; arr[3] = strs; return arr; } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.