Coding Exercise 1: Speed Converter

2021. 2. 18. 16:44Java programming

Speed Converter

1. Write a method called toMilesPerHour that has 1 parameter of type double with the name kilometersPerHour. This method needs to return the rounded value of the calculation of type long.

If the parameter kilometersPerHour is less than 0, the method toMilesPerHour neds to return -1 to indicate an invalid value.

Otherwise, if it is positive, calculate the value of miles per hour, round it and return it.

 

2. Write another method called printConversion with 1 parameter of type double with the name kilometersPerHour.

This method should not return anything (void) and it needs to calculate milesPerHour from th kilometersPerHour parameter.

Then it needs to print a message in the format "XX km/h = YY mi/h".

XX represents the original value kilometersPerHour.

YY represents the rounded milesPerHour from the kilometersPerHour parameter.

If the parameter kilometersPerHour is < 0 then print the text "Invalid Value".

 

public class SpeedConverter {

    public static long toMilesPerHour (double kilometersPerHour){
        if (kilometersPerHour < 0){
            return -1;
        }

        return Math.round(kilometersPerHour / 1.609);

    }

    public static void printConversion(double kilometersPerHour) {
        if (kilometersPerHour < 0){
            System.out.println("Invalid Value");
        } else {
            long milesPerHour = toMilesPerHour(kilometersPerHour);
            System.out.println(kilometersPerHour +
                    " km/h = " + milesPerHour +
                    " mi/h ");
        }
    }
}

Very first codeing exercise on Java was quite excited yet daunting.

If, else 구문을 사용하는 것이 아직 서툴지만 해냈다!!!

You'd never know how thrilling it was to get the 1st exercise done on checking comment saying "Well done, your solution is correct!".

Sorta understand why those involved in IT programming like developers as such keep doing this. Hope try to keep this feeling in my mind for ages.

'Java programming' 카테고리의 다른 글

Coding Exercise 3: Barking Dog  (0) 2021.02.18
Coding Exercise 2: MegaBytes Converter  (0) 2021.02.18
Operators, Operands and Expressions  (0) 2021.02.17
float and double Primitive Types  (0) 2021.02.17
Hello World! - 미약한 시작  (0) 2021.02.17