简体   繁体   中英

Error: main class not found

When compiling the program I get the error as

Could not find the main class: Solution. Program will exit.

The program is:

import java.util.*;

public class Solution{
   public static long[] factors(long a){
     long[] b;
     b=new long[50];
     int count=0;
     for(long i=1L;i<=a/2;i++)
       if(a%i==0) b[count++]=i;
     return b;
   }

   public static void main(String[] args) {

        Scanner in=new Scanner(System.in);

        int N=in.nextInt();
        long K=in.nextInt();
        long[] fact=factors(K);
        l1:
        for(int i=0;i<N;i++)
        {
            long num=in.nextInt();
            for(int j=0;j<fact.length;j++)
                if(num%fact[j]==0 && fact[j]!=1) {fact[j]=1;continue l1;}

        }
        int result=0;
        for(int i=0;i<fact.length;i++)
            if(fact[i]!=1) ++result;
        System.out.println(result);
    }
}

This will not compile because the main method is not belong to a class. Put the main method inside the class to solve the problem. And your code is throwing arithmetic exception divide by zero should be fixed like that.

for(int j=0;j<fact.length;j++)
  if (fact[j] != 0)
    if(num%fact[j]==0 && fact[j]!=1) {
      fact[j]=1;continue l1;
    }

Your code is correct - it compiles and runs fine on ideone ( link ).

The problem that you are seeing has to do with the way you are compiling and running your application. At the command line prompt, do this:

javac Solution.java

This will produce Solution.class file. Run it as follows:

java Solution

At this point the running program will be reading the input and producing the output on the console. It will throw exceptions if the expected input is not available because you call nextInt without checking for hasInt , but it will produce a result if you give it the input that it expects.

When compiling the program i get the error as

Could not find the main class: Solution. Program will exit.

Compiling doesn't require any main class: you can compile helper classes independently. So the problem is apparently that you're trying to run a class that you haven't compiled yet. For example, if you're using the command-line tools, then you're most likely running java when you mean to be running javac .

There are NO independent functions in the Java programming model; every procedure/function must be a method on some class, including the static void main method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM