Reputation: 2253
I'm trying to print the following output on the screen.
#
##
###
####
#####
######
This is my code,
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = Integer.parseInt(sc.nextLine());
for(int i= 1; i <= num; i++){
String spc = String.format("%" + (num - i) + "s", " ");
String hash = String.format("%" + i + "#", "#");
System.out.println(spc+hash);
}
}
I get the following error,
Exception in thread "main" java.util.FormatFlagsConversionMismatchException: Conversion = s, Flags = #
at java.util.Formatter$FormatSpecifier.failMismatch(Formatter.java:4298)
at java.util.Formatter$FormatSpecifier.printString(Formatter.java:2882)
at java.util.Formatter$FormatSpecifier.print(Formatter.java:2763)
at java.util.Formatter.format(Formatter.java:2520)
at java.util.Formatter.format(Formatter.java:2455)
at java.lang.String.format(String.java:2940)
at Solution.main(Solution.java:13)
I can understand my String.format has not been done right, but the docs are confusing on printing the character #
Any help appreciated.
Upvotes: 1
Views: 3678
Reputation: 1
I came across the same output. Here is one solution. Just in case someone stumbles again.
Instead of creating # and spaces separately, We can define width to the format method. Refer Java String Format Examples
String hash = "";
for (int i = 1; i <=n; i++) {
hash+="#";
System.out.println(String.format("%"+n+"s",hash));
}
Upvotes: 0
Reputation: 2270
You could try like this:
for (int i = 1; i <= num; i++) {
String spc = (i == num) ? "" : String.format("%" + (num - i) + "s", " ");
String hash = String.format("%" + i + "s", "#").replace(' ', '#');
System.out.println(spc + hash);
}
Output:
#
##
###
####
#####
######
Upvotes: 3
Reputation: 585
Try this
for(int i= 1; i <= num; i++)
{
if((num-i)>0)
{
String spc = String.format("%" + (num - i) + "S", " ");
String hash = String.format("%" + i + "s", "#");
System.out.println(spc+hash);
}
}
Upvotes: 0
Reputation: 36229
I guess you wanted to write:
String hash = String.format("%" + i + "s", "#");
Reading the error message helped me in finding this error, though you didn't marked where line 13 is.
Upvotes: 2