import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Turtle t = new Turtle();
while (true){
System.out.println("Enter a command:");
String command = scan.nextLine();
command.toLowerCase();
//moves the turtle forward
if (command.equals("forward"))
{
//further prompts the user for the number of steps
System.out.print("Number of steps: ");
int i = scan.nextInt();
t.forward(i);
}
else if (command.equals("right")){
System.out.print("Number of degrees: ");
double d = scan.nextDouble();
t.right(d);
}
else if (command.equals("left")){
System.out.print("Number of degrees: ");
double d = scan.nextDouble();
t.left(d);
}
//else if (command.equals("setpencolor")){
//System.out.print("New color: ");
//String c = scan.nextLine();
//t.setPenColor(c);
// }
else if (command.equals("quit")){
break;
}
else{
System.out.println("That is an invalid command.");
}
}
}
}
public class Turtle {
public final int RADIUS = 5;
private double xCoord;
private double yCoord;
private double direction;
private boolean penDown;
public Turtle(){
int canvasSize = 400;
StdDraw.setCanvasSize(canvasSize, canvasSize);
StdDraw.setXscale(0, canvasSize);
StdDraw.setYscale(0, canvasSize);
xCoord = canvasSize/2;
yCoord = canvasSize/2;
direction = 90;
StdDraw.setPenColor(StdDraw.BLACK);
penDown = false;
StdDraw.filledCircle(xCoord, yCoord, RADIUS);
}
//converts degrees to radians
public double convertToRadians(double degree){
return (degree*Math.PI)/180;
}
public void forward(int i){
double stepSize = 20;
//draws a turtle for each step
for (int j = 0; j < i; j++)
{
//draws a line connecting the turtles if penDown is true
if (penDown==true)
StdDraw.line(xCoord, yCoord, (j*stepSize*Math.cos(convertToRadians(direction))+xCoord), (j*stepSize*Math.sin(convertToRadians(direction))+yCoord));
xCoord = j*stepSize*Math.cos(convertToRadians(direction)+xCoord);
yCoord = j*stepSize*Math.sin(convertToRadians(direction)+yCoord);
StdDraw.filledCircle(xCoord, yCoord, RADIUS);
}
}
//turns the turtle a degrees to the right
public void right(double a){
direction -= a;
}
//turns the turtle a degrees to the left
public void left(double a){
direction += a;
}
//makes it so a line will not be drawn between turtles
public void penUp(){
penDown = false;
}
//makes it so a line will be drawn between turtles
public void penDown(){
penDown = true;
}
これは私が持っている私のコードであると私は一つのことにこだわっています。
Enter a command:
left
Number of degrees:
しかし、私は、任意の数で入力すると、それはちょうど私が私が何を知っていない
Enter a command: That is an invalid command.
が付属しています:あなたはそれがユーザーの入力を要求コードを再生すると、これは、それがどのようになるでそれを聴かせる程度をタイプするとされています。
サイドノート:: 'command.toLowerCase私は、この例のコードを簡素化するためにタートルオブジェクトに
main()
を折り畳まれてきました(); '単に' String'を返し、 'command'自体は変更しません。代わりに 'command = commandLowCase();'を使用してください。 – Jyrしかし、ユーザーからの入力を求めているときは、コマンドを入力すると、人は "left"と入力し、次にドットを何度も動かすかどうかを尋ねます。これは「次数」のようなもので、「90」と入力すると「これは無効なコマンドです」というメッセージが表示されます –
これは 'nextLine()'を使用しているためです。 – Jyr