DecimalFormat question

Hey all
How do I use DecimalFormat in such a way that the there can be an arbitrary number of digits before the decimal point and a speciffied number after the point, the caveat being that the returned number use scientific notation where applicable. Ill clarify with example.
I want three digits after the decimal
double d = 1.2345e10
use some DecimalFormat magic should output
1.235e10
and not
12350000000.0
another ex)
d = 1.3243373628372937e8
outputs
132433736.284
and not
1.324e8
Thanx in advance

Huh?
import java.text.DecimalFormat;
public class PG
    public static void main(String[] args)
        DecimalFormat format = new DecimalFormat("0.###E0");
        System.out.println(format.format(132433736.284));
}prints:
1.324E8

Similar Messages

  • Please Suggest - new java.text.DecimalFormat Question

    table2.setValueAt(
    "$"+new java.text.DecimalFormat("#.##").format
        ((Double.valueOf(table2.getValueAt(row,1).toString())).doubleValue())*
        ((Double.valueOf(table2.getValueAt(row,2).toString())).doubleValue())
    row,
    3
    );Is there a way to force DecimalFormat to display .00?
    Is there a way to ignore a "$" preceding the value from table2.getValueAt(row,1)?

    Is there a way to force DecimalFormat to display .00?YES: new java.text.DecimalFormat("\u00A40.00").format

  • For Loop and Void Method Questions

    Question 1: How would I write a for loop that repeats the according to the number entered, to prompt the user to enter a number (double) between 1 and 100. If the number is outside this range it is not accepted.
    Question: 2 Also how would I write a for loop to do sum and find the average of the array numbers in a seperate void method( does not return anything to the main method)?
    Question: 3 (first code snippet) With my for loop that is used to process each number in the array and square it and cube it and display the results to 2 decimal places. How do I make it so say I want the array to allow me to enter 2 numbers (so I enter 2 numbers) then it asks me to enter a number between 1 -100 (which will prompt 2 times) that it shows me the results for the entered numbers between 1-100 after one another instead of number then result number then result like I how it now.
    for (int index = 0; index < howNum; index++) // process each number in the array
              enterYourNumbers = JOptionPane.showInputDialog   
                            ("Enter a number between 1 and 100");                       
              numArray = new double[howNum]; 
            try
                numArray[index] = Double.parseDouble(enterYourNumbers);
            catch (NumberFormatException e)
                    enterYourNumbers = JOptionPane.showInputDialog
                              ("Enter a number between 1 and 100");                          
                DecimalFormat fmt = new DecimalFormat ("###,###.00");
                JOptionPane.showMessageDialog(null, enterYourNumbers + " "  + "squared is "  + fmt.format(calcSquare(numArray[index]))
                                              + "\n" + enterYourNumbers + " " +  "cubed is " + fmt.format(calcCube(numArray[index])));                                                                           
                wantToContinue = JOptionPane.showInputDialog ("Do you want to continue(y/n)? ");
      while (wantToContinue.equalsIgnoreCase("y"));
    import javax.swing.*;
    import java.text.DecimalFormat;
    public class Array
        public static void main(String[] args)
            int howNum = 0;
            int whichNum = 0;     
            double[] numArray;
            boolean invalidInput = true;
            String howManyNumbers, enterYourNumbers, wantToContinue;
      do // repeat program while "y"
          do // repeat if invalid input
            howManyNumbers = JOptionPane.showInputDialog
                        ("How many numbers do you want to enter");                     
            try
                 howNum = Integer.parseInt(howManyNumbers);
                 invalidInput =  false;
            catch (NumberFormatException e )
                howManyNumbers = JOptionPane.showInputDialog
                            ("How many numbers do you want to enter");
          while (invalidInput);
          for (int index = 0; index < howNum; index++) // process each number in the array
              enterYourNumbers = JOptionPane.showInputDialog   
                            ("Enter a number between 1 and 100");                       
              numArray = new double[howNum]; 
            try
                numArray[index] = Double.parseDouble(enterYourNumbers);
            catch (NumberFormatException e)
                    enterYourNumbers = JOptionPane.showInputDialog
                              ("Enter a number between 1 and 100");                          
                DecimalFormat fmt = new DecimalFormat ("###,###.00");
                JOptionPane.showMessageDialog(null, enterYourNumbers + " "  + "squared is "  + fmt.format(calcSquare(numArray[index]))
                                              + "\n" + enterYourNumbers + " " +  "cubed is " + fmt.format(calcCube(numArray[index])));                                                                           
                wantToContinue = JOptionPane.showInputDialog ("Do you want to continue(y/n)? ");
      while (wantToContinue.equalsIgnoreCase("y"));
        public static double calcSquare(double yourNumberSquared)
            return yourNumberSquared * yourNumberSquared;       
        public static double calcCube(double yourNumberCubed)
           return yourNumberCubed * yourNumberCubed * yourNumberCubed;              
        public static void calcAverage(double yourNumberAverage)
    }

    DeafBox wrote:
    Question 1: How would I write a for loop that repeats the according to the number entered, to prompt the user to enter a number (double) between 1 and 100. If the number is outside this range it is not accepted. Use a while loop instead.
    Question: 2 Also how would I write a for loop to do sum and find the average of the array numbers in a seperate void method( does not return anything to the main method)? Why would you want to use 2 methods. Use the loop to sum the numbers. Then after the loop a single line of code calculates the average.
    Question: 3 (first code snippet) With my for loop that is used to process each number in the array and square it and cube it and display the results to 2 decimal places. How do I make it so say I want the array to allow me to enter 2 numbers (so I enter 2 numbers) then it asks me to enter a number between 1 -100 (which will prompt 2 times) that it shows me the results for the entered numbers between 1-100 after one another instead of number then result number then result like I how it now. If I understand you correctly, use 2 loops. One gathers user inputs and stores them in an array/List. The second loop iterates over the array/List and does calculations.

  • Need help with Java, have a few questions about my Applet

    Purpose of the program: To create a mortgage calculator that will allow the user to input the loan principal then select 1 of 3 choices from a combo-box (7 years @ 5.35%, 15 years @ 5.50%, 30 years @ 5.75%).
    Problem: My program was working properly (so I thought). I can get the program to properly compile and run through TextPad. However, I noticed that when the user clicks the calculate more than once (with the same input), it slightly alters the output calculations. So that is my first question, Why is it doing that?  How can I get it only calculate that information once unless the user changes it etc?
    My next question is regarding my exit button. I was told by my instructor (who has already stated he won't help any of us) that my exit button does not work for an applet and only for an application. So, how can I create an exit button that will work with an applet? I thought I did it right but I can't find any resources online for this.
    Next question, why isn't my program properly validating invalid input? My program should only allow numeric input and nothing more.
    And last question, when invalid input is entered and the user clicks calculate, why isn't my JOptionPane window for error messages not displaying?
    I know my code is a little long so I have to post this in two messages. Please don't criticize me for what I am doing, that is why I am learning and have come to this forum for help. Thanks
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    import java.text.NumberFormat;
    import java.text.DecimalFormat;
    // Creating the main class
    public class test extends JApplet implements ActionListener
         // Defining of format information
         JLabel heading = new JLabel("McBride Financial Services Mortgage Calculator");
         Font newFontOne = new Font("TimesRoman", Font.BOLD, 20);
         Font newFontTwo = new Font("TimesRoman", Font.ITALIC, 16);
         Font newFontThree = new Font("TimesRoman", Font.BOLD, 16);
         Font newFontFour = new Font("TimesRoman", Font.BOLD, 14);
         JButton calculate = new JButton("Calculate");
         JButton exitButton = new JButton("Quit");
         JButton clearButton = new JButton("Clear");
         JLabel instructions = new JLabel("Please Enter the Principal Amount Below");
         JLabel instructions2 = new JLabel("and Select a Loan Type from the Menu");
         // Declaration of variables
         private double principalAmount;
         private JLabel principalLabel = new JLabel("Principal Amount");
         private NumberFormat principalFormat;
         private JTextField enterPrincipal = new JTextField(10);
         private double finalPayment;
         private JLabel monthlyPaymentLabel = new JLabel("  Monthly Payment    \t         Interest Paid    \t \t            Loan Balance");
         private NumberFormat finalPaymentFormat;
         private JTextField displayMonthlyPayment = new JTextField(10);
         private JTextField displayInterestPaid = new JTextField(10);
         private JTextField displayBalance = new JTextField(10);
         // Creation of the String of arrays for the ComboBox
         String [] list = {"7 Years @ 5.35%", "15 Years @ 5.50%", "30 Years @ 5.75%"};
         JComboBox selections = new JComboBox(list);
         // Creation of the textArea that will display the output
         private TextArea txtArea = new TextArea(5, 10);
         StringBuffer buff = null;
              Edited by: LoveMyAJ on Jan 19, 2009 1:49 AM

    // Initializing the interface
         public void init()
              // Creation of the panel design and fonts
              JPanel upper = new JPanel(new BorderLayout());
              JPanel middle = new JPanel(new BorderLayout());
              JPanel lower = new JPanel(new BorderLayout());
              JPanel areaOne = new JPanel(new BorderLayout());
              JPanel areaTwo = new JPanel(new BorderLayout());
              JPanel areaThree = new JPanel(new BorderLayout());
              JPanel areaFour = new JPanel(new BorderLayout());
              JPanel areaFive = new JPanel(new BorderLayout());
              JPanel areaSix = new JPanel(new BorderLayout());
              Container con = getContentPane();
              getContentPane().add(upper, BorderLayout.NORTH);
              getContentPane().add(middle, BorderLayout.CENTER);
              getContentPane().add(lower, BorderLayout.SOUTH);
              upper.add(areaOne, BorderLayout.NORTH);
              middle.add(areaTwo, BorderLayout.NORTH);
              middle.add(areaThree, BorderLayout.CENTER);
              middle.add(areaFour, BorderLayout.SOUTH);
              lower.add(areaFive, BorderLayout.NORTH);
              lower.add(areaSix, BorderLayout.SOUTH);
              heading.setFont(newFontOne);
              instructions.setFont(newFontTwo);
              instructions2.setFont(newFontTwo);
              principalLabel.setFont(newFontThree);
              monthlyPaymentLabel.setFont(newFontFour);
              displayInterestPaid.setFont(newFontFour);
              displayBalance.setFont(newFontFour);
              areaOne.add(heading, BorderLayout.NORTH);
              areaOne.add(instructions, BorderLayout.CENTER);
              areaOne.add(instructions2, BorderLayout.SOUTH);
              areaTwo.add(principalLabel, BorderLayout.WEST);
              areaTwo.add(enterPrincipal, BorderLayout.EAST);
              areaThree.add(selections, BorderLayout.NORTH);
              areaFour.add(calculate, BorderLayout.CENTER);
              areaFour.add(exitButton, BorderLayout.EAST);
              areaFour.add(clearButton, BorderLayout.WEST);
              areaFive.add(monthlyPaymentLabel, BorderLayout.CENTER);
              areaSix.add(txtArea, BorderLayout.CENTER);
              // Using the ActionListener to determine when each button is clicked
              calculate.addActionListener(this);
              exitButton.addActionListener(this);
              clearButton.addActionListener(this);
              enterPrincipal.requestFocus();
              selections.addActionListener(this);
         // The method that will perform specific actions defined below
         public void actionPerformed(ActionEvent e)
              Object source = e.getSource();
              buff = new StringBuffer();
              // Outcome of pressing the calculate button
              if (source == calculate)
                   // Used to call upon the user chosen selection
                   int selection = selections.getSelectedIndex();
                   // If statement to call upon Loan One's Method
                   if (selection == 0)
                        Double data = (Double)calculateLoanOne();
                        String sourceInput = data.toString();
                        displayMonthlyPayment.setText(sourceInput);
                        txtArea.setText(buff.toString());
                   // If statement to call upon Loan Two's Method
                   else if (selection == 1)
                        Double data = (Double)calculateLoanTwo();
                        String sourceInput = data.toString();
                        displayMonthlyPayment.setText(sourceInput);
                        txtArea.setText(buff.toString());
                   // If statement to call upon Loan Three's Method
                   else if (selection == 2)
                        Double data = (Double)calculateLoanThree();
                        String sourceInput = data.toString();
                        displayMonthlyPayment.setText(sourceInput);
                        txtArea.setText(buff.toString());
                   // Outcome of pressing the clear button
                   else if (source == clearButton)
                        enterPrincipal.setText("");
                        displayMonthlyPayment.setText("");
                        selections.setSelectedIndex(0);
                        txtArea.setText("");
                   // Outcome of pressing the quit button
                   else if (source == exitButton)
                        System.exit(1);
         // Method used to validate user input
         private static boolean validate(JTextField in)
              String inText = in.getText();
              char[] charInput = inText.toCharArray();
              for(int i = 0; i < charInput.length; i++)
                   int asciiVal = (int)charInput;
              if((asciiVal >= 48 && asciiVal <= 57) || asciiVal == 46)
              else
                   JOptionPane.showMessageDialog(null, "Invalid Character, Please Use Numeric Values Only");
                   return false;
                   return true;

  • Create a new subclass OverpunchFormat extends DecimalFormat

    Well the last question on Formats I had got such quick and good results I'll give this form another go...
    I've got a funny fixed field format I've got to produce call NSF Overpunch - used in the health care industry (NSF = National Standard Format). They decide to save a few of those expensive bytes and encode the sign of the dollar amount into the last (right most) digit of the number... also they imply 2 decimal points.
    So if the number 234.56 is output in Overpunch format
    it becomes 2345F;
    23.00 -> 230{ 
    -3.77 -> 37P
    Via the encoding chart below.
    So I can get the format for impling the 2 decimal digits - but now I need this sign convention applied.
    The $640000{ question, can any NumberFormat do this?
    Thanks, David
    <code>
    + -
    ========
    {  0  }
    A 1 J
    B 2 K
    C 3 L
    D 4 M
    E 5 N
    F 6 O
    G 7 P
    H 8 Q
    I 9 R
    </code>

    >
    But the doc for this method should normally tellyou
    what is the final situation for that parameter, oram
    I wrong?Well - yes it should tell me the side-effects to the
    parameter.
    But can you figure out what this means:
    fieldPosition - On input: an alignment field, if
    desired. On output: the offsets of the alignment
    field.
    That's the complete documentation on how DecimalFormat
    effects the object FieldPosition - and I don't
    understand it.In this case, I would read up on FielPosition class and see what it is used for. See if you need to use it or not. Basically, does your format have fields? If so, what are they? If not, don't over-ride the method, or do, but call your other format method and return its value, leaving the FieldPosition untouched.

  • Some questions on JFormattedTextField

    I more or less manage to work with JFormattedTextField, but have not mastered this control fully. I hope that someone can help me with some questions I still have.
    JFormattedTextField field = new JFormattedTextField(); // no-args constructor
    double d = 1.23456; // primitive type will be autoboxed to Double
    field.setValue(d); // AbstractFormatterFactory based on DoubleNow, when the field has the focus, a text value of +1.2+ is displayed. As soon as it looses focus, the text value is changed into +1.235+. I find that weird behaviour and would rather see it the other way around or see the same text in both situations. Can anybody explain me what's happening here? I do not observe this behavior when using one of the other constructors.
    Another problem has to do with internationalization. The Dutch locale, for example, uses a comma as a decimal separator. Users having a scientific background, however, often override the default settings and use a period as a decimal separator (on Windows by changing the regional options). Is there a way of using whatever separator a user has chosen for his system when formatting numbers in Java? I know you can use the DecimalFormatSymbols class to change symbols for a specific locale, but that does not take into account user-specific settings.

    Hi.
    Try this:
    DecimalFormatSymbols fs = new DecimalFormatSymbols();
        fs.setDecimalSeparator('.');
        fs.setGroupingSeparator(',');
    DecimalFormat format = new DecimalFormat("##.#", fs);
    AbstractFormatter formatter    = new NumberFormatter( format );
    AbstractFormatterFactory ff = new DefaultFormatterFactory( formatter, formatter, formatter);
    JFormattedTextField field = new JFormattedTextField();
    field.setFormatterFactory(ff);

  • DecimalFormat issues/Scientific notation

    I have 2 issues with formatting numbers with scientific notation via the DecimalFormat class
    ISSUE 1: Disregard of the number of MAXIMUM FRACTOINAL DIGITS
         in the code:
                                     NumberFormat nf = NumberFormat.getInstance();
                                    DecimalFormat df = (DecimalFormat)nf;
                                    df.applyPattern("#00.#E0");
                                    System.out.println( df.format(12345678)); 
                                       it printed: 12.35E6
         Why does it violate my request for one significant digit beyond the decimal
         point?. (Note, this problem
    only seems to occur when when the sum of MAX integer and Max fractional
    digits in my pattern is 4)
    ISSUE 2:
    Number of significant digits displayed:- I really just need a sanity check on this one
    The 1.4.2 API for DecimalFormat states
    ?     The number of significant digits in the mantissa is the sum of the minimum integer and
    maximum fraction digits, and is unaffected by the maximum integer digits. For example,
    12345 formatted with "##0.##E0" is "12.3E3". To show all digits, set the significant digits
    count to zero. The number of significant digits does not affect parsing.
    I tried this ? it displays 123.45E3, or 5 significant digits? Looks like the number of significant digits
    is MAX integer + MAX fractional digits in a pattern. Am I correct (and the API not correct)?
    thanks
    carol

    Thanks. I'm assuming you're responding to issue #1. I did try it, and it worked, as expected. I never seem to have an issue when all symbols
    preceding the decimal are 0. My issue, I suppose, is the inconsistency of how the formatting
    works, when it comes to the number of fractional digit positions. Most of the times it 'behaves' and
    only prints out the number of digits you ask, but sometimes it does not.
    I've tested quite a few combinations. I'm attaching the code (in case you need help sleeping tonight).
    The only 'pattern' I've noticed is that this issue only occurs when the total number of digits specified
    in the pattern (before and after decimal) is 4. (exception ... if all digits specified before the decimal
    are 0s, this never occurs)
    I know a simple solution ... make sure I never have
    a total of 4 #s and 0s in my pattern. But again, my question is why ... and/or ... does this type of
    inconsistency crop up elsewhere.
    import java.util.*;
    import java.text.*;
    public class x {
         public static void main(String [] args) {
              NumberFormat nf = NumberFormat.getInstance();
              DecimalFormat df = (DecimalFormat)nf;
              // these 3 work like I'd expect: 3 digits to the left, one to the right w/ rounding
              // signif digits = max int digits + max fractional digits
              df.applyPattern("000.#E0");
              System.out.println( df.format(12345678)); // 123.5E5
              df.applyPattern("00.#E0");
              System.out.println( df.format(12345678)); // 12.3E6
              df.applyPattern("0.#E0");
              System.out.println( df.format(12345678)); // 1.2E7
              // signif digits = TOTAL int digits + max fractional digits
         System.out.println("X");
              df.applyPattern("###.#E0");                    // how did it decide to place decimal where it did?
              System.out.println( df.format(12345678)); // 12.35E6    // why did it violate my "1 max fractional digit"
                                                 // request? I would have expected 123.5E5
              df.applyPattern("##.#E0");
              System.out.println( df.format(12345678)); // 12.3E6
              df.applyPattern("#.#E0");
              System.out.println( df.format(12345678)); // 1.2E7
              //signif digits - TOTAL int digits + max fractional didgits
         System.out.println("");
         System.out.println("XXXXXXXX");
              df.applyPattern("#000.#E0");
              System.out.println( df.format(12345678));  // 1234.6E4
              df.applyPattern("#00.#E0");
              System.out.println( df.format(12345678));  // 12.35E6       // how did it decide to place decimal where it did?
                                                 // why did it violate my "1 max fractional digit"
                                                 // request? I would have expected 123.5E5
              df.applyPattern("#0.#E0");
              System.out.println( df.format(12345678)); //  12.3E6
              // significant digtis = TOTAL int digits + max fractional digits
         System.out.println("");
              df.applyPattern("###0.#E0");
              System.out.println( df.format(12345678));  // 1234.6E4
              df.applyPattern("##0.#E0");                    // how did it decide to place decimal where it did?
              System.out.println( df.format(12345678));  // 12.35E6     // why did it violate my "1 max fractional digit"
                                                 // request? I would have expected 123.5E5
              System.out.println( df.format(12345678));  // 12.35E6
              df.applyPattern("##.#E0");
              System.out.println( df.format(12345678));  // 12.3E6
    //API example from DecimaFormat RE Scientific Notation.. api says this will print 12.3E3
              df.applyPattern("###.##E0");
              System.out.println( df.format(12345)); //12.345E3   //violates max fractiona digit request
    //NOTE DOCS ARE WRONG ... the number of significant digits is = to max integer digits (number of # and 0 prior
    // to decimal point)  PLUS max number of digits after the decimal point... NOT Min. Integer digits + Max fractional digits
              // suggested pattern
              df.applyPattern("000000.##E0");
              System.out.println( df.format(12345678));  //123456.78

  • Locale Formatting question

    Locale Formatting question
    In the preceding code the number 50 represent currency.
    The output of NumberFormat is 50 with the local symbol
    The output of DecimalFormat is 50.00 without the local symbol
    The question is how to show 50.00 with the local symbol ???
    import java.text.*;
    import java.math.BigDecimal;
    public class LocalFormating {
    public static void main(String[] args) {
    NumberFormat nf = NumberFormat.getCurrencyInstance();
    DecimalFormat decfs = new DecimalFormat("#,##0.00");
    BigDecimal anumb = new BigDecimal(50);
    String temp = nf.format(anumb);
    System.out.println("local anumb = " +temp);
    String temp2 = decfs.format(anumb);
    System.out.println("Decimal format anumb = " +temp2);

    Locale Formatting question
    In the preceding code the number 50 represent currency.
    The output of NumberFormat is 50 with the local symbol
    The output of DecimalFormat is 50.00 without the local symbol
    The question is how to show 50.00 with the local symbol ???
    import java.text.*;
    import java.math.BigDecimal;
    public class LocalFormating {
    public static void main(String[] args) {
    NumberFormat nf = NumberFormat.getCurrencyInstance();
    DecimalFormat decfs = new DecimalFormat("#,##0.00");
    BigDecimal anumb = new BigDecimal(50);
    String temp = nf.format(anumb);
    System.out.println("local anumb = " +temp);
    String temp2 = decfs.format(anumb);
    System.out.println("Decimal format anumb = " +temp2);

  • Use DecimalFormat on a global basis

    Hi!
    I have a problem with Scientific notations of doubles. (i don't want them to become scientific when writing into Strings)
    I know I can use DecimalFormat to change the output-format, but as far as I have seen the only way to do this is to add some code whenever I want to write the number into the string.
    Instead of writing
    String s = "bla bla"+double.toString();
    i have to write
    DecimalFormat f;
    f.setOptions/format etc ...
    String s = "bla bla"+f.format(doublevalue);
    My question is if it is possible to change the formatting in some kind of global way? ie so that I can keep the first way of writing but still make use of a custom formating of the value whenever it is written to a string.
    For example
    DecimalFormat f = (DecimalFormat) NumberFormat.getInstance()
    f.setOptions/format etc
    String s = "bla bla"+doublevalue.toString(); /which would produce a non-scientific representation of the double
    Best regards
    Daniel

    What you are having a problem with is the behavior of the Double.toString() method; so, ideally what you want to do is override this method. Unfortunately for your issue, Double is final and cannot be overridden.
    You could write a static method in a utility class that does what you want and would not take much more effort than calling toString().
    Something like:
    String s = "bla bla" + MyUtility.formatNumber(someDouble);Or you could just keep a reference to a single DecimalFormat instance that you call format on as needed.

  • DecimalFormat in actionPerformed()

    hello -
    the aim is to have the output formatted
    - as $0,000.00
    from 45.0 - which is the current format output for the calculations(hrs * rate (factor tax).
    // class declaration, just before constructor begins:-
    //have instantiated(?-hopefully the correct term)
    the method thus:
    DecimalFormat curFormat = new DecimalFormat("$0,000,000.00");
    // within the actionPerformed method :-
    The data types are declared for the input field(hrs)
    and for a choice(payRate) and a list(tax) thus:
    double hours = Double.parseDouble(tfHrs.getText());
    //further withing actionPerformed is if statement,
    where calculations are done.
    //according to our class notes (certificate IV tertiary education standard australia) -
    the formatting curFormat.format
    is effected with the grossPay(curFormat)
    that is setText to display in a TextArea.
    Have been around the block on this around ten times.
    feeling vertigo -
    despite two error lines )currently two(hahahaaaaah =:)
    er hmmm 'scuse.
    despite two error lines, the program is
    still(currently) executing,
    performing the calculation, however yet with the incomplete
    DecimalFormat's final littttle bit that -need-s-putting-ing-
    Thank You. Am happy to post "It" (the beast;) -
    if you can bear with the background notes
    (spent some hours on compiling meaningful comments
    in the .java file.
    ThanksAgain from Kelso

    the sun.java link certainly does expand my understandingThat's what tutorials are for. Bookmark the link, or better still bookmark the Tutorial home page
    {color:#0000ff}http://java.sun.com/docs/books/tutorial/{color}
    This is another useful link that tells you about coding conventions
    {color:#0000ff}http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html{color}
    These are about how to get good help in a forum:
    {color:#0000ff}http://catb.org/~esr/faqs/smart-questions.html
    mindprod.com/jgloss/sscce.html{color}
    Do each little step of your processing in its own line.
    -- read input, assign to a String type variable (if input is a String, as in this case)
    -- convert to a double, assign to a double type variable
    -- format the double, assign to a String type variable
    // not so good
    double hours = Double.parseDouble(tfHrs.getText());
    // better
    String inHrs = tfHrs.getText()
    double hours = Double.parseDouble(inHrs);etc.
    If you already know this, just ignore it -- but it appears that you are as yet unaware of the easiest (and standard) way to check that each stage of your process is achieving the result you think it is, and that is to useSystem.out.println (someVariable);after each code line. You can also add descriptive text so you know which line printed where:System.out.println ("inHrs is [" + inHrs + "]");note the square brackets which enable you to "see" whitespace that might otherwise be missed.
    db

  • Quick JOptionPane question

    my code is
    Str = JOptionPane.showInputDialog(null, "Question",
                   "Title");
    how do i edit what the cancel button does? i looked on tutorial page and couldnt find it
    i just want it to System.exit(0)
    right now it crashes my program
    Edited by: hiby220 on Nov 8, 2008 2:12 PM

    i realized i should of put it in the code format, and was in middle of editing my post to do so, but you posted something before i had chance to finish. cant edit after someone posts
    double input;
    str = JOptionPane.showInputDialog(null, "Question");
    //make sure user entered a valid input
    try {input = Double.parseDouble(str);
    } catch (NumberFormatException e) { //on this line
    JOptionPane.showMessageDialog(null, "That is not a valid input! System exiting");
    System.exit(0);
    }better? and you telling me that simplifying it messes things up makes no sense...
    now when i run it and press cancel i get a java.lang.NullPointerException the specified line
    but since you insist on having my real code here it is package one;
    import java.io.*;
    import java.util.Scanner;
    import javax.swing.JOptionPane;
    import java.text.DecimalFormat;
    public class ATM2 {
           !! Ronnie Girardot !!
         static double totalCost, amount, cost, commission, Rate, USDtoCanD, USDtoMexPeso, USDtoEuro;
         static String currencyStr, Transaction, BankName;
         static boolean quit = false;
         static DecimalFormat formatter = new DecimalFormat("$#0.00");
         public static void main(String[] args) throws IOException {
              readDailyFile();
              welcome();
              while(!quit){
                   getCurrency();
                   Transaction = getTransaction();
                   if (Transaction == "Buys")
                        buyTransaction();
                   else if (Transaction == "Sells")
                        sellTransaction();
              showResults();
              writeLog();
         public static void readDailyFile() throws IOException {
              //get daily exchange rates via dailyRates.txt
              File file = new File("dailyRates.txt");
              //make sure dailyRate.txt exists
              if (!file.exists())
                   System.out.println("The file dailyRates.txt is not found.");
                   System.exit(0);
              Scanner input = new Scanner(file);
              //take all needed information out of dailyRates.txt
              BankName = input.nextLine();
              USDtoCanD = input.nextDouble();
              USDtoMexPeso = input.nextDouble();
              USDtoEuro = input.nextDouble();
         public static void welcome(){
         JOptionPane.showMessageDialog(null, "Hello and welcome to " + BankName + ",\n the best bank in the world!",
                   BankName,
                  JOptionPane.WARNING_MESSAGE);
         public static void getCurrency(){
              //show dialog asking what they wish to convert their USD to
              Object[] options = {"Canadian Dollar", "Mexican Peso", "Euro", "Cancel"};
            int n = JOptionPane.showOptionDialog(null,
            "Here you select which currency you are intrested in.\n" +
            "The next page then asks if you wish to buy or sell.\n" +
            "(The currect USD is worth " + formatter.format(USDtoCanD) + " Canadian, " + formatter.format(USDtoMexPeso) + " Pesos, " + formatter.format(USDtoEuro) + " Euros)",
            BankName + ", the best bank in the world.",
            JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            null, options, options[2]);
            switch(n){
            case 0:
                 currencyStr = "Canadian Dollars";
                 break;
            case 1:
                 currencyStr = "Pesos";
                 break;
            case 2:
                 currencyStr = "Euros";
                 break;
            case 3:
                 System.exit(0);
         public static String getTransaction(){
              String Action = "";
              //see if user wants to buy or sell
              Object[] options = {"Buy", "Sell", "Cancel"};
            int n = JOptionPane.showOptionDialog(null,
            "Do you wish to buy or sell " + currencyStr,
            BankName + ", the best bank in the world.",
            JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            null, options, options[2]);
            switch(n){
            case 0:
                 Action = "Buys";
                 break;
            case 1:
                 Action = "Sells";
                 break;
            case 2:
                 System.exit(0);     
              return Action;
         public static void buyTransaction(){
              String amountStr;
              //get amount user wishes to buy
              amountStr = JOptionPane.showInputDialog(null, "How many " + currencyStr +" do you wish to buy?");
              //make sure user entered a valid input
              try {amount = Double.parseDouble(amountStr);
                   } catch (NumberFormatException e) {
                         JOptionPane.showMessageDialog(null, "That is not a valid input! System exiting");
                         System.exit(0);
              //find out which rate to use
                   if (currencyStr == "Canadian Dollars")
                   Rate = USDtoCanD;
              else if (currencyStr == "Pesos")
                   Rate = USDtoMexPeso;
              else if (currencyStr == "Euros")
                   Rate = USDtoEuro;
              //find USD cost
              cost = amount / Rate;
              //find commission cost on USD amount
              commission = cost * .015;
              totalCost = cost + commission;
    public static void sellTransaction(){
         String amountStr;
         //get amount user wishes to sell
         amountStr = JOptionPane.showInputDialog(null, "How many " + currencyStr +" do you wish to sell?");
         //make sure user entered a valid input
         try {amount = Double.parseDouble(amountStr);
              } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(null, "That is not a valid input! System exiting");
                    System.exit(0);
         //find out which rate to use
              if (currencyStr == "Canadian Dollars")
              Rate = USDtoCanD;
         else if (currencyStr == "Pesos")
              Rate = USDtoMexPeso;
         else if (currencyStr == "Euros")
              Rate = USDtoEuro;
         //find USD cost
         cost = amount / Rate;
         //find commission cost on USD amount
         commission = cost * .015;
         totalCost = cost + commission;
         public static void showResults(){
              String str = "";
              if (Transaction == "Buys")
                   str = "US Dollar cost  = ";
              else if (Transaction == "Sells")
                   str = "US Dollar gain  = ";
              JOptionPane.showMessageDialog(null, Transaction + " " + formatter.format(amount) + " " + currencyStr + "\n"
                        + str + formatter.format(cost) + "\n" +
                          "Commission     = " + formatter.format(commission) + "\n" +
                          "Total cost          = " + formatter.format(totalCost));
              //see if user wants to make another transaction
              Object[] options = {"Yes", "No", "Cancel"};
            int n = JOptionPane.showOptionDialog(null,
            "Do you want to make another transaction?",
            BankName + ", the best bank in the world.",
            JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            null, options, options[2]);
            if (n == 1) System.exit(0);
            else if (n == 2) System.exit(0);
         public static void writeLog(){
    } i couldnt just cut out any of my real code because its a little complex. note i know its not finished yet, so dont complain about infinite loops or the blank writeLog() method

  • Funny question on double value

    hi all,
    I have a rather funny question ...
    how to getrid of the E from a very huge double number without using the java.math.BigDecimal or java.math.BigInteger classes.
    ex:-
    Double d1 = new Double("1487194731984573985734095734905873059734059734957340958734957309457389457983475");
    Double d2 = new Double(d1.doubleValue() * d1.doubleValue());
    d2.doubleValue() will give 7.246073001982964E147
    but the result should not have the E but the complete value.
    the thing is not to use java.math package.
    thx
    chandra

    Well you can use java.text.DecimalFormat to format the output of a double value. However you'll find that the huge value you think you stored in the Double is not in fact what java has kept - double does not have the precision you have requested and using the DecimalFormat this will be evident... EG doing something like
    double d = 123456789012345678901234567890.0;
    DecimalFormat df = new DecimalFormat(
    System.out.println("123456789012345678901234567890.0");
    System.out.println(d);
    System.out.println(df.format(d));Should clearly show that the value stored has lost precision. The reason you do not get an overflow as with an int value is that the values scale can be represented in the double not its precision.
    Hope that helps...
    Talden

  • Another Newb Question

    When using doubles I get like 140.000001 one or so when I put it into an equation. My question is how would I just just drop it off to a certain amount of decimal points that I choose?

    http://java.sun.com/j2se/1.4.1/docs/api/java/text/DecimalFormat.html

  • Very simple and quick question about Arrays

    Hi,
    I have the following code to produce a student grades provessing system. I have got it to store data in the array, i just cant figure out how to add the integers from the row to produce a total. Thats all I want to do create a total from the 6 marks and add a percentage.
    Any help would be greatly appreciated.
    -------------CODE BELOW----------------------
    import java.util.*;
    public class newstudent1_2
    public static void main (String[]args)
    System.out.println ("-----------------------------------------------"); //Decorative border to make the welcome message stand out
    System.out.println (" Welcome to Student Exam Mark Software 1.2"); //Simple welcome message
    System.out.println ("-----------------------------------------------");
    int [][] mark;
    int total_mark;
    int num_students;
    int num_questions = 9;
    Scanner kybd = new Scanner(System.in);
    System.out.println("How many students?");
    num_students =kybd.nextInt();
    mark = new int[num_students][num_questions] ;
    for (int i=0; i<num_students; i++)
    System.out.println("Enter the Students ID");
    String student_id;
    student_id =kybd.next();
    System.out.println("Student "+i);
    for( int j=1; j<num_questions; j++)
    System.out.println("Please enter a mark for question "+j);
    mark[i][j]=kybd.nextInt();
    System.out.print("id mark1 mark2 mark3 mark4 mark5 mark6 mark7 mark8");
    //This section prints the array data into a table
    System.out.println();
    for (int i=0; i<num_students; i++)
    for( int j=0; j<num_questions; j++)
    System.out.print(mark[i][j]+"\t"); //the \t is used to add spaces inbetween the output table
    System.out.println();
    --------------END OF CODE---------------
    Thanks.

    I had to do this same sort of thing for a school assignment but i didnt use an array.
    import java.text.DecimalFormat;
    import TurtleGraphics.KeyboardReader;
    public class grade_avg
         public static void main(String[] args)
              int grade, total = 0, count = 0;
              double avg = 0.0;
              KeyboardReader reader = new KeyboardReader();
              DecimalFormat df = new DecimalFormat("0.00");
         for (;;)
                   grade = reader.readInt("Please enter a grade: ");
              if (grade > 0)
                        total = total + grade;
                        count ++;
              if (grade == 0)
                        avg = total / count;
                        System.out.println("The average is: " + df.format(avg));
                        System.exit(0);
    }output looks like:
    Please enter a grade: 100
    Please enter a grade: 50
    Please enter a grade: 0
    The average is: 75.00

  • JFormatterTextField & InputVerifier Question

    Hi all,
    I am attempting to write a generic inputVerifier implementation and would appriaciate some thoughts and comments about its design. I want to achieve a verifier that will respond to different types of values entered into the JFormmatedTextFields ie if the input is a digit then call a specific method to verify its input range.
    Execution order is the shouldYieldFocus(), followed by verify() then verifyInt()... , i been looking at many examples and searched through this forum and have been able to get this far .. but cannot figure out how to override those methods
    My question is;
    1. I am implementing the shouldYieldFocus(JComponent input) & verify(JComponent input) in my FormVerifier class, how can I override these methods so for example I can pass some arguements for my customised verifyInt() method. eg i want my verify() function to acknoweledge that I want to call a specific method and pass it some upper and lower values, at the moment i hack it by using .setName("int") , but you will notice that my conditional checking is hardcoded, i would like these to be variables.
    snippet...
           FormVerifier verifier = new FormVerifier();
            farm_noLbl = new JLabel();
            farm_noFld = new JFormattedTextField();
            farm_noFld = new JFormattedTextField(createFormatter("####"));
            farm_noFld.setToolTipText("4 digit number e.g. 4065");
            farm_noFld.setName("int");
            farm_noFld.setInputVerifier(verifier);
    //NB: this method is in a different class (FormVerifier)
    public boolean verify(JComponent input)
            boolean wasValid = true;
            if (input.getName().equals("int"))
                wasValid = verifyInt(input);
            return wasValid;
    public boolean shouldYieldFocus(JComponent input)
            boolean inputOK = verify(input);
            if (!inputOK)
                //Avoid possible focus-transfer problems when bringing up
                //the dialog by temporarily removing the input verifier.
                //This is a workaround for bug #4532517.
                    input.setInputVerifier(null);
                   //Reinstall the input verifier.
                    input.setInputVerifier(this);
                return inputOK;
      public boolean verifyInt(JComponent input)
            final JFormattedTextField ftf = (JFormattedTextField) input;
            boolean wasValid = true;
            DecimalFormat decimalFormat;
            decimalFormat = (DecimalFormat)NumberFormat.getNumberInstance();
            decimalFormat.setParseIntegerOnly(true);
            int num = 0;
            try
              num = decimalFormat.parse(ftf.getText()).intValue();
            catch(ParseException e)
                System.out.println("Parse exce\n");
                return false;
            //Value was invalid.
            if (num < 1000)
                wasValid = false;
               System.out.println("Bad value: Number of years was < ");
            else if (num > 2000)
            wasValid = false;
             System.out.println("Bad value: Number of years was > ");
            return wasValid;
        }

    Thanks for your input camickr, I have since modified the code to import various verifiers to suit the needs for the different types of validition that I need to perform. I create a instance of each verifier and use set methods to achieve different results for each textfield ie
            RangeVerifier rv = new RangeVerifier();
            rv.setIntMinValue(1000);
            rv.setIntMaxValue(2000);
            farm_noFld.setInputVerifier(rv);
           rv.setIntMinValue(5);
           rv.setIntMaxValue(10);
           block_noFld.setInputVerifier(rv);
           DateVerifier ......
    ...I do have an other question though, in your previous post you mentioned that I dont need to use the shouldYieldFocus() but I have seen this method mplemented in many examples, is there a reason why you reconmend not to use it?

Maybe you are looking for

  • No index in Logic Express 9?

    Why do they take out the index in Logic Express 9?  I can't believe this. It was so easy to find things with L.E. 8.  You just looked it up in the back index and then go to that page. I tried downloading the L.E.8 manual, but since I upgraded to 9, t

  • How to unlock my i pad 3rd generation

    My I pad says to connect to i tunes. Itunes says it needs a passcode but the screen appears to be locked and I canoot get up the passcode page? Help please

  • How to simulate a pll circuit with NI MULTISIM

    I want to simulate a PLL circuit with Multisim 13.0 before building it on the real NI ELVIS 2 breadboard. I want to see what results I should be expecting first, but I couldn't find a 74HC4046 chip in the Multisim software. Does anyone know how I can

  • Help With Switch Statements

    Alrighty, so I have to do this assignment for my Java course, using a switch statement. The assignment is to have the user enter a number (1-5), and have the corresponding line of a poem be displayed. So if the user entered 1, "One two, buckle your s

  • Asset Depreciation posting at historical exhange rate in Non-leading LEDGER

    Hi Dear collegues Our client would like to post depreciation at historical exchange rates, but only at certain non-leading ledgers. So in leading leger the exchange rate should be at the posting day exchange rate, and at the other ledgers should be a