Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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;
   }
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...