【小练习】立方体旋转

题目要求:按顺序旋转立方体,输出旋转后的结果。

立方体的前后左右上下分别为3、4、1、2、5、6。F表示向前翻转、B表示向后翻转,L表示像左翻转,R表示向右翻转、C表示顺时针旋转、A表示逆时针旋转。

在不做任何操作的情况下,默认打印123456。现要求输入一定规则,要求输出一定结果(如:输入RAF,输出431256)。

源码如下:

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Square {

    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        String input="RAF";

        if(input == null || input.trim().length() ==0){
            System.out.println(-1);
            return;
        }

        if(!input.trim().matches("^[R|L|F|B|A|C]+$")){
            System.out.println(-1);
            return;
        }
        Square square = new Square();
        if(input.length()>0){
            for (String c : input.trim().split("")){
                Method method = Square.class.getMethod(c,null);
                method.invoke(square);
            }
        }
        square.print();
    }


    int front =3;
    int back =4;
    int left =1;
    int right =2;
    int up =5;
    int down =6;

    public void print(){
        System.out.println(String.format("%s%s%s%s%s%s", left, right, front, back, up, down));
    }

    //前翻
    public void F(){
        //交换前后上下四个面
        int tmp= up;
        up = back;
        back = down;
        down = front;
        front =tmp;
    }

    //后翻
    public void B(){
        //交换前后上下四个面
        int tmp= up;
        up = front;
        front = down;
        down = back;
        back =tmp;
    }

    //左翻
    public void L(){
        //交换上下左右四个面
        int tmp= up;
        up = right;
        right = down;
        down = left;
        left =tmp;
    }


    //右翻
    public void R(){
        //交换上下左右四个面
        int tmp= up;
        up = left;
        left = down;
        down = right;
        right =tmp;
    }

    //顺时针
    public void C(){
        //交换前后左右四个面
        int tmp= front;
        front = right;
        right = back;
        back = left;
        left =tmp;
    }

    //逆时针
    public void A(){
        //交换前后左右四个面
        int tmp= front;
        front = left;
        left = back;
        back = right;
        right =tmp;
    }
}
原文地址:https://www.cnblogs.com/aligege/p/12327250.html