Instantiating NumberFormat Class

  • Thread starter Thread starter friendbobbiny
  • Start date Start date
  • Tags Tags
    Class
Click For Summary
The discussion centers on a coding issue related to the instantiation of the NumberFormat class in Java. The user encounters a compiler error when trying to create an instance of NumberFormat directly, which is not allowed since NumberFormat is an abstract class. Instead, it is recommended to use factory methods provided by the class, such as NumberFormat.getInstance(), to obtain a concrete instance for formatting numbers according to a specified locale. Additional resources and examples from the official Java documentation are suggested for further clarification on proper usage.
friendbobbiny
Messages
49
Reaction score
2
I've imported java.util, java.text and placed the following method under an appropriate class.

I'm unable to pinpoint why compiler can't instantiate the type NumberFormat in my method's second line





public static void tailorFormat(String name, double value, Locale loc){

NumberFormat kitty = new NumberFormat (loc); // <<<<< this is where I've referred to

DecimalFormat shelter = (DecimalFormat) kitty;
shelter.applyPattern(name);
shelter.format(value);
System.out.println(name + " " + value + " " + loc.toString());
}
 
Technology news on Phys.org
What is the error that the compiler is telling you?
Usually (but not always) the compiler is actually quite helpful in telling you what you've done wrong :)
 
java.text.NumberFormat is an abstract class, so you can't use it directly as you are trying to. Here's a sample of how this class can be used (see http://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html):
To format a number for the current Locale, use one of the factory class methods:
Code:
  myString = NumberFormat.getInstance().format(myNumber);
The web page I linked to has several other examples that might be of help to you.
 
Last edited by a moderator:
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 8 ·
Replies
8
Views
2K
Replies
8
Views
2K
  • · Replies 3 ·
Replies
3
Views
1K
Replies
4
Views
2K
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 19 ·
Replies
19
Views
1K
  • · Replies 41 ·
2
Replies
41
Views
5K
  • · Replies 3 ·
Replies
3
Views
4K
Replies
1
Views
2K