O
O
Optimus2015-03-03 15:24:37
Java
Optimus, 2015-03-03 15:24:37

Where is the error in the simplest JAVA script?

Compiled ideone.com/gA6knT Script
:

class HelloWorld {
    public static void main(String[] args) {
        // int x = 10;

        for (int x = 1; x<11; x=x+1){
        	
          if(x==1){
          	String name = "бутылка";
          }
          if(x==2 | x==3 | x==4){
          	String name = "бутылки";
          }
          if(x > 4 & x < 21){
          	String name = "бутылок";
          }
          
        System.out.println("У нас есть " + x + name);
        }
        
    }
}

He says that the name variable is missing, as I understand it (cannot find symbol symbol: variable name), so it seems to be defined for all variants present in the cycle ...
The second question: in line 3, int x = 10 is commented out; if you uncomment it, it swears at for (int x = 1 and says that the variable is already defined above. So JAVA does not support redefinition like in php or is it somehow done differently?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anatoly Zhukov, 2015-03-03
Pyan @marrk2

1. The problem is in the scope of the name variable. Take out String name = null; before the loop, and in the loop already define it (name = ....)
2. use for(x =1; x<11; x++)

V
Vasily, 2015-03-03
@Applez

That's what you have to beat on the hands.
And yes, read about variable scopes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question