Hello其他程序员!我是Java初学者,我需要一些帮助。
我有一个程序,我希望使用名为“rule”的字符串中的预制指令来移动Turtle。我希望将该规则解析为if-else语句的可读格式。然后,if-else语句将读取已解析的“规则”中的每个字符,并使Turtle相应地移动到每个条件。
我遇到了程序的一些问题,它解析(我想是这样)并显示规则,但是没有来自乌龟的动作。我认为它与if-else语句有关。请帮忙!
import java.awt.*;
import java.util.Scanner;
class FractalEngine
{
World worldObj = new World();
Turtle m = new Turtle(200, 200, worldObj);
Scanner in = new Scanner(System.in);
FractalEngine()
{
//String rule = "F-F+F+F-FQ";
String rule = "F-F+F+F-F-F-F+F+F-F+F-F+F+F-F+F-F+F+F-F-F-F+F+F-FQ";
//String rule = "F-F+F+F-F-F-F+F+F-F+F-F+F+F-F+F-F+F+F-F-F-F+F+F-F-F-F+F+F-F-F-F+F+F-F+F-F+F+F-F+F-F+F+F-F-F-F+F+F-F+F-F+F+F-F-F-F+F+F-F+F-F+F+F-F+F-F+F+F-F-F-F+F+F-F+F-F+F+F-F-F-F+F+F-F+F-F+F+F-F+F-F+F+F-F-F-F+F+F-F-F-F+F+F-F-F-F+F+F-F+F-F+F+F-F+F-F+F+F-F-F-F+F+F-FQ";
m.setHeading(0);
Scanner scanner = new Scanner(rule);
System.out.println();
System.out.println("Fractal Rule: ");
System.out.println(scanner.nextLine());
System.out.println();
// it prints it to the terminal, but no Turtle movement. Am I using the right parsing method?
do
{
Scanner scanRule = new Scanner(rule);
scanRule.nextLine();
if(rule.equalsIgnoreCase("F"))
m.forward(25);
else if(rule.equals("-"))
m.turnLeft();
else if(rule.equals("+"))
m.turnRight();
else
rule = "Q";
}
while(!rule.equalsIgnoreCase("Q"));
System.out.println("Fractal construction terminated.");
}
}
public class FractalConstructor
{
public static void main(String[] args)
{
FractalEngine fe = new FractalEngine();
}
}
答案 0 :(得分:0)
我认为你有很多代码逻辑问题,你可以用代码下面改变你的do while循环
boolean done = false;
String line ;
while((line = scanner.nextLine()) != null && !done)
{
for (int i = 0; i< rule.length(); i++) {
if(rule.charAt(i) == 'F')
m.forward(25);
else if(rule.charAt(i) == '-')
m.turnLeft();
else if(rule.charAt(i) == '+' )
m.turnRight();
else{
done = true;
break;
}
}
}
答案 1 :(得分:0)
我尝试了那个脚本,它对我来说它打印每个动作取决于命令,所以我认为问题出在你的函数中我的意思是(m.forward(),m.turnRight()...)< / p>
public class Main {
public static void main(String[] args)
{
String rule = "F-F+F+F-F-F-F+F+F-F+F-F+F+F-F+F-F+F+F-F-F-F+F+F-FQ";
int i = 0 ;
char[] cmds = rule.toCharArray();
do
{
if(cmds[i] == 'F') {
System.out.println("Foward");
}
else if(cmds[i] == '-') {
System.out.println("Left");
}
else if(cmds[i] == '+') {
System.out.println("Right");
}
else // it's surely "Q"
break ;
i++ ;
}
while(true);
System.out.println("Fractal construction terminated.");
}
}