I am trying to create a while loop, but the compiler keeps saying I have an "illegal start of type." How do I fix this?
code:
class whileLoop
{
int p = 0;
while(p < 10)
{
System.out.println(p);
p++;
}
}
I am trying to create a while loop, but the compiler keeps saying I have an "illegal start of type." How do I fix this?
code:
class whileLoop
{
int p = 0;
while(p < 10)
{
System.out.println(p);
p++;
}
}
Put your code in a valid main method:
public static void main(String[] args) {
// code here
}
In Java, your code must go inside a method, constructor or initialization block; it cannot simply reside in the class body. When you "run" a program, the main method (as shown above) is invoked.
main method because we thought that the code you posted was all you had. If you already have a main method, put this code inside that same main method or some other method, depending on what you're actually trying to do.You need to put this in some method or initialization block.
in an initialization block, it means the code will execute every time an instance of the class is created
{
int p = 0;
while (p < 10) {
System.out.println(p);
p++;
}
}
in instance method, the code is executed whenever the method is invoked.
public void someMethod() {
int p = 0;
while (p < 10) {
System.out.println(p);
p++;
}
}
in main method.
public static void main(String[] args) {
int p = 0;
while (p < 10) {
System.out.println(p);
p++;
}
}
You can't just put arbitrary code directly into the body of a class. You need put it in a method (or an initializer block, a slightly more advanced topic), e.g.
class whileLoop
{
public static final void main (String[] args) {
int p = 0;
while(p < 10)
{
System.out.println(p);
p++;
}
}
}
The main method is a special method that is called when you invoke your class through the java command line. You can define any other methods that you need to, though. However, I highly suggest checking out a basic Java tutorial, e.g. http://docs.oracle.com/javase/tutorial/