future2020 future2020 - 4 months ago 30
Java Question

eclipse says to insert "EnumBody" to complete EnumDeclaration

I wanted to create a method to write on files. But i got this error

Syntax error, insert "EnumBody" to complete EnumDeclaration


Here is my code

import java.io.*;
import java.util.*;
public class ClassA throws IOException{
public void writer(){
PrintWriter writer = new PrintWriter("Name.txt", "UTF-8");
Scanner in = new Scanner(System.in);
writer.println("The first line");

writer.close();
}
}


and my main class is

public class Main {
public static void main(String[] args){
ClassA test = new ClassA();
test.writer();
}
}


There is red line under class(in Writer class) and '{' after IOException.
What is the problem and if it can't be solved how to declare a method to write on File.

I am using eclipse on Windows10.

Answer

Classes don't throw exceptions, methods do. Move throws IOException to the writer() method signature.

import java.io.*;
import java.util.*;
public class ClassA {
  public void writer() throws IOException {
    PrintWriter writer = new PrintWriter("Name.txt", "UTF-8");
    Scanner in = new Scanner(System.in);
    writer.println("The first line");

    writer.close();
  }
}
Comments