Hallo! I have a quation about java language! Write a program that reads a file c
ID: 3919861 • Letter: H
Question
Hallo!
I have a quation about java language!
Write a program that reads a file containing name (see class list) and puts all names in an ArrayList <String> called Class List.
Reading file is easiest with java's Scanner scan = new Scanner (new file ("filename")). Make sure the file is in the same folder as the application. If you are using Eclipse or another development environment, check where to add the text file.
Print the list so you know that the program works.
Type a method public static boolean addToList (ArrayList list, String name) that argues an ArrayList object list that contains a list of names in alphabetical order and a name. The method should investigate if the name is in the list. If not already, the name should be added to the list in the correct location (ie the list must remain sorted) and the method should return the true. If the name already exists, the method returns false.
Tip! Use the comparTo () method of the String class to find the correct index in the list.
Complete the program you have written before calling it the addToList method a few times, both with existing names and with names that are not available.
How can you prove that the program is working properly?
Here is class name!
Explanation / Answer
import java.io.*;
import java.util.*;
public class Demo237{
public static boolean addToList(ArrayList<String> list, String name){
for (int i = 0; i<list.size(); i++){
if (list.get(i).equals(name))
return false;
}
for (int i = 0; i<list.size(); i++){
if (list.get(i).compareTo(name) > 0){
list.add(i,name);
return true;
}
}
list.add(name);
return true;
}
public static void main(String[] args){
try {
ArrayList<String> data = new ArrayList<String>();
FileInputStream fin = new FileInputStream("input.txt");
Scanner fc = new Scanner(fin);
while (fc.hasNextLine()){
String name = fc.nextLine();
if (addToList(data,name))
System.out.println(name + " added");
else
System.out.println(name + " not added");
}
fc.close();
System.out.println("The names are:");
for (int i = 0; i<data.size(); i++){
System.out.println(data.get(i));
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.