JAVA: Remainder % with printf() not working

272 Views Asked by At

I am trying to write the equivalent of

System.out.println(a + " % " + b + " = " + r);  

with the print(f)

System.out.printf("%d +'%' + %d = %d",a,b,r);

but it says the format string is malformed. I am guessing it is because of the % sign. Is there a way around this?

3

There are 3 best solutions below

1
On BEST ANSWER
System.out.printf("%d %% %d = %d%n", a, b, r);

Self-escaped.

Your code constructed a string with a single %. Also add a newline, by %n which can deliver \n or \r\n.

0
On

% is used as a formate specifier, instead of directly using it you can use it as char.

public static void main(String[] args) {

       int a = 6 ;
       int b = 7;
       int r = 8;
       char chr = '%';
        System.out.printf("%d + %c + %d = %d",a,chr,b,r);
    }

enter image description here

0
On

It should be like that

 class Main {
  public static void main(String[] args) {
    int a =10;
    int b =5;
    int r =22;

System.out.printf("%d %d %d ",a,b,r);


  }
}