Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Background: In the code distributed with the assignment for MP5, the columns of

ID: 3816815 • Letter: B

Question

Background: In the code distributed with the assignment for MP5, the columns of simulation output will only be properly titled if the gate names are all exactly 5 characters long. The code that does the relevant printing is: system out. print g.name A problem: Write code to replace the above that pads shorter names to 5 characters and truncates longer names. This is a small exercise in Java string manipulation. only once to compute the title line of the output. Hint: It can be done in one simple expression Computational efficiency is not really importa a this code is used involving concatenation and substring operations (1 point)

Explanation / Answer

This string manipulations is possible in java usinig String.subSequence() and String.format() methods.

we could simply use below one line to get the formatted string in name1.

We have used ternary if else condition to check if length of given string is greater than 5, then we would trim the string by using subsequence method and if the string is lesser than 5 characters long, we could add some empty space after the given string to make final string 5 characters long.

String name="Johanesha";

String name1 = (String) (name.length()>5?name.subSequence(0, 5):name.format("%-5s",name));

So, in our code, we could simply use one line highlighted above and pass the string to get formatted value.