2

I am trying to format in java using the printf statement like in this webpage: Click Here. But I just can't figure out what the purpose of the $ sign is. Can someone please explain this to me?

Input:

java 100
cpp 65
python 50

Expected Output: ( there should be a space instead of _ )

 ================================
 java___________100 
 cpp___________065 
 python_________050 
 ================================

My code:

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.printf(s1 + "%03d", x);
            System.out.println();
        }
        System.out.println("================================");

    }
}
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
Suhas Bacchu
  • 37
  • 1
  • 1
  • 6
  • 2
    Please post your code here, not a link. Questions without **a clear problem statement** are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable example.](http://stackoverflow.com/help/mcve) – elixenide Nov 01 '15 at 02:42
  • 2
    See http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax – PM 77-1 Nov 01 '15 at 02:47
  • In short, the dollar character is not going to solve your problem. Try "%10.0d" instead. Read the javadocs fof a specification of what the format string means. – Stephen C Nov 01 '15 at 04:54

1 Answers1

8

It is the Argument Index. You can read the docs. I will try to explain the string from the tutorial for you:

String fmt = "%1$4s %2$10s %3$10s%n";

// format
cnsl.printft(fmt, "Items", "Quantity", "Price");
cnsl.printft(fmt, "-----", "-----", "-----");
cnsl.printft(fmt, "Tomato", "1 kg", "15");
cnsl.printft(fmt, "Potato", "5 kg", "50");
cnsl.printft(fmt, "Onion", "2 kg", "30");
cnsl.printft(fmt, "Apple", "4 kg", "80");

In general the format is %[argument_index$][flags][width][.precision]conversion.

In our example, #$ points to the position within our printft() statement. We have 3 strings to be formatted and hence why our format string has 1$, 2$,3$. The number that follows its the width between each argument. This width begins at 0 which means the actual width would be +1. The s is our conversion to string and the %n new line at the end.

Items      Quantity      Price
-----      --------      -----
Tomato     1 kg          15
Potato     5 kg          50
Onion      2 kg          30
Apple      4 kg          80
Michael-O
  • 18,123
  • 6
  • 55
  • 121
Alexander
  • 480
  • 2
  • 5
  • 21