Question: My code below wont allow me to enter the ID number and I cannot figure out why. The error that shows is below the code,
My code below wont allow me to enter the ID number and I cannot figure out why. The error that shows is below the code, thank you for your help.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String data = "";
String id = "";
while (true) {
System.out.println("Enter 'List' to Show Items | Enter 'Add' to Add Professor | Enter 'Exit' to Exit ");
String choice;
choice = sc.nextLine();
if (choice.equals("List")) {
try {
File object = new File("file.txt");
Scanner scan = new Scanner(object);
while (scan.hasNextLine()) {
data = scan.nextLine();
id = scan.nextLine();
System.out.println(data);
System.out.println(id);
}
scan.close();
} catch (FileNotFoundException e) {
System.out.println("No Files Found.");
System.out.println("Must Add Information Before Viewing List");
}
} else if (choice.equals("Add")) {
System.out.println("Enter name to add:");
String name = sc.next();
data += (name);
System.out.println("Enter ID:");
String number = sc.next();
id = (number); //New 'if' statement if needed
try {
FileWriter writer = new FileWriter("file.txt");
writer.write(data);
writer.close();
writer.write(id);
System.out.println("Successfully wrote to the file. ");
System.out.print(data + " has been added to the file with ID Number ");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
else break;
}
sc.close();
}
}
Enter 'List' to Show Items | Enter 'Add' to Add Professor | Enter 'Exit' to Exit
Add
Enter name to add:
James
Enter ID:
4444
An error occurred.
java.io.IOException: Stream closed
at java.base/sun.nio.cs.StreamEncoder.ensureOpen(StreamEncoder.java:51)
at java.base/sun.nio.cs.StreamEncoder.write(StreamEncoder.java:124)
at java.base/sun.nio.cs.StreamEncoder.write(StreamEncoder.java:141)
at java.base/java.io.OutputStreamWriter.write(OutputStreamWriter.java:223)
at java.base/java.io.Writer.write(Writer.java:249)
at Main.main(Main.java:44)
Enter 'List' to Show Items | Enter 'Add' to Add Professor | Enter 'Exit' to Exit
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
