Dana Vrajitoru
C101/I210 Computer Programming

C101/I210 Lab 9

Date: Wednesday, April 1, 2020.
Due date: Wednesday, April 8, 2020.

Objective: To write methods in Java.

Ex. 1. Real Number Methods

In this project we will input a real number from the user, then call a few functions with it.

Create a Java project in Eclipse and call it lab9. Create a class in this project called RealNumber and containing the main method. Write your name, course, semester, and homework number at the top as a comment. Add the code for the definition of a scanner.

a. Whole and Fractional Parts

Write a couple of methods to extract the whole and the fractional parts of a float number. They should take one parameter and return the different parts as float numbers too. The whole part can be obtained by casting the number as an integer. The fractional part is the difference between the number and its whole part. Here are the headers for these functions:

static float wholePart(float x)
static float fractPart(float x)

Add a test for these functions in the main. For that, declare a float variable, input its value form the user, then output the whole and fractional parts by calling the methods to compute them.

b. Round

Write a method taking one float parameter and one integer and rounding the first parameter to a number of digits specified by the second one. The header of the function should be

static float round(float x, float digits)

We have seen a similar example where the number of digits was 2 and where we truncated the number keeping two digits. Here we'll be doing the same thing, but for an arbitrary number of digits. We also want to round the number and not truncate it. For example, round(2.157, 2) should return 1.15, which round(4.211, 2) should return 2.11.

For this function, we will start by multiplying the number by 10 for a number of times equal to the number of digits we want. Then we'll add 0.5 to the number and cast it as an integer. Finally, we'll divide by the number by 10 for a number of times equal to the number of digits.

Add a test for this function in the main. Ask the user for the number of digits, then call the function and output the result.

c. Run Again

In the main, add a do loop that asks the user to enter another number to test until they enter a 0.

Add an output statement after the loop saying goodbye to the user, so that they know that program has ended.

Run the program to make sure everything works correctly.

Turn in:

Upload RealNumber.java to Canvas in Assignments - Homework 9, or wait until you have completed the homework to upload both files at the same time.