Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Problem Description The assignment is meant as an introduction to Java programming and is partially structured as a tutorial. To solve this assignment you will

Problem Description

The assignment is meant as an introduction to Java programming and is partially structured as a tutorial. To solve this assignment you

will have to make use of concepts we havent covered yet, so this document will briefly touch on the constructs you will need. Much

of this material will also be covered in the tutorials.

The objective of this assignment is to learn how to write a simple Java program that uses a simple text-based interface to communicate

with a user. Specifically this program, BaseConversion, will read in a text string representing a positive decimal integer and convert it

to a number in a user-specified base, e.g. an input of 255 would output FF if Base-16 were specified. Since println() only knows how

to render integers in decimal format, you will have to encode your output as a String so that it can be rendered by println(). Some

examples are shown below (which your program should replicate exactly).

Base conversion program; converts +ve integers to a target base.

Enter number to be converted and target base on separate lines following the prompts.

A blank entry for either input terminates the program.

Number > 42

Target base > 2

42 expressed in base 2 is 101010

Number > -42

Error! -42 does not correspond to a positive integer.

Number > aasssf

Error! aasssf does not correspond to a positive integer.

Number > 42

Target base > -4

The base must be between 2 and 16 inclusive.

Number > 42

Target base > 17

The base must be between 2 and 16 inclusive.

Number > 42

Target base > 16

42 expressed in base 16 is 2A

Number > 54271

Target base > 10

54271 expressed in base 10 is 54271

Number > 54271

1/92/9

Target base > 9

54271 expressed in base 9 is 82401

Number > 54271

Target base > 8

54271 expressed in base 8 is 151777

Number >

Program terminated.

Lets examine the examples to gain a better understanding of the program requirements. In the first case 42 and 2 are valid inputs a

positive integer to be converted and a base in the range of 2 to 16. The result is 101010 which is 42 in binary. In the next 2 examples

the input is negative and invalid respectively, so an error is signaled, and the program prompts for input again. The next two cases

correspond to a correct input with invalid base. The logic to keep reading until a correct base is input is a bit cumbersome (for where

we are now in the course), so our strategy is to abandon the current round and start over with a prompt for a new input. When both the

input and base are correctly entered, the program will produce the correct result.

Where to Start

Before even thinking about code, the first step is to breakdown the problem, e.g., by writing a pseudo-code description of the process:

public void run() {

Identify program

Give user instructions

Repeat until blank input

Read character string corresponding to number to be converted

If the string is blank

End Repeat

Convert character string to integer value

If the input is not valid

Print an error message

Else

Read character string corresponding to the base to convert to

Convert character string to integer value

If the string is blank, end Repeat

If the input is not valid

Print an error message

Else3/9

Convert the input to an integer in the target base and print

End Repeat

}

The Run Method

It is straightforward to translate this into Java code (you can use this code in your program, if you wish, but you must acknowledge

where it came from in the comments, e.g.,

// The code below is taken from ECSE 202, Winter 2021, Assignment 1.

Recall that the run() method needs to be embedded in a class that extends ConsoleProgram.

// Run method:

// Print greeting and instructions.

public void run() {

println("Base conversion program; converts +ve integers to a target base.");

println("Enter number to be converted and target base on separate lines following the prompts.");

println("A blank entry for either input terminates the program.");

// Main program loop: read input, check for exit, convert, print result.

while (true) {

String input = readLine("Number > ");

// Read input and check for break.

if (input.equals("")) break;

int number = String2Int(input);

// Convert to integer

if (number < 0) {

println("Error! "+input+" does not correspond to a positive integer.");

}

else {

input = readLine("Target base > ");

// Now do the same for the base value

if (input.equals("")) break;

int base = String2Int(input);

// Convert to integer

if (base < 2 || base > 16) {

// Range error

println("The base must be between 2 and 16 inclusive.");

}

else {4/9

String result = baseConv(number,base);

// Convert and print result

println(number+" expressed in base "+base+" is "+result);

}

}

}

// Termination of program

println("Program terminated.");

}

Observations:

1. The readLine method is provided by ConsoleProgram and works like readInt and readDouble, except that a string

corresponding to the user input is returned instead.

2. The equals method is part of the String class. You can use it as shown to test whether the user entered a blank input.

3. The String2Int method, which you have to write as part of this assignment, takes an argument of type String, corresponding to

the user input, and returns either i) a positive integer in the case of a valid user input or ii) -1 indicating an invalid input (see

the examples on the previous page). We will talk more about this input shortly.

4. The baseConv method, which is the other method that you will have to write, takes two integers as input corresponding to the

number to be converted and the target base respectively, and returns a string that corresponds to the number in the target base.

There are several concepts involved in this method that will be detailed shortly.

String2Int

The String2Int method has the following signature:

int string2int (String input), where input is a string corresponding to the number that the user entered on the keyboard.

Under the assumption that the string corresponds to a positive number, each character must then correspond to a digit between [0,9].

The following pseudocode describes an algorithm that will do the job.

String2Int:

Input: a character string corresponding to positive decimal integer5/9

Output: -1 if the input string is not valid (each character must correspond to a digit between [0,9]), or the value otherwise.

Let sum = 0

Let power_of_ten = 1

For index = length of string - 1 to 0 by -1

Get character at index position

Convert from char code to integer in [0,9]

If integer is not [0,9] return with -1

Multiply by power_of_ten

Add to sum

Multiply power_of_10 by 10

End for

Return sum

To code this algorithm, you can make use of the following methods from the String class. Note that receiver syntax is used (see

examples immediately following).

Some useful methods in the String class:

