【编程题】(满分18分)    某少年宫引进了一批机器人小车。可以接受预先输入的指令,按指令行动。小车的基本动作很简单,只有3种:左转(记为L),右转(记为R),向前走若干厘米(直接记数字)。    例如,我们可以对小车输入如下的指令:    15L10R5LRR10R20    则,小车先直行15厘米,左转,再走10厘米,再右转,...    不难看出,对于此指令串,小车又回到了出发地。    你的任务是:编写程序,由用户输入指令,程序输出每条指令执行后小车位置与指令执行前小车位置的直线距离。【输入、输出格式要求】    用户先输入一个整数n(n<100),表示接下来将有n条指令。    接下来输入n条指令。每条指令只由L、R和数字组成(数字是0~100之间的整数)    每条指令的长度不超过256个字符。    程序则输出n行结果。    每条结果表示小车执行相应的指令前后位置的直线距离。要求四舍五入到小数后2位。    例如:用户输入:
5
L100R50R10
3LLL5RR4L12
LL
100R
5L5L5L5    则程序输出:
102.96
9.06
0.00
100.00
0.00
【注意】    请仔细调试!您的程序只有能运行出正确结果的时候才有机会得分!
    
    请把所有类写在同一个文件中,调试好后,存入与【考生文件夹】下对应题号的“解答.txt”中即可。
    
    相关的工程文件不要拷入。
    
    请不要使用package语句。
    
    源程序中只能出现JDK1.5中允许的语法或调用。不能使用1.6或更高版本。 

