Using an array, reading from a file

From Progzoo
Jump to: navigation, search

In these tutorials you are passed a token stream containing numbers.

  • When the tokens run out then token.nextToken() returns the value StreamTokenizer.TT_EOF
  • You can read the current token as a double using token.nval
  • to change this to an integer you can cast as an int using (int)token.nval

There are three files used in these examples:

array01.txt: 1 1 1 5 9 9
array02.txt: 3 1 4 1 5
array03.txt: 2 4 6 1 2 2 6

Print each digit in the file

Add the following line inside the while loop, after the declaration of n.

    System.out.println(n);

to see each number in the file.


[Font] [Default] [Show] [Resize] [History] [Profile]

The following questions are the same as the previous tutorial - it's just that you are reading data from a file.

Show the frequency of each digit

You can create an array with ten items - one for each digit (you may be sure that all numbers in x are between 0 and 9).

if x is the list [1,1,1,5,9,9]
then the result will be

freq
0      0
1      3
2      0
3      0
4      0
5      1
6      0
7      0
8      0
9      2

Print the frequency of each digit


[Font] [Default] [Show] [Resize] [History] [Profile]

Show the number of different digits

If x is the list [1,1,1,5,9,9] then the result will be 3 because there are three different number (namely 1,5 and 9)

You can use the freq array created as above - then just count the number of non-zero elements using an accumulator:

 int acc = 0;
 for (int i=0;i<freq.length;i++)
   if (freq[i]>0)
     acc++;
 System.out.println(acc);

Print the number of different digits


[Font] [Default] [Show] [Resize] [History] [Profile]

Show the repeated digits

If x is the list [1,1,1,5,9,9] then the result will be 1 and 9 because 1 occurs more than once and 9 occurs twice.

You can use the freq array created as above - then just show the index when the freq is more than 1:

 for (int i=0;i<freq.length;i++)
   if (freq[i]>1)
     System.out.println(i);

Print the repeated digits


[Font] [Default] [Show] [Resize] [History] [Profile]

Show the missing digits

If x is the list [1,1,1,5,9,9] then the result will be 2 3 4 6 7 8 because these digits are not in the input list.

You can use the freq array created as above - then just print the indexes when the freq is 0:

  for (int i=0;i<freq.length;i++)
    if (freq[i]==0)
      System.out.println(i);

Print the missing digits


[Font] [Default] [Show] [Resize] [History] [Profile]