KaiquanMah's picture
catch (FileNotFoundException e) {...}
ea79f6b verified
Write a program that asks the user for names.
The given names are added to a file named 'names.txt' such that each name is on its own line.
When the user enters the name "stop", the program execution ends.
import java.util.Random;
import java.util.ArrayList;
import java.util.Arrays;
import java.io.FileNotFoundException;
import java.util.Collections;
import java.util.Scanner;
public class Test{
public static void main(String[] args){
final Random r = new Random();
//ADD
Scanner reader = new Scanner(System.in);
ArrayList<String> names = new ArrayList<String>();
// get user input 'name'
while (true) {
System.out.print("Enter a name: ");
String name = String.valueOf(reader.nextLine());
// break if user inputs "stop"
if (name.equals("stop")) {
break;
}
// add name to ArrayList
names.add(name);
}
// add name to the file, separated by newline "\n"
try (PrintWriter file = new PrintWriter("names.txt")) {
names.forEach(name -> file.write(name + "\n"));
}
catch (FileNotFoundException e) {
System.out.println("An error occurred: " + e);
}
System.out.println("File content:");
}
}
Enter a name: Jack
Enter a name: Sophie
Enter a name: Oliver
Enter a name: Harry
Enter a name: Harry
Enter a name: Jack
Enter a name: Sophie
Enter a name: Lily
Enter a name: Oliver
Enter a name: Emily
Enter a name: Emily
Enter a name: Lily
Enter a name: stop
File content:
Jack
Sophie
Oliver
Harry
Harry
Jack
Sophie
Lily
Oliver
Emily
Emily
Lily