Reached end of file while parsing java ошибка

I have the following source code

public class mod_MyMod extends BaseMod
public String Version()
{
     return "1.2_02";
}
public void AddRecipes(CraftingManager recipes)
{
   recipes.addRecipe(new ItemStack(Item.diamond), new Object[] {
      "#", Character.valueOf('#'), Block.dirt
   });
}

When I try to compile it I get the following error:

java:11: reached end of file while parsing }

What am I doing wrong? Any help appreciated.

asked Feb 8, 2011 at 14:44

adeo8's user avatar

1

You have to open and close your class with { ... } like:

public class mod_MyMod extends BaseMod
{
  public String Version()
  {
    return "1.2_02";
  }

  public void AddRecipes(CraftingManager recipes)
  {
     recipes.addRecipe(new ItemStack(Item.diamond), new Object[] {
        "#", Character.valueOf('#'), Block.dirt });
  }
}

Andrew Tobilko's user avatar

answered Feb 8, 2011 at 14:48

Bigbohne's user avatar

BigbohneBigbohne

1,3563 gold badges12 silver badges24 bronze badges

1

You need to enclose your class in { and }. A few extra pointers: According to the Java coding conventions, you should

  • Put your { on the same line as the method declaration:
  • Name your classes using CamelCase (with initial capital letter)
  • Name your methods using camelCase (with small initial letter)

Here’s how I would write it:

public class ModMyMod extends BaseMod {

    public String version() {
         return "1.2_02";
    }

    public void addRecipes(CraftingManager recipes) {
       recipes.addRecipe(new ItemStack(Item.diamond), new Object[] {
          "#", Character.valueOf('#'), Block.dirt
       });
    }
}

answered Feb 8, 2011 at 14:49

aioobe's user avatar

aioobeaioobe

414k113 gold badges812 silver badges827 bronze badges

0

It happens when you don’t properly close the code block:

if (condition){
  // your code goes here*
  { // This doesn't close the code block

Correct way:

if (condition){
  // your code goes here
} // Close the code block

eebbesen's user avatar

eebbesen

5,0908 gold badges48 silver badges70 bronze badges

answered Apr 21, 2015 at 23:29

ntthushara's user avatar

ntthusharantthushara

3313 silver badges5 bronze badges

1

Yes. You were missing a ‘{‘ under the public class line. And then one at the end of your code to close it.

answered Aug 14, 2017 at 1:28

Techno Savage's user avatar

  1. reached end of the file while parsing — Missing Class Curly Brace in Java
  2. reached end of the file while parsing — Missing if Curly Block Brace in Java
  3. reached end of the file while parsing — Missing Loop Curly Brace in Java
  4. reached end of the file while parsing — Missing Method Curly Brace in Java
  5. Avoiding the reached end of file while parsing Error in Java

Fix the Reach End of File While Parsing Error in Java

This tutorial introduces an error reach end of the file while parsing during code compilation in Java.

The reached end of the file while parsing error is a compile-time error. When a curly brace is missing for a code block or an extra curly brace is in the code.

This tutorial will look at different examples of how this error occurs and how to resolve it. The reached end of file while parsing error is the compiler’s way of telling it has reached the end of the file but not finding its end.

In Java, every opening curly place ({) needs a closing brace (}). If we don’t put a curly brace where it is required, our code will not work properly, and we will get an error.

reached end of the file while parsing — Missing Class Curly Brace in Java

We missed adding closing curly braces for the class in the example below.

When we compile this code, it returns an error to the console. The reached end of file while parsing error occurs if the number of curly braces is less than the required amount.

Look at the code below:

public class MyClass {
    public static void main(String args[]) {
  
      print_something();
    } 

Output:

MyClass.java:6: error: reached end of file while parsing
    }
     ^
1 error

The closing brace of the MyClass is missing in the above code. We can solve this issue by adding one more curly brace at the end of the code.

Look at the modified code below:

public class MyClass {
   static void print_something(){
     System.out.println("hello world");
   }
    public static void main(String args[]) {
  
      print_something();
    }  
  } 

Output:

Let us look at the examples where this error can occur.

reached end of the file while parsing — Missing if Curly Block Brace in Java

The if block is missing the closing curly brace in the code below. This leads to the reached end of the file while parsing error during code compilation in Java.

public class MyClass {
    public static void main(String args[]) {
      int x = 38;
      if( x > 90){
        // do something
          System.out.println("Greater than 90");
    }  
}

Output:

MyClass.java:8: error: reached end of file while parsing
}
 ^
1 error

We can resolve this error by adding the curly brace at the appropriate place (at the end of the if block). Look at the code below:

public class MyClass {
    public static void main(String args[]) {
      int x = 38;
      if( x > 90){
        // do something
          System.out.println("Greater than 90");
      } // this brace was missing
    }  
}

The above code compiles without giving any error.

Output:

reached end of the file while parsing — Missing Loop Curly Brace in Java

The missing curly braces can be from a while or a for loop. In the code below, the while loop block is missing the required closing curly brace, leading to a compilation failure.

See the example below.

public class MyClass {
    public static void main(String args[]) {
      int x = 38;
      while( x > 90){
        // do something
        System.out.println("Greater than 90");
        x--;
      
    }  
}

Output:

MyClass.java:10: error: reached end of file while parsing
}
 ^
1 error

We can resolve this error by putting the curly brace at the required position (at the end of the while loop). Look at the modified code below:

public class MyClass {
    public static void main(String args[]) {
      int x = 38;
      while( x > 90){
        // do something
        System.out.println("Greater than 90");
        x--;
      } // This brace was missing
    }  
}

The above code compiles without giving any error.

Output:

reached end of the file while parsing — Missing Method Curly Brace in Java

In this case, we have defined a method whose closing brace is missing, and if we compile this code, we get a compiler error. Look at the code below.

public class MyClass {
    
    public static void main(String args[]) {
      customFunction();
    }  
    static void customFunction(){
      System.out.println("Inside the function");
    
}

Output:

MyClass.java:9: error: reached end of file while parsing
}
 ^
1 error

We can resolve this error by putting the curly brace at the required position (at the end of the function body). Look at the modified code below:

public class MyClass {
    
    public static void main(String args[]) {
      customFunction();
    }  
    static void customFunction(){
      System.out.println("Inside the function");
    }
}

Output:

Avoiding the reached end of file while parsing Error in Java

This error is very common and very easy to avoid.

To avoid this error, we should properly indent our code. This will enable us to locate the missing closing curly brace easily.

We can also use code editors to automatically format our code and match each opening brace with its closing brace. This will help us in finding where the closing brace is missing.

«reached end of file while parsing» is a java compiler error. This error is mostly faced by java beginners. You can get rid of such kind of errors by coding simple java projects. Let’s dive deep into the topic by understanding the reason for the error first.

Read Also: Missing return statement in Java error

1. Reason For Error

This error occurs if a closing curly bracket i.e «}»  is missing for a block of code (e.g method, class).

Note: Missing opening curly bracket «{» does not result in the «reached end of file while parsing» error. It will give a different compilation error.

[Fixed] Reached end of file while parsing error in java

1. Suppose we have a simple java class named HelloWorld.java

public class HelloWorld
{
    public static void main(String args[])
    {
       System.out.println("This class is missing a closing curly bracket");
    }

If you try to compile the HelloWorld program using below command

javac HelloWorld.java

Then you will get the reached end of file while parsing error.

reached end of file while parsing java error

If you look into the HelloWorld program then you will find there is closing curly bracket «}» missing at the end of the code. 

Solution: just add the missing closing curly bracket at the end of the code as shown below.

public class HelloWorld
{
    public static void main(String args[])
    {
       System.out.println("This class is missing a closing curly bracket");
    }
}

2.  More Examples 

2.1  In the below example main() method is missing a closing curly bracket.

public class HelloWorld
{
    public static void main(String args[])
    {
       System.out.println("Main method is missing a closing curly bracket");
    
}

2.2 In the below example if block is missing a closing curly bracket.

public class HelloWorld
{
    public static void main(String args[])
    {
       if( 2 > 0 )
       {
            System.out.println("if block is missing a closing curly bracket");
    }
}

Similarly, we can produce the same error using while, do-while loops, for loops and switch statements.

I have shared 2.1 and 2.2 examples that you should fix by yourself in order to understand the reached end of file while parsing error in java.

3. How to Avoid This Error

You can avoid this error using the ALT + Shift + F command in Eclipse and Netbeans editor. This command autoformats your code then it will be easier for you to find the missing closing curly bracket in the code.

That’s all for today. If you have any questions then please let me know in the comments section.

This is a compile error, easily fixed

KIVILCIM PINAR / Getty Images

Updated on January 28, 2019

The Java error message Reached End of File While Parsing results if a closing curly bracket for a block of code (e.g, method, class) is missing.

The fix is easy — just proofread your code.

Example

In the code below, the method called main does not conclude with a closing curly bracket. The compiler cannot parse the code properly and will throw the error.

public class Main {
public static void main(String[] args) {
System.out.println("Oops missed a curly bracket..");
}

Avoiding the Error

Because this error is both common and easily avoided, using a code editor like Visual Studio Code or an integrated development environment like Eclipse. Code editors that feature linters and syntax checkers for Java (or whatever language you use) will uncover errors before you attempt to compile.

Ошибка «reached end of file while parsing } java» возникает в Java-программировании, когда компилятор обнаруживает, что в файле закончилось необходимое количество закрывающих скобок. Эта ошибка может возникать при написании программы, когда программист неправильно использует открывающие и закрывающие скобки, не следует правилам форматирования кода или пропускает закрывающую скобку.

Если в вашей программе возникла ошибка «reached end of file while parsing } java», то первое, что нужно сделать, это проверить, имеется ли в вашем коде необходимое количество закрывающих скобок. Если закрывающая скобка недостает, нужно добавить ее в соответствующее место в коде.

Если вы уверены, что в вашем коде все скобки расставлены правильно, то причиной ошибки может быть несоблюдение форматирования кода. Рекомендуется следовать стандартам кодирования Java и правилам форматирования кода, чтобы избежать подобных ошибок.

Для удобства чтения и отладки кода, следует использовать отступы, чтобы отмечать каждый уровень вложенности кода. Это поможет различать блоки кода и установить соответствующие открывающие и закрывающие скобки.

Автоматические инструменты проверки кода, такие как Eclipse, IntelliJ IDEA или NetBeans, могут помочь избежать ошибок компиляции, включая «reached end of file while parsing } java».

Другими причинами возникновения ошибки могут быть синтаксические ошибки, которые могут привести к тому, что компилятор не сможет определить, где завершается блок кода. Обычно компилятор сообщает о синтаксических ошибках вместе с текстом ошибки, который указывает на место проблемы.

Возможно, проблема находится в нескольких файлах проекта. Обычно в таком случае необходимо начать поиск ошибок с того места, где ошибка возникает, и далее продолжить до тех пор, пока не будет найден первоначальный исход ошибки.

Иногда правописание и использование ключевых слов, среди других факторов, могут вызвать ошибку «reached end of file while parsing } java». Перепроверьте все объявления переменных, функций, классов, методов и операторов, чтобы выявить проблему, если она есть.

В заключение, ошибка «reached end of file while parsing } java» может произойти в результате недостаточного количества закрывающих скобок в вашей программе, которые необходимо добавить, также могут быть связаны с нарушением форматирования кода, пропуском закрывающей скобки, синтаксическими ошибками или с другими проблемами, которые необходимо исследовать и решить. Необходимо быть тщательными и внимательными при написании кода и использовать различные инструменты, доступные для отладки кода.

Понравилась статья? Поделить с друзьями:
  • Red alert 3 ошибка 5 0000065434
  • Red alert 2 фатальная ошибка
  • Red alert 2 ошибка присоединения
  • Red alert 2 ошибка loeaea iaaicii
  • Red alert 2 ошибка ioeaea