Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: '.class' expected error when passing array to function [closed]

I'm taking a java class, but have been away from it for a bit.

Trying to get this sorting program to work:

import java.util.*;
public class Assignment1 
{
   private int[] nums;
   private int[] ast;

   private int n;

   public void sort(int[] vals)
   {
      this.nums = vals;
      n = vals.length;
      this.ast = new int[n];
      merges(0, n - 1);
   }   

   private void merges(int bot, int top)
   {
      if (bot < top)
      {
         int mid = bot + (top - bot) / 2;
         merges(bot, mid);
         merges(mid + 1, top);
         merge(bot, mid, top);
      }
   }

   private void merge(int bot, int mid, int top)
   {
      for (int i = bot; i <= top; i++)
      {
         ast[i] = nums[i];
      }
      int i = bot;
      int j = mid + 1;
      int k = bot;
      while (i <= mid && i <= top)
      {
         if (ast[i] <= ast[j])
         {
            nums[k] = ast[i];
            i++;
         }
         else
         {
            nums[k] = ast[j];
            j++;
         }
         k++;
      }
      while (i <= mid)
      {
         nums[k] = ast[i];
         k++;
         i++;
      }
   }

   private void show()
   {
      System.out.print("Sorted Array:  ");
      for(int l=0;l<nums.length;l++)
      {
         System.out.print(nums[l] + "  ");
      }

   }
   public static void main(String[] args) 
   {
      Assignment1 a = new Assignment1();
      Scanner scan = new Scanner(System.in);
      System.out.print("\nArray Size: ");
      int s = scan.nextInt();
      int[] array = new int[s];
      for(int x=0;x<s;x++)
      {
         System.out.print("Enter Element " + (x + 1) + ":");
         array[x] = scan.nextInt();
      }


      a.sort(array[]);
      a.show();
   }
}

The error I'm getting is this:

Assignment1.java:82: error: '.class' expected
  a.sort(array[]);

I know it's something basic eluding me, but the basics are the things that are most hazy...

like image 735
ShengLong916 Avatar asked Feb 21 '14 23:02

ShengLong916


1 Answers

I believe the compiler thinks you are trying to pass in an class type into sort because you added the [] after array in your call to sort which is how you declare an array type.

Just change

a.sort(array[]) 

to

 a.sort(array)

because you have already initialized array as an int[] type/array earlier in your method.

You only need to add the [] during the intialization. After that, the variable name for an array is referenced just like the variable name for any other variable.

like image 96
mdewitt Avatar answered Oct 11 '22 14:10

mdewitt