import java.util.*;
import static java.lang.System.*;
public class tester
{
public static void main(String args[])
{
Scanner kbReader = new Scanner (in);


System.out.print("Enter your integer here."); //enter 3001
int i = kbReader.nextInt( );


int  count =0;
for(int i = 100; i <= 999; i++)
{
int factors = 0 ;
for (int j = i;j<=i;j++)
{
if(i%j == 0)
factors++;
}
if (factors == 2)
out.print(i+"\t");
if((count +1) %5 == 0)
System.out.println();
count ++;
}
}
}

it says "i is already defined in main(java.lang.String[])"
what's wrong?

Recommended Answers

All 5 Replies

You've already defined the "i" in

int i = kbReader.nextInt( );

So you cannot declare it again in for loop as

for(int i = 100; i <= 999; i++)

you can re-define it, but not as long as it is in the same scope.

you can re-define it, but not as long as it is in the same scope.

Yes, but that is not what the OP is asking for. The OP is asking for "why" he/she gets the error. Also, the class the OP created has only 1 method scope -- main. As a result, attempt to define "i" anywhere in the method after the first define will not be valid.

Anyway, I don't think that the answer should involve that "redefine" because it is confusing for a beginner.

true, it was just a little remark on your first answer, but, method scope is not the only kind of scope:

for (int i = 0; i < 5 ; i++){
}
for ( int i = 0; i < 15; i++){
}

can occur in the same method, yet it's not in the exact same scope.
I didn't mean your first answer was incorrect in light of the OP's question.

Great description. That's what the explanation I would want you to show when you are talking about redefine. Unfortunately, this could be more confusing for the OP because of the way the OP declare the variable.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.