If by any amazing chance, somebody looooves programming java and would like to do my assignment, please feel free . I have 4 tests tomorrow and dont have time to mess w/ this. LAB # 17 - Using an array as a counter. Write a class, PercentDigit, that creates 2000 random integers between 1 and 1000 and stores these numbers directly onto numbers2000.txt (not the array). Then read the numbers from the text file and count the number of numbers that begin with a 1 (15,132,199,1), with a 2, with a 3 and so on through 9 onto a count array of size 10. Output the % of each number using DecimalFormat. You will have a separate driver program that creates a PercentDigit object and runs the program. public static void main(String[]args) { PercentDigit p = new PercentDigit(); p.writeToFile(); p.fillArray(); System.out.println(p); }
ewww, I hate how teachers make you do OOP when its just plain stupid to use it. Code (Text): import java.io.*; import java.text.DecimalFormat; public class PercentDigit { String[] array; DecimalFormat df = new DecimalFormat( "00.00%" ); public void writeToFile() throws Throwable { PrintWriter out = new PrintWriter( new BufferedWriter( new FileWriter( "numbers2000.txt" ) ) ); for( int i = 0; i < 2000; i++ ) out.println( (int)( 1 + 1000*Math.random() ) ); out.close(); } public void fillArray() throws Throwable { BufferedReader in = new BufferedReader( new FileReader( "numbers2000.txt" ) ); array = new String[2000]; for( int i = 0; i < 2000; i++ ) array[i] = in.readLine(); } public String toString() { int[] count = new int[9]; for( String s : array ) count[ s.charAt( 0 )-'1' ]++; String s = ""; for( int i = 0; i < 9; i++ ) s += ( i+1 ) + ":\t" + df.format( count[i]/2000d ) + '\n'; return s; } public static void main( String[] args ) throws Throwable { PercentDigit p = new PercentDigit(); p.writeToFile(); p.fillArray(); System.out.println( p ); } }
Nice code Zer0.... it's nothing hard, but not one simple line of this code can be removed. Optimization baby ! :lol:
lol, I tend to optimize and condense all of my code (while still retaining readability) Just looking at it now, I can eliminate one line. Without the stupid constraint to use functions, I could probably shorten the code by an extra 10 lines or so.