JAVA程序練習---小車行走距離

LRUD分別表示左右上下,後面跟行駛距離,計算到原點的距離?

package 測試包;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class 小車行駛距離簡化 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("請輸入字符串如:LL10UU20L20U20U");
        String s = sc.nextLine();
        sc.close();
        Pattern p = Pattern.compile("[A-z][0-9]+");//正則表達式匹配有效的命令
        Matcher m = p.matcher(s);
        ArrayList<String> al = new ArrayList<String>();
        while (m.find()) {
            al.add(m.group());
        }
        int x = 0;
        int y = 0;
        for (int i = 0; i < al.size(); i++) {
            switch (al.get(i).charAt(0)) {
            case 'L':
                x = x
                        - Integer.parseInt(al.get(i).substring(1,
                                al.get(i).length()));
                break;
            case 'R':
                x = x
                        + Integer.parseInt(al.get(i).substring(1,
                                al.get(i).length()));
                break;
            case 'U':
                y = y
                        - Integer.parseInt(al.get(i).substring(1,
                                al.get(i).length()));
                break;
            case 'D':
                y = y
                        - Integer.parseInt(al.get(i).substring(1,
                                al.get(i).length()));
                break;
            default:
                break;
            }
        }
        System.out.println("有效的行駛指令是:" + al);
        System.out.println("小車的停止位置是:[" + x + "," + y + "]");
        System.out.println("行駛的距離是:"
                + Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)));
        // LL10UU20L20U20U
    }
}

輸入:
LL10UU20L20U20U
輸出:
請輸入字符串如:LL10UU20L20U20U
LL10UU20L20U20U
有效的行駛指令是:[L10, U20, L20, U20]
小車的停止位置是:[-30,-40]
行駛的距離是:50.0

發佈了41 篇原創文章 · 獲贊 9 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章