Home Articles

java中相同包中的多个公共main main方法[duplicate]

Asked
Viewed 1053 times
0

这个问题在这里已有答案:

**Can i have two or more public static void main(String args[]) method in diffrent classes but same package **

我是java和stackoverflow的新手 . 对于任何无知提前抱歉 .

我试图在同一个包中放置两个带有public static void main(String args [])方法的类,但是在编译其中一个类时出现了“无法找到或加载主类BinarySearch”的错误 .

所以我的问题是为什么我们不能在不同的类中声明两个main方法,因为在同一个名字的不同类中声明其他方法是有效的?

头等舱的代码

package geeksforgeeks;
class BinarySearch
{
// Returns index of x if it is present in arr[l..
// r], else return -1
int binarySearch(int arr[], int l, int r, int x)
{
    if (r>=l)
    {
        int mid = l + (r - l)/2;

        // If the element is present at the 
        // middle itself
        if (arr[mid] == x)
           return mid;

        // If element is smaller than mid, then 
        // it can only be present in left subarray
        if (arr[mid] > x)
           return binarySearch(arr, l, mid-1, x);

        // Else the element can only be present
        // in right subarray
        return binarySearch(arr, mid+1, r, x);
    }

    // We reach here when element is not present
    //  in array
    return -1;
}

// Driver method to test above
public static void main(String args[])
{
    BinarySearch ob = new BinarySearch();
    int arr[] = {2,3,4,10,40};
    int n = arr.length;
    int x = 10;
    int result = ob.binarySearch(arr,0,n-1,x);
    if (result == -1)
        System.out.println("Element not present");
    else
        System.out.println("Element found at index " + 
                                             result);
}
}

同一包中第二类的代码

package geeksforgeeks;

 import java.util.Scanner;

class LinearSearch{
  public static void main(String args[]){
  Scanner in = new Scanner(System.in);
  int [] a = new int[5];
  for(int i=0;i<5;i++)
    a[i]= in.nextInt();

   System.out.println("enter number to be found");
   int key = in.nextInt();

  for(int i=0;i<5;i++){
    if(a[i]==key){
    System.out.println("number is present");
    break;
  }
  if(i==4)
    System.out.println("number is not present");
}
 }
 }

并且终端输出是

C:\Users\ayush\Desktop\java\geeksforgeeks>javac BinarySearch.java

C:\Users\ayush\Desktop\java\geeksforgeeks>java BinarySearch
Error: Could not find or load main class BinarySearch

1 Answer

  • 2

    BinarySearchgeeksforgeeks 包中 . 要启动它,您当前的目录必须是 c:\Users\ayush\Desktop\java ,您必须使用命令行:

    C:\Users\ayush\Desktop\java>java geeksforgeeks.BinarySearch
    

    或者,您也可以在启动时指定类路径,而不是更改当前目录 .

Related