解决方案 »

  1.   

    package ban.com;import java.text.DecimalFormat;
    import java.util.Scanner;public class test {
    public static int direction ;
    public static int X[]={1,0,-1,0};
    public static int Y[]={0,-1,0,1};
    public static int x,y;
    public static void  GetDirection(String d){
    if (d.equals("L")){
    direction = (direction +1)%4;
    }else if (d.equals("R")){
    direction = (direction +3)%4;
    }

    }
    public static void CountXY(int d){
    x += X[direction]*d;
    y += Y[direction]*d;
    }
    public static void getAnswer(String s){
    int i,j,k;
    String ss = "";
    k = s.length();
    for(i = 0;i<k;i++){
    char c = s.charAt(i);
    if (c >= '0' && c <= '9'){
    ss += c;
    }else {
    if (!ss.equals("")){
    CountXY(Integer.valueOf(ss));
    ss = "";
    }
    GetDirection(c+"");
    }
    }
    if (!ss.equals("")){
    CountXY(Integer.valueOf(ss));
    ss = "";
    }

    }
    public static void main(String[] args) {
    String s;
    int n;
    Scanner sc = new Scanner(System.in);
    DecimalFormat dg=new DecimalFormat("0.00"); //保留两位小数
    n = sc.nextInt();
    while( n > 0){
    direction = 0;
    x = 0;
    y = 0;
    s = sc.next();
    getAnswer(s);
    System.out.println(dg.format(Math.sqrt(x*x+y*y)));
    n --;
    }
    }
    }
      

  2.   


    import java.text.DecimalFormat;
    import java.util.ArrayList;
    import java.util.Scanner;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;public class Car
    {
        static final int NORTH = 0;
        static final int SOUTH = 1;
        static final int WEST = 2;
        static final int EAST = 3;
        static final int LEFT = 2;
        static final int RIGHT = 3;
        static final DecimalFormat DF = new DecimalFormat("0.00");    public int getDirection(int direction, int action)
        {
    if (direction == NORTH || direction == SOUTH)
    {
        return direction ^ action;
    }
    else
    {
        return direction ^ action ^ 1;
    }    }    public void execute(String command)
        {
    String regex = "[L|R]{0,1}[0-9]*";
    Pattern pt = Pattern.compile(regex);
    Matcher mather = pt.matcher(command);
    ArrayList<String> ar = new ArrayList<String>();
    while (mather.find())
    {
        String s = mather.group();
        ar.add(s);
    }
    // 下面初始原点坐标与方向
    int direction = NORTH;
    int x = 0;
    int y = 0;
    for (int i = 0; i < ar.size(); i++)
    {
        String order = ar.get(i);
        int len = order.length();
        if (len > 0)
        {
    char action = order.charAt(0);
    int move = 0; if (action == 'L')
    {
        direction = getDirection(direction, LEFT);
        if (len > 1)
        {
    move = Integer.parseInt(order.substring(1));
        }
    }
    else if (action == 'R')
    {
        direction = getDirection(direction, RIGHT);
        if (len > 1)
        {
    move = Integer.parseInt(order.substring(1));
        }
    }
    else
    {
        move = Integer.parseInt(order);
    }
    switch (direction)
    {
    case NORTH:
        y += move;
        break;
    case SOUTH:
        y -= move;
        break;
    case WEST:
        x -= move;
        break;
    case EAST:
        x += move;
        break;
    }     }
    }
    double d = Math.sqrt(x * x + y * y);
    System.out.println("移动直线距离为: " + DF.format(d));
        }    public static void main(String[] args)
        {
    Scanner sc = new Scanner(System.in);
    int count = sc.nextInt();
    if (count <= 0 || count > 100)
    {
        System.out.println("次数超出限制");
        return;
    }
    ArrayList<String> ar = new ArrayList<String>();
    while (count > 0)
    {
        String command = sc.next();
        ar.add(command);
        count--;
    }
    for (String command : ar)
    {
        Car c = new Car();
        c.execute(command.trim().toUpperCase());
    }
        }
    }
      

  3.   

    哦  ~~~没看清楚   您的做法非常好  比我写的强  我当时是定义了一个变量flag来表示方向的,和“L”"R"作为参数确定下一时刻的方向,next(int flag,String dir)...这样子弄得,但我觉得你那个更好!
      

  4.   

    这道题没难度啊
    public class MovingProcessor {
        //所谓四面八方,把方向控制好就行了
        //以2维坐标为参考,前为上(y坐标增加),右为右(x坐标增加),后为下(y坐标减少),左为左(x坐标减少)
        private static final int[][] MOVING_DIR = {{0,1}, {1,0}, {0,-1}, {-1,0}};    protected int dir  = 0; //用于控制方向
        protected double x = 0; //用于控制x坐标
        protected double y = 0; //用于控制y坐标
        private boolean isolating = true; //是否是独立的命令(用于扩展,此题可忽略),因为是每次独立计算距离(即后面的距离不累加前面的距离),所以本题设为独立命令
        //private boolean realTime = false;//是否是实时处理(用于扩展,此题忽略)    public MovingProcessor() {}
        public MovingProcessor(boolean isolating) {
            this.isolating = isolating; 
        }    public void reset() { //处理器重置
            dir = 0;
            x   = 0;
            y   = 0; 
        }    public double execute(String cmd) throws Exception { //执行指令,支持小数距离(题目给的是整数距离,这里扩展支持小数距离)
            if (isolating) reset();        int dec = 0; //小数标志
            double num = 0, times = 0;
            for (char c : cmd.toCharArray()) { //按字符遍历指令
                if (c == 'L') { //遇到左转L指令
                    if (num > 0) {//判断是否L指令前是否存在移动距离,如果存在,则先移动
                        move(num); //移动距离
                        num = 0; 
                        dec = 0;
                    }
                    changeDir(c); //改变方向
                } else if (c == 'R') { //遇到R右转指令
                    if (num > 0) {
                        move(num);
                        num = 0;
                        dec = 0;
                    }
                    changeDir(c);
                } else if (c>='0' && c<='9') { //遇到数字累加数字
                    if (dec == 0) { //无小数的时候
                        num = num*10 + (c-'0');
                    } else { //有小数的时候
                        num += (c-'0')/times;
                        times *= 10;
                    }
                } else if (c == '.') { //遇到小数点
                    if (dec > 0) { //非法小数点则抛出异常
                        throw new Exception(String.format("Error Command[%s].", cmd));
                    }
                    dec = 1;
                    times = 10;
                } else { //非法字符则抛出异常
                    throw new Exception(String.format("Error Command[%s].", cmd));
                }
            }        if (num > 0) { //如果有移动距离就移动
                move(num);
            }        return Math.sqrt(x*x + y*y); //返回移动的距离
        }    protected void changeDir(char dir) { //改变方向
            this.dir += (dir=='L' ? -1 : (dir=='R' ? 1 : 0));
        }    protected void move(double value) { //移动距离
            dir %= 4;
            dir += (dir < 0) ? 4 : 0;
            x += value * MOVING_DIR[dir][0];
            y += value * MOVING_DIR[dir][1];
        }    public static void main(String[] args) {
            String[] cmds = getCmds();
            MovingProcessor mp = new MovingProcessor();
            System.out.println("Execute Result:");
            for (String cmd : cmds) {
                try {
                    System.out.printf("%.2f\n", mp.execute(cmd));
                } catch (Throwable e) {
                    e.printStackTrace();
                    //break; //skip, ignore, cancel, so on...
                }
            }
        }    public static String[] getCmds() {
            String[] cmds;
            int count = 0;
            Scanner sc = new Scanner(System.in);
            try {
                System.out.println("User Input:");
                count = Integer.valueOf(sc.nextLine()).intValue();
            } catch (Throwable e) {
                e.printStackTrace();
                System.exit(-1);
            }        cmds = new String[count];
            for (count=0; count<cmds.length; count++) {
                cmds[count] = sc.nextLine();
            }        return cmds;
        }
    }
      

  5.   

    package splite;public class Rbot {
    public double test(String command){
    int x=0;
    int y=0;
    int b=0;
    int t=0;
    command=" "+command;
    String[] direction={"x","y","-x","-y"};
    String[] commands=command.split("\\d+");
    for(int i=0;i<commands.length;i++){
    commands[i]=commands[i].trim();
    System.out.println(commands[i]);
    }
    String[] num=command.split("[LR]+");
    if(num.length>commands.length){
    b=1;
    }
    if(commands.length>num.length){
    t=1;
    }
    System.out.println(t);
    System.out.println(num.length+"\t"+commands.length);
    for(int i=0;i<num.length;i++){
    if(num[i].trim().length()<1){
    num[i]="0";
    }
    num[i]=num[i].trim();
    }
    int d=0; 
    for(int i=0;i<commands.length-t;i++){
    for(int m=0;m<commands[i].length();m++){
    char c=commands[i].charAt(m);
    if(c=='L'){
    d+=1;
    if(d==4){
    d=0;
    }
    }else{
    d-=1;
    if(d==-1){
    d=3;
    }
    }
    }
    System.out.println(direction[d]);
    if(direction[d].equals("x")){
    x+=Integer.parseInt(num[i+b]);
    }else if(direction[d].equals("y")){
    y+=Integer.parseInt(num[i+b]);
    }else if(direction[d].equals("-x")){
    x-=Integer.parseInt(num[i+b]);
    }else{
    y-=Integer.parseInt(num[i+b]);
    }
    }
    System.out.println(x+"\t"+y);
    double l=Math.sqrt(x*x+y*y);
    return l;
    }
    public static void main(String[] args){
    Rbot r=new Rbot();
    System.out.println(r.test("5L5L5L5"));
    }

    }
    做了一个小时  勉强能测试过那五组数据  但不是完全按照那个输入次数的要求做的
      

  6.   

    public static double getDistance(String code)
    {
    String mCode = code.toUpperCase().trim();
    double distance; // only direction
    Pattern p = Pattern.compile("[0-9]+");
    Matcher m = p.matcher(mCode);
    ArrayList<String> alist = new ArrayList<String>();
    while (m.find())
    {
    alist.add(m.group());
    } // record x and y distance from (0,0)
    double x = 0;
    double y = 0;
    Testing t = new Testing();
    // init direction as whatever you like
    Direct d = t.new Direct(0, 1);
    if (alist.size() > 0)
    {
    mCode = mCode
    .substring(mCode.indexOf(alist.get(0)), mCode.length());
    Iterator<String> it = alist.iterator();
    while (it.hasNext())
    {
    // handle distance
    String dis = it.next();
    int disInt = Integer.parseInt(dis);
    x += d.dx * disInt;
    y += d.dy * disInt; // handle direction change
    if ((mCode.length() - dis.length()) > 0)
    {
    mCode = mCode.substring(dis.length(), mCode.length());
    while (mCode.length() > 0
    && (mCode.startsWith("L") || mCode.startsWith("R")))
    {
    if (mCode.charAt(0) == 'L')
    {
    d.turnLeft();
    }
    else if (mCode.charAt(0) == 'R')
    {
    d.turnRight();
    }
    mCode = mCode.substring(1, mCode.length());
    }
    }
    }
    }
    else
    {
    return 0.0; // only direction
    } distance = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
    return distance;
    } /**
     * Direction class
     **/
    class Direct
    {
    public int dx; public int dy; public Direct(int dx, int dy)
    {
    this.dx = dx;
    this.dy = dy;
    } public void turnLeft()
    {
    if (dx == 0 && dy == 1)
    {
    dx = -1;
    dy = 0;
    }
    else if (dx == -1 && dy == 0)
    {
    dx = 0;
    dy = -1;
    }
    else if (dx == 0 && dy == -1)
    {
    dx = 1;
    dy = 0;
    }
    else if (dx == 1 && dy == 0)
    {
    dx = 0;
    dy = 1;
    }
    } public void turnRight()
    {
    if (dx == 0 && dy == 1)
    {
    dx = 1;
    dy = 0;
    }
    else if (dx == -1 && dy == 0)
    {
    dx = 0;
    dy = 1;
    }
    else if (dx == 0 && dy == -1)
    {
    dx = -1;
    dy = 0;
    }
    else if (dx == 1 && dy == 0)
    {
    dx = 0;
    dy = -1;
    }
    }
    }
    思路是提取出纯数字的距离,不断累加,两次累加之间处理下方向的变化。
    好像有点长...
      

  7.   

    public class Car extends Vehicle{
    protected int speed; private int direction;
    private int x;
    private int y;

    public Car(){
    reset();
    }

    public void reset(){
    this.direction = 0;
    this.x = 0;
    this.y = 0;
    }
    public void turn(String sDirction){
    if (sDirction.compareTo("R") == 0){
    this.direction = (this.direction+1)%4;
    }
    else if (sDirction.compareTo("L") == 0){
    this.direction = (this.direction+4-1)%4;
    }
    }

    public void walk(int sDistance){
    if (this.direction == 0){
    this.y += sDistance;
    }
    else if (this.direction == 2){
    this.y -= sDistance;
    }
    else if (this.direction == 1){
    this.x += sDistance;
    }
    else if (this.direction == 3){
    this.x -= sDistance;
    }
    }

    public double range(){
    return Math.sqrt(this.x*this.x + this.y*this.y);
    }

    public  void execute(String cmds){
    List<String> subCmds = new ArrayList<String>();


    int lastPos = 0;
    while (true)
    {
    int sLPos = cmds.indexOf("R", lastPos);
    int sRPos = cmds.indexOf("L", lastPos);

    int sPos = -1;
    if (sLPos == -1){
    sPos = sRPos;
    }
    else if (sRPos == -1)
    {
    sPos = sLPos;
    }
    else
    {
    sPos = sLPos > sRPos ? sRPos : sLPos;
    }

    if (sPos < 0)
    {
    if (!cmds.substring(lastPos).isEmpty()){
    subCmds.add(cmds.substring(lastPos));
    }
    break;
    }
    String distance = cmds.substring(lastPos, sPos);
    String cmd = cmds.substring(sPos, sPos+1);
    if (!distance.isEmpty()){
    subCmds.add(distance);
    }
    subCmds.add(cmd);
    lastPos = sPos+1;
    }

    for (String s : subCmds){
    if (s.compareTo("R") == 0 || s.compareTo("L") == 0){
    turn(s);
    }
    else{
    walk(Integer.valueOf(s));
    }
    }
    }

    public static void main(String[] args){
    Car c = new Car();
    c.execute("L100R50R10");
    System.out.println(c.range());
    c.reset();
    c.execute("3LLL5RR4L12");
    System.out.println(c.range());
    c.reset();
    c.execute("LL");
    System.out.println(c.range());
    c.reset();
    c.execute("100R");
    System.out.println(c.range());
    c.reset();
    c.execute("5L5L5L5");
    System.out.println(c.range());
    }
    }
    写了一个类,没有按要求输入输出,结果应该是对的。
    基本思想定义了四个方向0-y+ 2-y- 1-x+ 3-x-
    初始正前方,右转+1,左转-1,最后求得x,y坐标