M251 Meeting 7 Activity Solution
M251 Meeting 7 Activity Solution
)Input/Output Files(
A. Write a Java class DemoFiles, the class has the following methods:
Solution: A.
import java.io.*;
import java.util.*;
//2
public DemoFiles(){
list = new ArrayList<String>();
}
//3
public void fill(){
list.add("Ali 90 95 88");
list.add("Sami 85 84 90");
list.add("Rana 78 85 88");
list.add("Huda 66 75 68");
}
//4
public void writeToFile(){
try{
File f = new File("C:/students.txt");
PrintWriter pr = new PrintWriter(f);
for(String x : list)
pr.println(x);
pr.close();
}
catch(IOException e){
System.out.println("There is an error "+ e);
}
}
//5
public void readFrom(){
try{
File f = new File("C:/students.txt");
Scanner sc = new Scanner(f);
String s, name; int g1,g2, g3; double avg;
int c = -1;
while(sc.hasNext()){
name = sc.next();
g1 = sc.nextInt();
g2 = sc.nextInt();
g3 = sc.nextInt();
avg = (g1+g2+g3)/3.0;
c++;
s = "Name is: "+list.get(c)+", avg ="+ avg;
list.set(c, s);
}
sc.close();
}
catch(FileNotFoundException e){
System.out.println("The File is not found");
}
}
//6
public void printList(){
for(String x : list)
System.out.println(x);
}
}
Solution: B.
public class Activity_Meeting7 {
df.fill();
df.writeToFile();
df.readFrom();
df.printList(); }