Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA Variable declaration not allowed here

I get an error "Variable declaration not allowed here" and I don't know why, I'm new in java and can't find answer :/ As it says, I can't make "int" in "if" but is there a way to create it?

import java.io.PrintWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;import java.util.Scanner;
 public class test{
  public static void main(String[] args) throws FileNotFoundException{
    File plik = new File("test.txt");
    PrintWriter saver = new PrintWriter("test.txt");

     int score = 0;
     System.out.println("Q: What's bigger");
     System.out.println("A: Dog B: Ant");
     Scanner odp = new Scanner(System.in);
     string odpo = odp.nextLine();

     if(odpo.equals("a"))
        int score = 1;
     else
         System.out.println("Wrong answer");

  }
}
like image 570
TheXDX Avatar asked Sep 16 '26 06:09

TheXDX


1 Answers

As per Java spec, You cannot declare a local variable when there is no scope. While declaring int score = 1 in if, there is no scope. http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html

A local variable, one of the following
*A local variable declared in a block
*A local variable declared in a for statement

Also you have already declared a variable named score above. Even if you remove that declaration, you'll get the error because of the above reason.

like image 168
barunsthakur Avatar answered Sep 17 '26 20:09

barunsthakur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!