7
\$\begingroup\$

Output formatting:

Input Format

Every line of input will contain a String followed by an integer. Each String will have a maximum of 10 alphabetic characters, and each integer will be in the inclusive range from 0 to 999.

Output Format

In each line of output there should be two columns: The first column contains the String and is left justified using exactly 15 characters.
The second column contains the integer, expressed in exactly 3 digits; if the original input has less than three digits, you must pad your output's leading digits with zeroes.

Sample Input

java 100
cpp 65
python 50

Sample Output

================================
java           100 
cpp            065 
python         050 
================================

printf is pretty straightforward. Two formats per row, newline at the end. The lines that don't need to be formatted (first and last) can be put on the screen using println instead. To the best of my knowledge it isn't possible to put both printf statements in one printing statement, so I made it a function instead. Keeps things neat.

My naming is probably horrible. As usual.

import java.util.Scanner;

public class Solution {
    private static void printRowOutlined(String left, int right) {
        System.out.printf("%-15s", left);
        System.out.printf("%03d\n", right);
    }
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("================================");
        for(int i = 0; i < 3; i++){
            String text = sc.next();
            int number = sc.nextInt();
            printRowOutlined(text, number);
        }
        System.out.println("================================");
    }
}
\$\endgroup\$

3 Answers 3

6
\$\begingroup\$

To the best of my knowledge it isn't possible to put both printf statements in one printing statement, so I made it a function instead.

It is possible: the printf method takes a varargs as second argument, so you can give it multiple arguments to format. When you have multiple arguments, each parameter can be refered to as %[argument_index$] in the format String (as per Formatter Javadoc), where argument_index is the index of the argument in the varargs. In this case, we can have:

private static void printRowOutlined(String left, int right) {
    System.out.printf("%-15s%03d%n", left, right);
}

Since each parameter in the format String are refered to in the order in which they are given in the arguments, we don't even need to specify the index (but we could have "%1$-15s%2$03d%n" as the format String). Regardless of that, I think having a separate method for the printing operation is still cleaner.

Also, don't use \n. You can use the %n specifier, which will use the line separator of the current system.

Furthermore, I notice you're not doing any validation on your input, you could verify that the integer is correct, in the right range, and that the String to format has the right numbers of characters.

\$\endgroup\$
1
  • \$\begingroup\$ Great advice :-) \$\endgroup\$
    – Mast
    Aug 29, 2016 at 22:18
3
\$\begingroup\$

There happen to be 3 lines of input in the given example, but the problem description doesn't mention that there will always be exactly 3. The program won't behave well with a different number of lines. Excess lines would be simply ignored, but if there's less than 3 lines, the scanner will throw a runtime exception.

A Scanner has a hasNext method that can help make this work with any number of lines of input, if you change the for-loop to this:

while (sc.hasNext()) {

As for naming... I usually try to err on the side of simplicity and naturalness. For example I'd call an instance of Scanner a scanner, and a method that prints columns printColumns, or printPaddedColumns, or even simply print.

The formatting style leaves something to be desired... I suggest you copy-paste into an IDE like IntelliJ or Eclipse and use the Reformat Code feature and observe what it changes. It will add spaces around operators and such, resulting in something slightly easier to read.

Instead of printing the === twice, I'd use a helper function. I'd go even further and add printHeader and printFooter helpers that can both call the same thing. It's a small thing, but it would make the main function higher level, delegating lower level details such as header and footer formatting elsewhere, out of the way of the bigger picture.

\$\endgroup\$
-1
\$\begingroup\$

A simple alternative approach could also be used to answer the above question.

import java.util.Scanner;

public class Solution {

public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("================================");
        for (int i = 0; i<3; i++) {
            String s1 = sc.next();
            int x = sc.nextInt();
            System.out.format("%-15s%03d%n", s1, x);
        }
        System.out.println("================================");
}

}

Solution Steps

First of all we will use System.out.format instead of System.out.println as it is use to format the output. So our code will be –> System.out.format();

Next we will use Modulus(%) within double quote. So our code will be –> System.out.format(“% “);

Next, we will use ‘-‘ after modulus which will instruct the compiler that it will be left indent, if you want to use right indent do not use “-“. So our code will be –> System.out.format(“%- “);

The 15 makes our String to be a minimum length of 15, it is required as per the question. So our code will be –> System.out.format(“%-15”);

s will be substituted by our String. This will mark the end of the first requirement. So our code will be –> System.out.format(“%-15s”);

Now the second part of the question. So again we will put % and 3d in order to format integer. The 3 makes our integer be a minimum length of 3. So our code will be –> System.out.format(“%-15s%3d”);

%n will help to go to the next line

\$\endgroup\$
3
  • 3
    \$\begingroup\$ You presented an alternative solution but the aim is to review the existing one \$\endgroup\$ Oct 29, 2023 at 12:27
  • 1
    \$\begingroup\$ @BillalBegueradj Please can you point to where in our rules alternative solution are not allowed? \$\endgroup\$
    – Peilonrayz
    Oct 29, 2023 at 19:23
  • \$\begingroup\$ @BillalBegueradj In code reviews, our primary goal is to assess and enhance code quality, correctness, and adherence to standards within a specific context. The process encourages the consideration of alternative, more efficient approaches, as well as code refactoring. The focus isn't on preserving the existing code as is, but on optimizing it to meet the desired quality and maintainability standards. By presenting an alternative, cleaner approach, I aim to collectively improve the codebase without being confined to the status quo, ultimately striving for more effective & efficient solutions. \$\endgroup\$
    – Gehan
    Oct 31, 2023 at 8:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.