YTU Java语言程序设计教程第二章课后题

第二题:封装一个Runner,按照以下步骤写出Java代码

import java.util.Scanner;

public class Runner {
    static double miles;
    static double KILOMETER_PRE_MILE = 1.557;

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        double kilometer = s.nextDouble();
        run(kilometer);

    }

    public static void run(double kilometer) {
        miles = kilometer * KILOMETER_PRE_MILE;
        System.out.println(miles);
    }


}

第九题:封装一个类MyHanoi,3根柱子和3个盘子的汉诺塔

为了体现面向对象,特意建立了两个Java,前者调用后者

汉诺塔中用到了递归思想

package Main;

import Method.Move;

public class MyHanoi {
    public static void main(String[] args) {
        char A = 'A', B = 'B', C = 'C';
        Move mo = new Move();
        mo.move(A, B, C, 3);

    }


}
package Method;



public class Move {
    public static void move(char a, char b, char c, int n) {
        if (n == 1) {
            System.out.println(a + "->" + c);
        } else {
            move(a,c, b, n-1);
            System.out.println(a + "->" + c);
            move(b,a,c,n-1);

        }

    }
}


 第十题

封装一个类NumberChange,将十进制转换为十六进制

package Main;


import Method.Change;

public class NumberChange {
    public static void main(String[] args){
        double num=12.9;
        Change a=new Change();
        a.change(num);
    }


}

package Method;

public class Change {
    public static void change(double n) {
        double new_n = 0;
        int size = 500;
        int[] t = new int[size];
        int temp = 0;
        int i = 0;
        int first = 0;
        char[] number = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

        int n_int = (int) n;
        double n_point = n - (n_int);
        do {            //22
            temp = n_int / 16;   //1
            t[i] = n_int % 16;   //6      t[0]=6,t[1]=1
            i++;             //1

        } while (temp > 15);
        t[i] = temp;


        for (; i >= 0; i--) {
            if (number[t[i]] != '0')
                System.out.print(number[t[i]]);
        }
        System.out.print('.');
        for (int j = 0; j < 8; j++) {
            first = (int) (n_point * 16);
            System.out.print(number[first]);
            n_point = (n_point * 16) - first;
        }


    }
}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值