@@ -531,12 +531,14 @@ void main() {
531531 <program xml : id =" python-input-file1" interactive =" activecode" language =" python" >
532532 <code >
533533def main():
534- count = [0]*10
535- data = open('test.dat')
534+ """ Program to read numbers from a file and produce a histogram. """
535+ count = [0]*10 # create a list of 10 zeros
536+ data = open('test.dat') # open the data file
537+ # read each line and update the count
536538 for line in data:
537539 count[int(line)] = count[int(line)] + 1
538540 idx = 0
539- for num in count:
541+ for num in count: # iterate over the list and print the histogram
540542 print(idx, " occurred ", num, " times.")
541543 idx += 1
542544main()
@@ -627,33 +629,40 @@ Here is the Java code needed to write the exact same program:
627629
628630 <program xml : id =" java-null-object" interactive =" activecode" language =" java" datafile =" test.dat" >
629631 <code >
630- import java.util.Scanner;
631- import java.util.ArrayList;
632- import java.io.File;
633- import java.io.IOException;
632+ import java.util.Scanner; // import the Scanner class to read input from the user
633+ import java.util.ArrayList; // import the ArrayList class to use dynamic arrays
634+ import java.io.File; // import the File class to read from files
635+ import java.io.IOException; // import the IOException class to handle file input/output exceptions
636+ /**
637+ * Program to read numbers from a file and produce a histogram in Java.
638+ */
634639public class Histo {
635640 public static void main(String[] args) {
636- Scanner data = null;
637- ArrayList< Integer> count;
641+ Scanner data = null;
642+ ArrayList< Integer> count; // create an ArrayList to hold counts of numbers, of type Integer
638643 Integer idx;
644+
645+ // Try to open the data file and handle any potential IOExceptions
639646 try {
640647 data = new Scanner(new File("test.dat"));
641648 }
642649 catch ( IOException e) {
643650 System.out.println("Unable to open data file");
644- e.printStackTrace();
651+ e.printStackTrace(); // print the stack trace for debugging
645652 System.exit(0);
646653 }
647- count = new ArrayList< Integer> (10);
654+ count = new ArrayList< Integer> (10); // create an ArrayList with an initial capacity of 10
648655 for (Integer i = 0; i < 10; i++) {
649- count.add(i,0);
656+ count.add(i,0); // initialize the first 10 positions in the ArrayList to hold the value 0
650657 }
651658 while(data.hasNextInt()) {
652- idx = data.nextInt();
659+ // read each integer from the file and update the count
660+ idx = data.nextInt();
653661 count.set(idx,count.get(idx)+1);
654662 }
655663 idx = 0;
656664 for(Integer i : count) {
665+ // iterate over each element in the ArrayList and print the histogram
657666 System.out.println(idx + " occurred " + i + " times.");
658667 idx++;
659668 }
0 commit comments