Text file number.txt contains 1000 integers vary from 1 to 100. You need to 1. U
ID: 3702362 • Letter: T
Question
Text file number.txt contains 1000 integers vary from 1 to 100. You need to
1. Use an ArrayList (Required) to store all integers. If one number appears multiple times in text file, only save the first occurrence in the ArrayList.
2. The output should be saved in one txt file called results.txt In results.txt, the output information should be in the following format
Name: XXXXXXX
Email: XXXXXXXX@xxx.edu
3. The output information should be in the following format in the text file.
Number Occurrence Times
1 3
2 1
3 2
. .
. .
100 1
Numbers 1 to 100 should be in the first column in the order of appearance. Second column presents the occurrence times of the corresponding number.
Explanation / Answer
import java.util.*;
import java.io.*;
class Solution
{
public static void main(String[] args)
{
try{
// create a FileReader object
FileReader fr = new FileReader("input.txt");
// create an object to read file
Scanner sc = new Scanner(fr);
ArrayList<Integer> arr = new ArrayList<Integer>();
// store the number of times the element i appears in count
int[] count = new int[101];
int i;
while( sc.hasNext() )
{
int x = Integer.parseInt( sc.next() );
// if current elements is not present in arr
if( !arr.contains(x) )
// add element to arr
arr.add(x);
count[x]++;
}
// create FileWriter object to write into file
FileWriter fw = new FileWriter("output.txt");
fw.write("Name : ");
fw.write("Email : ");
fw.write("Number Occurence Times ");
for( i = 1 ; i <= 100 ; i++ )
fw.write(i + " " + count[i] + " ");
fw.flush();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
---------------------------input.txt--------------------------
1
2
1
3
4
4
100
100
98
100
99
99
-----------------------------output.txt------------------------------
Name :
Email :
Number Occurence Times
1 2
2 1
3 1
4 2
5 0
6 0
7 0
8 0
9 0
10 0
11 0
12 0
13 0
14 0
15 0
16 0
17 0
18 0
19 0
20 0
21 0
22 0
23 0
24 0
25 0
26 0
27 0
28 0
29 0
30 0
31 0
32 0
33 0
34 0
35 0
36 0
37 0
38 0
39 0
40 0
41 0
42 0
43 0
44 0
45 0
46 0
47 0
48 0
49 0
50 0
51 0
52 0
53 0
54 0
55 0
56 0
57 0
58 0
59 0
60 0
61 0
62 0
63 0
64 0
65 0
66 0
67 0
68 0
69 0
70 0
71 0
72 0
73 0
74 0
75 0
76 0
77 0
78 0
79 0
80 0
81 0
82 0
83 0
84 0
85 0
86 0
87 0
88 0
89 0
90 0
91 0
92 0
93 0
94 0
95 0
96 0
97 0
98 1
99 2
100 3
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.