Subclass not allowing world to run

2019-09-05 13:56发布

问题:

I am a beginner, taking a CompSci class in school. This chapter is making subclasses; however, The class is somehow causing the program to terminate. The world doesn't even appear, and there are no errors. (I am running Eclipse).

Here is my code:

package karel;
import kareltherobot.*;
public class Race implements Directions
{
public static void main(String args[]) {



class Car extends UrRobot
{   public Car(int street, int avenue, Direction direction, int beepers) 
    {super(5, 5, East, infinity);
    }

    public void turnAround()
    {
        turnLeft();
        turnLeft();
    }

    public void turnRight()
    {   
        turnLeft();
        turnLeft();
        turnLeft();
    }
}
    {   
        World.setVisible(true);
        World.showSpeedControl(true);
    }
        {
            Car kar = (Car) new UrRobot(5, 5, East, infinity);
            kar.move();
            kar.turnLeft();
            kar.move();
            kar.turnAround();
            kar.move();
            kar.turnRight();

        }

}

}

Is there a way to get this program to not error to termination?

回答1:

You need to have code ran in the main function. Java finds and executes code in the classes main function. Try that, if it doesn't work, come back and repost.



回答2:

Try the following.

import kareltherobot.*;

public class Race implements Directions
{
    public Race(){
     }

public static void main(String args[]) {

class Car extends UrRobot
{   

public Car(int street, int avenue, Direction direction, int beepers)

{

    super(street, avenue, direction, beepers);
}

public void turnAround()

{
    super.turnLeft();
    super.turnLeft();
}
public void turnRight()
{           
    super.turnLeft();
    super.turnLeft();
    super.turnLeft();
}
}

World.setVisible(true);
World.showSpeedControl(true);    
Car kar = new Car(5, 5, East, 100);
kar.move();
kar.turnLeft();
kar.move();
kar.turnAround();
kar.move();
kar.turnRight();

}
}