Пользовательский ввод для шестнадцатеричного числа - PullRequest
0 голосов
/ 01 марта 2020

Добрый вечер всем, я пишу программу для танца робота-зяблика.
Танец будет состоять из движений вперед и назад.
Если пользователь вводит шестнадцатеричное число из двух ди git робот-зяблик должен двигаться вперед и назад в течение 0,5 секунды, а если пользователь вводит число di git, он должен двигаться в течение одной секунды.
Выходные данные будут в двоичных числах, означающих, что зяблик будет читать двоичный и переместиться соответственно к двоичному выходу (например, если двоичное число равно «0», зяблик должен двигаться назад и наоборот).
Кроме того, цвет светодиода будет создаваться путем смешивания различных значений красного , зеленый и синий. Значение красного цвета должно быть десятичным эквивалентом заданного шестнадцатеричного числа; значение зеленого должно быть равно остатку десятичного эквивалента при делении на 80, умноженном на 3; значение синего должно быть равно наибольшему из двух (красного или зеленого) значений.
Программа должна начать с запроса ввода данных пользователем (между 30 - AD в шестнадцатеричном формате), а затем преобразовать код в восьмеричный и двоичный эквиваленты. Если это что-то выше или ниже, программа должна предложить пользователю ввести числа в диапазоне.

Мой шестнадцатеричный - восьмеричный код преобразования:

public class HEXOCT {
    public static int hex_to_decimal(String s) {
        String digits = "0123456789ABCDEF";
        s = s.toUpperCase();
        int val = 0;
        for (int i = 0; i < s.length(); i++) {  //Variables assigned
            char c = s.charAt(i);
            int d = digits.indexOf(c);
            val = 16 * val + d;
        }
        return val;
    }
    //Start of conversion method
    public static void main(String[] args) {
        String hexdec_num;
        int Dec_num, i=1, j;
        int Octal_num[] = new int[100];
        Scanner in = new Scanner(System.in);

        System.out.print("Please Input a Hexadecimal Number (30 - AD): ");

        System.out.print("\n");
        hexdec_num = in.nextLine();

        //Hexadecimal to Decimal conversion

        Dec_num = hex_to_decimal(hexdec_num);

        //Decimal to Octal conversion

        while (Dec_num != 0){
            Octal_num[i++] = Dec_num%8;
            Dec_num = Dec_num/8;
        }
        System.out.print("The Octal equivalent is:");
        System.out.print("\n");
        for(j=i-1; j>0; j--)
        {
            System.out.print(Octal_num[j]);
        }
        System.out.print("\n");



    }
    //End of conversion method
}

Main method:

public class AS {
    private static final int S = 0;
    private static Object myFinch;
    private static int durofexec;                       
    static Finch myfinch = new Finch();
    public static void forward()
    {
        myfinch.setWheelVelocities(255,255,10000);
    }
    static long Start = System.currentTimeMillis();
    static int j, l, r;

    public static void main(final String[] args) throws InterruptedException {
        Welcome();
        UserInput();
        ProgramStart();
        //NumberConversion();
        LED();
        End();
        Timer();
    }
    private static void Welcome() {
        System.out.println("");  //Welcome message
        System.out.println("Hello welcome to Dancing Finch");
        myfinch.setLED(Color.white);
        System.out.println("");
    }
    private static void UserInput() {
        //User Input
        Scanner myUI = new Scanner(System.in);  //New Scanner Object
        String UserInput;

        //Enter Hexadecimal number
        System.out.println("Please enter a Hexadecimal Number for the Dance to launch (e.g. F or 1F)");
        UserInput = myUI.nextLine();

        System.out.println("User Input is: " + UserInput);  //Output = Whatever number the user has entered
    }
    //DanceStart
    public static void ProgramStart() throws InterruptedException {
        System.out.println("The application is ready to start in ...");     //Dance Countdown (3,2,1, Dance Start)
        int P = 3;
        while (P > 0) {
            System.out.print(P + " ");
            P = P - 1;
            TimeUnit.SECONDS.sleep(1);

            myfinch.buzz(13000, 500);
        }
    }
    public static void LED() {
        //Initiating Finch Object
        Finch myFinch = new Finch();
        Random rand = new Random();

        float R = rand.nextFloat();     //Random Color for Finch
        float G = rand.nextFloat();      //This class takes on 3 floats ranging from 0 - 1
        float B = rand.nextFloat();

        Color randomColor = new Color(R, G, B);
        myFinch.setWheelVelocities(230,230,3000); //First Speed  //Finch Test

    }

    /*private static int NumberConversion() {
        String digits = "0123456789ABCDEF";
        S = S.toUpperCase();
        int val = 0;
        for (int i = 0; i < S.length(); i++) {  //Variables assigned
            char c = S.charAt(i);
            int d = digits.indexOf(c);
            val = 16 * val + d;
        }
        return val;
    }
    //Start of conversion method
    {
        String hexdec_num;
        int Dec_num, i = 1, j;
        int Octal_num[] = new int[100];
        Scanner in = new Scanner(System.in);
        System.out.print("Please Input a Hexadecimal Number: ");
        System.out.print("\n");
        hexdec_num = in.nextLine();

        //Hexadecimal to Decimal conversion

        Dec_num = hex_to_decimal(hexdec_num);

        //Decimal to Octal conversion

        while (Dec_num != 0) {
            Octal_num[i++] = Dec_num % 8;
            Dec_num = Dec_num / 8;
        }
        System.out.print("The equivalent of Octal number is:");
        System.out.print("\n");
        for (j = i - 1; j > 0; j--) {
            System.out.print(Octal_num[j]);
        }
        System.out.print("\n");
    */
    private static void End() {
        while (j == 255); {
            myfinch.setWheelVelocities(0, 0);
            Scanner userInput = new Scanner(System.in);  //Creating Scanner Object
            System.out.println("Would you like to continue the Dance Routine?");
            String input = userInput.nextLine();  //Reviewing User Input
            System.out.println("Yes or No: " + input);  //User Output
            if (input == "Yes")
                System.out.println("Restart Dance Routine");
            new Finch();
            if (input.equals("No"))
                System.out.println("The program will now terminate");
                myfinch.quit();
            System.out.println("Program Terminated");
        }
    }
    private static void Timer() {
        long finish = System.currentTimeMillis();
        myfinch.buzz(5000, 500);
        long start = 0;
        long timelapsed = finish - start;
        durofexec = (int) (timelapsed / 1000);

    }
}

Если кто-то может намекнуть я был бы очень признателен, и кто-то мог бы сказать мне, как мне следует вводить данные, потому что я не слишком уверен.

Заранее большое спасибо!

...