Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
713 views
in Technique[技术] by (71.8m points)

sorting - Java: Variable is already defined in method main

So I have been the following error every time I try to compile my .java file

"error: variable max is already defined in method main(String[]) int max = j; "

And I haven't been able to figure out what is the issue or how to fix it. Been stuck at it for about 2 hours now. What I'm trying to ultimately do is enter one integer into my array and sorting the digits in that integer from least to greatest to provide context.

Here is the relevant part from my code:

   int[] wholeNumber = new int[1];


   //Sorting algorithm beginning
   int n = wholeNumber.length;

   System.out.println("Length of array is :" + n); //Array length displayed

   for(int i = 0; i < 1; i++)
   {
     System.out.println("Hello!");

     int max = i;

     for(int j = i+1; j < 1; j++)
     {
       if (wholeNumber[j] > wholeNumber[max])
       {  
          int max = j;
       }

     }
     if (max != i)
     {
        wholeNumber[i] = wholeNumber[max];
        wholeNumber[max] = wholeNumber[i];
     }



   }
   //Sorting algorithm end
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As the error says, you have int max declared twice. You need to change the second one to a variable assignment, not declaration:

 int max = i;

 for(int j = i+1; j < 1; j++)
 {
   if (wholeNumber[j] > wholeNumber[max])
   {  
      max = j; // NOT: int max = j;
   }
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...