1

The program is working just fine, but when the last line is printed it'd go like this: enter image description here

I tried doing it like this,because it's a symbol :

System.out.println(MessageFormat.format("The rectangle\'s area is {0}", area));

But it's still the same result. It'll only work , if I remove the symbol ->" ' ".

And I don't want suggestions of how I should write my the code. Only asking where is my mistake. Thank you

import java.text.MessageFormat;
import java.util.Scanner;

/*4. Rectangles

        Write an expression that calculates rectangle’s perimeter and area by given width and height.*/
public class Rectangles {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Please enter width:");
        double width = scan.nextDouble();
        System.out.print("Please enter height:");
        double height = scan.nextDouble();
        double area = 2 * width + 2* height;
        double perimeter = width*height;
        System.out.println(MessageFormat.format("Perimeter {0}",perimeter));
        System.out.println(MessageFormat.format("The rectangle's area is {0}", area));

    }
}
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
  • 5
    http://stackoverflow.com/questions/17569608/format-a-message-using-messageformat-format-in-java/17569639 – Reimeus Sep 08 '16 at 18:58
  • Hm, I couldn't find that when I searched. My bad. Thank you –  Sep 08 '16 at 19:05

2 Answers2

1

Whenever you are using MessageFormat you should be aware that the single quote character (') fulfils a special purpose inside message patterns. The single quote is used to represent a section within the message pattern that will not be formatted. A single quote itself must be escaped by using two single quotes ('').

Messageformat

System.out.println(MessageFormat.format("The rectangle'' area is {0}", area));
Dev. Joel
  • 1,127
  • 1
  • 9
  • 14
0

{} part of the format function denotes the index of the arguments passed, in this case width and height.width is stored at args[0] while height stored at args[1] for the above program.So {0} should be the format element for width while {1} should be the formatelement for height unlike the above program where {0} is chosen as formatelement for height as well.Moreover Area is being printed in the last line , May be the scope of the args[] parameter ended one line before. I tried printing both area and perimeter using the same line using {1} and {0} respectively and it worked well.