Java编译错误:方法嵌套定义引发Illegal start of expression问题求助
Hey there, let's break down why you're hitting those errors on line 18—they stem from a basic Java syntax rule you might have overlooked!
The Root Cause
In Java, you cannot define a method inside another method (or inside a code block like a while loop). Your public boolean Ap(){} is nested directly inside the while loop within the main method, which violates Java's class structure rules. That's exactly why the compiler throws "illegal start of expression" and "; expected" errors—it doesn't recognize method definitions in that context.
How to Fix It
Move the Ap() method out of the main method and make it a direct member of the PrimeExample class. Also, since main is a static method, you'll need to mark Ap() as static too (unless you plan to create an instance of PrimeExample to call it).
Here's the corrected code structure:
import java.util.ArrayList; public class PrimeExample{ // Move Ap() to the class level as a static method public static boolean Ap(){ // Don't forget to add your actual logic here! // Right now it just returns false, which will make your while loop run forever return false; } public static void main(String args[]) { int i =0; int m=0; int flag=0; int k =10;//number of terms int d =210;// common difference int n=2;//it is the number to be checked m=n/2; ArrayList list = new ArrayList( ); int number=0; boolean b= false; while( Ap() == false) { d++; list.clear(); // No more method definition here! } } }
Key Notes to Remember
- Method Placement: Always define methods directly inside the class, never inside other methods or loops.
- Static vs Non-Static: Since
mainis static, any method called directly frommainmust also be static (or you need to instantiate the class first, likePrimeExample example = new PrimeExample(); example.Ap();). - Ap() Logic: Right now your
Ap()method just returnsfalse, which will make yourwhileloop run infinitely. Be sure to add the actual logic you need to determine when the loop should stop.
内容的提问来源于stack exchange,提问作者Leon H. Spence

