[Java Programming] When I turn FileWriter on a while statement, I get an error.

Asked 2 years ago, Updated 2 years ago, 42 views

Hello, I am a student who is learning Java. I'm making a diary program for my school assignment. Using File Class such as FileWriter and FileReader in Java, diaries and schedules were saved as notepads, and the contents of the stored notepad were read NoSuchElementException error occurs when you enter the contents and press Enter and Ctrl + Z when saving a schedule or diary (pictured as attached).

How can we solve this? (Use Java Eclipse.)

Below is the code.

/*Class with DiaryMenu.java main method*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;
public class DiaryMenu{
    public static void main (String args[]) throws IOException{
        Scanner scanner = new Scanner(System.in);
        int choice =0;
        int choice2 =0;
        ScheduleAdd scheduleAdd = new ScheduleAdd();
        WriteDiary writeDiary = new WriteDiary();

        while (choice!=5) {
            System.out.print ("(1) Schedule (2) Diary (3) Credit Calculator (4) User Setup (5) Exit >>");
            choice = scanner.nextInt();

            switch (choice) {
            case 1:
                System.out.print("(1) Calendar View (2) Register Schedule (3) Schedule View >>");
                choice2 = scanner.nextInt();
                if (choice2 == 1) {
                    BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
                       System.out.print ("Enter year:"); 
                       int year = Integer.parseInt(br.readLine()); 
                       System.out.print (enter month: "); 
                       int month = Integer.parseInt(br.readLine()); 
                       Calender cal = new Calender(year, month); 
                       cal.Display();
                }

                If (choice2 == 2) {//Register Schedule
                    scheduleAdd.scheduleAdd();
                }

                If (choice2 == 3) {//View schedule
                }
                else {
                    System.out.print ("You have entered it incorrectly."");
                }

                break;
            case 2:
                System.out.print("(1) Writing a Diary (2) Reading a Diary >>");
                choice2 = scanner.nextInt();

                if (choice2 == 1) {
                    writeDiary.addDiary();
                }

            }
        }
    }
}

/*ScheduleAdd.java (1) Schedule -> (2) Schedule Registration*/
import java.io.*;
import java.util.Scanner;

public class ScheduleAdd {
    InputStreamReader in = new InputStreamReader(System.in);
    FileWriter sch = null;
    String schedule_day = null;

    Scanner scanner = new Scanner(System.in);

    public void scheduleAdd () {
        System.out.print ("Enter the date to register for the schedule (ex: 160611) >>");
        schedule_day = scanner.nextLine();
        int c;
        //System.out.println();
        System.out.print ("Enter after entering schedule content, ctrl+z>>");

        try {
            sch = new FileWriter("d:\\KNKDiary\\schedule\\"+schedule_day+".txt");

            while ((c=in.read())!= -1) {
                sch.write(c);
            }
            in.close();
            sch.close();
        }
        catch (IOException e) {
            System.out.println ("input/output error");
        }
        System.out.println ("Saved".");
    }
}

java eclipse

2022-09-22 21:56

1 Answers

Entering Ctrl+Z from the console in Windows Glasses is the same as sending End of File (EOF) to an application. (Ctrl+D on UNIX)

EOF is usually the end of the file, meaning InputStream has nothing more to read.

When marked as EOF on System.in, I understand that after that, you will only read the EOF, and you will not be able to enter any more.

First of all, if you want to exit without errors, you can modify the code as follows.

while (choice!=5) {
            System.out.print ("(1) Schedule (2) Diary (3) Credit Calculator (4) User Setup (5) Exit >>");
            if( scanner.hasNext() ) {
                choice = scanner.nextInt();
            } } else {
                // End.
                break;
            }

Please make the following changes.

private static string TERMINATE = "."; // End character
public void scheduleAdd() {
     System.out.print ("Enter the date to register for the schedule (ex: 160611) >>");
     schedule_day = scanner.nextLine();
     //System.out.println();
     System.out.print("To enter and exit after entering the schedule, enter only a period (.) in the last line>>");}

     int lines = 0; // Tip: Delete if no line is entered.
     Path path = Paths.get("d:\\KNKDiary\\schedule\\"+schedule_day+".txt");
     // When using Java NIO2, you must import java.nio.file.Path and java.nio.file.Paths.
     try(sch = new FileWriter(path.toFile())) {
        // Autoclose is supported from Java 7 onwards.
        // Automatically close when the try syntax ends.

        while(scanner.hasNext()) {
            String line = scanner.nextLine();
            if( TERMINATE.equals(line) { // if the current character is a period.
                sch.flush();
                break;
            }
            lines++;
            sch.If you read line with write(line); // scanner, the line break character at the end is removed.
            sch.write(System.lineSeparator()); // Line break. From Java 7, you can use System.lineSeparator() for the line separator.            
        }
     } } catch(IOException e) {
        System.out.println ("input/output error");
     }
    If (lines == 0) { // Tip: Cancel if you have not entered any lines.
        Files.delete(path); // Delete the file. You must import java.nio.file.Files.
        System.out.println ("Cancelled".");
    } } else {
        System.out.println ("Saved".");
    }

}


2022-09-22 21:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.