charAt(index)

returns the character (primitive type char) at position index (first character has index 0).

length()

returns the length of the string.

Examples:

String foo = "324794";

int length = foo.length();

char myChar = foo.charAt(4);

println("Length of string is "+length+". Character at position 4 is "+myChar+".);

Length of string is 6. Character at position 4 is 9.6/9

The last character in the string is foo.charAt(foo.length-1).

To convert the character code for characters in the range [0,9] to their integer counterparts, do the following:

int x = foo.charAt(4) - '0';

As we shall see a bit later in the course, the character codes for letters and numbers follow alphabetical order. This means that the

code corresponding to integer 5 (53) has a value that is greater than the character code for 0 (48) by 53-48=5. So, to convert the

character code corresponding to a single digit in the range [0,9], all we need to do is to subtract the character code for 0. In the above

example variable x will have a value of 9. This is because the code for the character in position 4 is 57 and the code for 0 is 48. In

fact, we don't have to know anything about the particular codes, just the fact that the codes are ordered in alphabetical and numerical

order. By the way, when your write an expression of the form

int y = 'w';

the right hand side of the expression evaluates to the character code for w. String and character representations will be dealt with later

in Chapter 11.

baseConv

The pseudocode for an algorithm to convert an integer in Base-10 to an integer in some other base is listed below. As each digit is

calculated, it is immediately converted into its corresponding symbol in the target base. The symbol is then concatenated to the output

string. Note that since the algorithm produces the digits in reverse order, the symbol is concatenated onto the beginning of the string

instead of the end.

Algorithm: convert a number in Base-10 to a string representing the number in the target base.

Input: number, base integers corresponding to the number to be converted and the target base.

Output: A string corresponding to the output.

Let string = ""

Initialize the result string to empty

While number > 07/9

digit = number % base

Current digit beginning with the least significant; range is [0,base]

number = number / base

Convert digit to a character in {0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F}

string = converted digit + string

End while

return string

Example: Convert 127 to Base_16

digit = 127 % 16 = 15

The first iteration produces the least significant digit

number = 127 / 16 = 7

digit = 7 % 16 = 7

The last iteration produces the most significant digit.

number = 7 / 16 = 0

Answer: 7 15

Each digit needs to be expressed in Base_16 (hexadecimal) form.

7 in Base_16 7

15 in Base_16 F

Final form: 7F

Suppose we define the following string: String LUT = "0123456789ABCDEF" (LUT stands for Look-Up Table).

The expression LUT.charAt(7) would result in the character 7

The expression LUT.charAt(15) would result in the character F

So, one can easily convert the current digit into its corresponding symbol (character) with the following expression:

char symbol = LUT.charAt(digit);8/9

Or we can write the concatenation as follows:

string = LUT.charAt(digit) + string;

Observe that this assembles the string in reverse order as required.

Tips on Developing the Code

It is generally advisable to get the individual components written and tested before proceeding to test and debug the overall program.

For the present assignment there are 3 key methods: run(), String2Int() and baseConv(). Here are some suggestions as to how you

might proceed if you are new to writing code:

1. Start with String2Int() by translating the pseudocode into a working method. Write a simple test class where the run() method

simply prompts the user for input, calls String2Int(), and prints the return value. You should do this in a loop so the method

can be validated with different inputs and test cases.

2. baseConv() is a bit more complicated. If the method does not produce the correct result, you might consider adding println()

statements to your code to show the values computed for each digit of the output before converting to a character. Once this

part is working it becomes easier to debug any issues with conversion.

3. With these key methods tested and debugged, it is straightforward to put together and test the run() method.

The overall assignment code is approximately 50 lines (excluding comments) using the default Eclipse formatting.

Documenting Your Code

As the complexity of software code grows it becomes increasingly difficult to maintain unless properly documented. In Chapter 6 we

will discuss the Javadoc code documentation system which is part of Java and built in to most integrated development environments

(IDE) such as Eclipse. Javadoc automatically produces code documentation from comments embedded in classes and methods. Such

comments are essential as the intent of a programmer is not always transparent in one's computer code especially if written by

someone else or even to the author after a certain period of time has elapsed. For this reason, any code written for this course must be

properly documented (Chapter 6 will describe how) or else be considered incomplete (i.e. marks deducted) even if it works

correctly. For this first assignment such documentation is not mandatory, but you are strongly encouraged to start doing so. At the

very least, variables should be commented along with header comments in the different sections of your code.Instructions

1. Write a Java program consisting of a class, BaseConversion.java, that implements an interactive program along the lines

described earlier in this document. If this is one of the first programs you have written, you can elect to use the example in

this document as a starting point (* make sure to indicate this in your comments). More experienced Java programmers may

wish to do this without using acm the choice is up to you.

2. Run the examples shown earlier and make sure that your results are correct. Save these results in a screen capture and save the

results as a pdf file called A1.pdf.

3. Make sure that your Java source file is properly documented and that it contains your name and student ID in the comments.

4. Upload BaseConversion.java and A1.pdf on myCourses as indicated.

* Plagiarism also applies to software. If you incorporate code from an external source (i.e. code that you did not write), then you must

cite the source of this code in your comments.

and the ConsoleProgram which can be found at https://cs.stanford.edu/people/eroberts/jtf/acm.jar Best,

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Linked Data A Geographic Perspective

Authors: Glen Hart, Catherine Dolbear

1st Edition

1000218910, 9781000218916

More Books

Students also viewed these Databases questions

Question

Provide examples of KPIs in Human Capital Management.

Answered: 1 week ago

Question

What are OLAP Cubes?

Answered: 1 week ago