【问题标题】:Issue with arrays and methods数组和方法的问题
【发布时间】:2014-04-21 00:52:01
【问题描述】:

所以我想用这个程序做的是取两个数组,然后将它们合并到第三个数组中。 main 方法从指定文件中获取数据,然后为每一行创建数组,并且只有两行。文件格式如下:

11 -5 -4 -3 -2 -1 6 7 8 9 10 11
8 -33 -22 -11 44 55 66 77 88

创建数组后,我尝试调用我创建的合并方法,但我从 Netbeans 收到此错误:

'.class' 预期

意外的类型

必需:值

找到:类

我真的不知道这意味着什么,Netbeans 尝试通过创建其他类来修复它。 我所有的代码都在下面:

import java.io.*;
import java.util.*;

public class ArrayMerge
{

/**
 * @param args the command line arguments
 */
public static void main(String[] args)
{
   File inputDataFile = new File(args[0]);
   try
   {
       Scanner inputFile = new Scanner(inputDataFile);   
       Scanner keyboardin = new Scanner(System.in);
       int aSize = inputFile.nextInt();
       int a[] = new int[aSize];
       for (int i= 0 ; i<aSize; i++ )
           {
               a[i] = inputFile.nextInt();
           }
       int bSize = inputFile.nextInt();
       int b[] = new int[bSize];
       for (int j = 0; j < bSize; j++)
           {
               b[j] = inputFile.nextInt();
           }
       int c[] = ArrayMerge.merge(a, b);
       System.out.println(Arrays.toString(c));




   }
   catch(FileNotFoundException e)
   {
       System.err.println("FileNotFoundException: " + e.getMessage());
   }



}

public static int[] merge(int[] a, int[] b) 
{
            // merge 2 sorted arrays

            int[] c = new int[a.length + b.length];
            int i=0, j=0, k=0;

            while (i<a.length && j<b.length) {
                    c[k++] = (a[i]<b[j]? a[i++]: b[j++]);
            } // end while

            while (j<b.length) {
                    c[k++] = b[j++];
            } // end while

            while (i<a.length) {
                    c[k++] = a[i++];
            } // end while

            return c;
    } // end merge()

}

更新:我解决了自己的问题。我忘记了数组不是由它们的名称和括号调用的,而仅仅是变量名。意识到这一点后,我发现我必须将有错误的行移到 Try{} 块中。我更新了上面的代码以反映这些变化。

【问题讨论】:

    标签: java arrays netbeans


    【解决方案1】:

    您的merge() 方法在类外部声明。

    将类的右大括号从merge() 方法上方移到下方

    【讨论】:

    • 再次检查括号。 merge() 属于同一类。我弄乱了复制/粘贴到 StackOverflow 中的空白,因此当您查看它们时它们不会对齐,但如果您数数它们就会对齐。
    猜你喜欢
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 2011-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多