Doubles & rounding

I'm working on an ASCII version of battleship, and as part of the project, the hit/miss stats have to be printed out at the end. Because this is for a computer science course, my output has to be identical to the required output.
My program prints this:
Hit ratio: 66.66666666666667%
When it should be printing:
Hit ratio: 66.66666666666666%
and..
My Program:
Hit ratio: 33.333333333333336%
Required output:
Hit ratio: 33.33333333333333%
I'm assuming that this is happening because of the way doubles round, but I have no idea how I would fix that.
Here's the code that computes the ratio:
double ratio = 100.0 * numHit / numFired;
Where numHit is a double representing the number of missiles that hit
and numFired is a double representing the number of missiles fired

Couldn't you use java.text.DecimalFormat class?DecimalFormat lets you round down (truncate), which takes care of the
second example. But what about the first? You can get 13 6's after the dot
by truncating, but not 14.
I guess it's possible if you use BigDecimals to evaluate the ratio with quite
a lot of precision (more than a double) then use setScale() specifying that you
want the result truncated. But I sort of wonder why. (Yes, there are the marks,
but they don't make it sensible.)

Similar Messages

  • Formatting a Double to a String for Swing output

    Hi, I'm new to Java and I'm working on a project with AWT & Swing. I'm trying to read in a user entered number, convert it to a double, work on it and then output the String value of the result with only two decimal places. The code I have is:
    public void actionPerformed(ActionEvent e)
    double result = 99;
    double temp;
    DecimalFormat newTemp = new DecimalFormat("#,###.00");
    if (e.getSource() == bConvert1)
    temp = (Double.parseDouble(tTemp1.getText().trim()));
    result = (temp*1.8)+32;
    newTemp.format(result);
    tResult1.setText(String.valueOf(result));
    else if (e.getSource() == bConvert2)
    temp = (Double.parseDouble(tTemp2.getText().trim()));
    result = (5.0/9)*(temp-32);
    newTemp.format(result);
    tResult2.setText(String.valueOf(result));
    This is working for some values, but for some values entered, the result displayed is just the remainder.

    The reason it doesn't always work could be because DecimalFormat (for reasons known only to Sun) uses ROUND_HALF_EVEN...
    This means that you will have to round the value to the number of decimal places you require before calling format()
    I use something like the following formatter class
    class Formatter {
      public static final int DEFAULT_PRECISION = 2;
      public static final String DEFAULT_PATTERN = "#.00";
      public static final String ZEROS = "0000000000000000";
      public static String convertDoubleToString(Double d) {
        return convertDoubleToString(round(d, DEFAULT_PRECISION), DEFAULT_PATTERN);
      public static String convertDoubleToString(double d) {
        return convertDoubleToString(round(d, DEFAULT_PRECISION), DEFAULT_PATTERN);
      public static String convertDoubleToString(Double d, int precision) {
        return convertDoubleToString(round(d, precision), "#." + ZEROS.substring(precision));
      public static String convertDoubleToString(double d, int precision) {
        return convertDoubleToString(round(d, precision), "#." + ZEROS.substring(precision));
      public static String convertDoubleToString(Double d, String pattern) {
        return new DecimalFormat(pattern).format(d.doubleValue());
      public static String convertDoubleToString(double d, String pattern) {
        return new DecimalFormat(pattern).format(d);
      private static final double round(Double d, int precision) {
        double factor = Math.pow(10, precision);
        return Math.round((d.doubleValue() * factor)) / factor;
      private static final double round(double d, int precision) {
        double factor = Math.pow(10, precision);
        return Math.round((d * factor)) / factor;
    }

  • Rounding up to the nearest 0.05

    Hi guys i am trying to round a value up to the nearest 0.05. e.g. the value 94.63 would be rounded up as 94.65
    I have used big decimal with the round half up and round up modes but it still outputs 94.63
    How can I get arround this ?
    Cheers

          * Returns the value rounded up to the nearest 0.05
          * @param  double  value to be rounded
          * @return double  rounded up value
         private static double roundOff(double value)
              return Math.ceil(value / ROUNDUP_FACTOR) * ROUNDUP_FACTOR;
         }Where ROUNDUP_FACTOR = 0.05
    Edited by: fatjack on Dec 20, 2007 6:05 AM

  • Setting double value precision

    Is there any way to set the precision on a double.
    Example:
    double = 25.00016000207654
    precision = 4 decimal places (or some value 'x')
    So I am looking for 25.0002 (this value will then be converted to a string and then displayed).

    Here is a simple little program that will allow you to round and format the way you wanted:
    import java.text.*;
    public class testFormat {
       public static void main(String[] args) {
          double x=25.00016000207654;
          x=Round(x,4);
          DecimalFormat NF=new DecimalFormat("0.####");
          String formatted=NF.format(x);
          System.out.println(formatted);
       public static double Round(double x, int dec) {
          double multiple=Math.pow(10,dec);
          return Math.round(x*multiple)/multiple;
    }V.V.

  • Round to two decimal places...and keeping trailing 0

    Ok, I have done a search on rounding. So I made this function:
        private double round(double number){
           double d = Math.pow(10, 2);
           return Math.round(number * d) / d;
        }However, if I use a number like 3.59999, it returns 3.6. For what I am using it for, I need it to return 3.60. Any ideas? Thanks.

    You normally only format for display! You seem to be wanting the default format to show 2 decimal places. This makes no sense. Internally a number(double or float) doesn't know about decimal places so how can the default format know you want 2 decimal places?
    For the most part you only need to worry about decimal places when you print a number using the DecimalFormat class.
    There are times when you might want to round values to 2 decimal places before doing more calculation. I have only met this when adding monetary values when it is important that a column total equals the sum of a displayed column values. In this case one uses something like the technique you originally proposed to round values before summing them. You then use DecimalFormat to display the values.

  • Double to 2 decimal places

    I am putting a double variable out to a web page and also calculations on that double(a price). I am getting 4 decimal places on the original price and several decimal places on the calculations. Can anyone tell me how to round down to 2 decimal places?
    Thank you.
    Karen

    I generally use a formatter along the lines of the following. You could also use a wrapper class (Double is final, and you can't extend primitives) for Double which would incorperate this formatting. However you only need to use it when you are presenting it (or if you are persisting it to a lower precision data source, where truncation could result in larger inaccuracies creeping in).
    This also changes the ROUND_HALF_EVEN behaviour of DecimalFormat to ROUND_HALF_UP.
    Alternatively you could use BigDecimal (.setScale() to set decimal places) but there is an overhead which may be restrictive.
    class Formatter {
      public static final int DEFAULT_PRECISION = 2;
      public static final String DEFAULT_PATTERN = "#.00";
      public static final String ZEROS = "0000000000000000";
      public static String convertDoubleToString(Double d) {
        return convertDoubleToString(round(d, DEFAULT_PRECISION), DEFAULT_PATTERN);
      public static String convertDoubleToString(double d) {
        return convertDoubleToString(round(d, DEFAULT_PRECISION), DEFAULT_PATTERN);
      public static String convertDoubleToString(Double d, int precision) {
        return convertDoubleToString(round(d, precision), "#." + ZEROS.substring(precision));
      public static String convertDoubleToString(double d, int precision) {
        return convertDoubleToString(round(d, precision), "#." + ZEROS.substring(precision));
      public static String convertDoubleToString(Double d, String pattern) {
        return new DecimalFormat(pattern).format(d.doubleValue());
      public static String convertDoubleToString(double d, String pattern) {
        return new DecimalFormat(pattern).format(d);
      private static final double round(Double d, int precision) {
        double factor = Math.pow(10, precision);
        return Math.round((d.doubleValue() * factor)) / factor;
      private static final double round(double d, int precision) {
        double factor = Math.pow(10, precision);
        return Math.round((d * factor)) / factor;
    }

  • Money Rounding

    Hi all,
    I've looked-up the BigDecimal class from Math and i wana round the money such that it is always ROUND UP in 5 or 10 cents. Eg:
    $100.29 becomes $100.30
    $100.22 becomes $100.25
    $50.214 becomes $50.25
    Any idea how to do this? Thanks

    Although using DecimalFormat is a good choice, here is a method that do the rounding (deals with the 123.35000000001 case):
        static final double DELTA = 0.01;
        // num must be positive
        public double round(double num) {
            double numex = num * 100;
            int inumex = (int)numex;
            if ((numex - inumex) > DELTA)
                inumex++;
            int rest = inumex % 5;
            if (rest > 0)
                inumex += 5 - rest;
            return (double)inumex / 100;
        }Regards

  • Rounded Numbers Dont Add Up

    I have a user who is complaining that the numbers on her report don't add up to the total that's printed at the bottom. I haven't seen a sample of this yet but I wanted to run this by you guys and see if this code makes sense.
      function() {
        NumberFormat nf = new DecimalFormat("#,##0.00");
        double total = 0D;
        for (...) {
          double d = Math.random();
          total += round(d);
          print(nf.format(d));
        print(nf.format(total));
      double round(double d) {
        return (double)(Math.round(d*100)/100D);
      }Is my round() sound?

    I have a user who is complaining that the numbers on
    her report don't add up to the total that's printed at
    the bottom. This could be a problem with the user in that they don't understand numerics.
    Or it could b a problem with you in that you do not understand the problem domain.
    Floating point numbers are always inaccurate. It doesn't matter whether humans or computers do this. That is because floating point numbers (when used correctly) are an approximate measure of something which can not be measured exactly.
    For example a pound of hamburger might be marked as weighing 1.01 pounds. The inaccuracy is in that it might actually weigh 1.01015678 pounds (but is unlikely to weigh even that.) There is no way to get the exact weight.
    Now if that is your situation then it is problem with the user - the user doesn't understand numerics and the inherit inaccuracies.
    And it would probably be a bad idea for you to "fix" it for one user, when other users are expecting correct approximations.
    (One way to fix this is to 'fiddle' with the numbers that make up your sum. Adjust one so everything 'looks' right.)
    On the other hand maybe it is your problem. For example money. Money is not a floating point number, because money is always exact. Even when caculating interest it is always exact. You will never end up with a partial penny in your savings account, no matter how the interest rate is computed.
    And since money is accurate a floating point number is not necessarily the best way to represent it. Care must be used in doing so. As a previous poster suggested the BigDecimal class can be used.
    Or if your numbers are small then simply convert the money to integers by multiplying by 100 and rounding and then compute everything using that. And simply reformat the integer values so they look like floating point numbers rather than integers when you print them out.

  • Can I have some iWeb sites on one computer & some on another?

    I've been using iWeb to creat both personal and business sites for myself. I've got about six sites and I'd like to control the business ones from my work computer and my personal ones from my home computer. Can I do this? I had copied the files over so that both machines had the same data and I just deleted the personal pages from my work machine. When I went to quit out of iWeb it asked me if I wanted to publish my site which set off a light in my head. Only then did it occur to me that it was going to attempt to republish everyting, this time deleting my personal sites from my .Mac account because this (my work) computer no longer has my personal sites on it. Can someone help? Is there a way to do what I want to do?
    Thanks,
    Ben

    Benjamin,
    Yes, you can do what you are looking to do, but it will take a little time and effort to get it set up correctly. You are right that publishing from your work machine will delete your personal sites right now, but that can be fixed fairly easily. I'll walk you through the steps here, but I'd also encourage you to read through ApNewbie's domain splitting guide, too. (and be sure to read my notes at the end before starting this process!)
    1.) Copy your domain sites file both of your computers and put them in a safe place.
    2) If your iDisk is the desktop of either computer, unmount it.
    3) "Publish All" from your work computer. This will delete your home site, but we'll fix that before we are done.
    4) On your home computer, delete the work sites from iWeb, then "Publish All" from your home computer. This will delete your work site, but we'll fix that, too.
    5) From your work computer, "Publish All" again.
    6) From your home computer, "Publish All" again.
    7) Check your sites from your browser (don't forget to clear the cache before doing so!)
    8) If all is well, you are done; if they still don't all show up, do one more round of "Publish All," and you should be set to go.
    9) From here on out, you should be able to use the regular "Publish to .mac" process
    Note that the site that shows up at your "short" url (web.mac.com/username) will be the most recently updated site. If this is an issue for you, there are at least two options:
    1)create a one-page site in each domain.sites file (home and work) with links to all your sites. Make sure to give this site a different name in each file. (e.g. "siteindexwork" and "siteindexhome." For an example of a site index, look here.
    2) follow ApNewbie's directions for domain splitting and on each machine create a separate domain.sites file with just a site index and publish anytime you publish one of the other websites. (Note that if you create this index by copying your other file and deleting existing websites in it you need to do another double round of "Publish All" to get everything up and running.)

  • How do I convert my GUI java app to be an applet or display it on a webpage

    I have created a loan calculator program in netbeans, I got the application to run fine but now I want to add it into a html page.
    I'm just looking for a place to start, I just don't know where to go from here, I want to know if I can actually convert my app with a few changes to an applet or if any one can point me to a forum of similar interest or tutorials that explain what I'm looking for.
    I don't even know what i'm looking for except i want this program to run on a webpage.
    Or is there a way to run my .jar file on a webpage??
    My teacher has not taught us anything on this matter except the below code suggestions on converting and my program is more extensive than her examples for converting. This is what she briefly described on this subject.
    1.To convert an application to an applet the main differences are: import java.awt.Graphics; import javax.swing.JApplet; import javax.swing.JOptionPane;
         Extend JApplet Replace main with public void init() method
    Output with public void paint( Graphics g ) method
    2. Remove calls to setSize, setTitle, pack, and any window listener calls, e.g., setDefaultCloseOperation. Compile the program---if something doesn't compile just comment it out for now.
    3. Create a simple web page with the following body.
    <applet CODE="__________.class" WIDTH="300" HEIGHT="300"
    archive="http://www.cs.duke.edu/courses/fall01/cps108/resources/joggle.jar">
    Your browser does not support applets </applet>
    I understand those steps for a simple program like hello world but not my current app
    Heres my code on the 2 extend off my first GUI of the Loan Application
    public class AnalysisGUI extends GUI {
        /** Creates new form AnalysisGUI */
        public AnalysisGUI(java.awt.Frame parent, boolean modal) {
            super(parent, modal);
            initComponents();
        }//end constructor
        private DecimalFormat currency = new DecimalFormat("0.00");
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            analysisjButton = new javax.swing.JButton();
            jScrollPane1 = new javax.swing.JScrollPane();
            writejTextArea = new javax.swing.JTextArea();
            clearTextAreajButton = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
            analysisjButton.setText("Analysis");
            analysisjButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    analysisjButtonActionPerformed(evt);
            writejTextArea.setColumns(20);
            writejTextArea.setRows(5);
            jScrollPane1.setViewportView(writejTextArea);
            clearTextAreajButton.setText("Clear Analysis Output");
            clearTextAreajButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    clearTextAreajButtonActionPerformed(evt);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(analysisjButton)
                        .addComponent(clearTextAreajButton))
                    .addGap(18, 18, 18)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 433, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(86, 86, 86))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap(306, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(analysisjButton)
                            .addGap(84, 84, 84)
                            .addComponent(clearTextAreajButton)
                            .addGap(113, 113, 113))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 263, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(22, 22, 22))))
            java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-700)/2, (screenSize.height-627)/2, 700, 627);
        }// </editor-fold>
        private void analysisjButtonActionPerformed(java.awt.event.ActionEvent evt) {                                               
            // TODO add your handling code here:   
            //importing values for FOR loop of 13 pyaments a years
            ir13 = super.rate;
            balance13 = super.balance;
            time13 = super.time;
            payment13 = MortgageCalculator.CalculatePayment(ir13, balance13, time13, PayperYear13);           
            interest13 = round((balance13 * (ir13/PayperYear13)));                   
            principle13 = round(payment13 - interest13);
            //set up for 12 pyaments a year
            balance = super.balance;          
            ir = super.rate;
            time = super.time;         
            payment = super.payment;
            interest = round((balance * (ir/PayperYear12)));
            principle = round(payment - interest);
            //set up for 24 payments a year   
            balance24 = super.balance;          
            ir24 = super.rate;
            time24 = super.time;         
            payment24 = super.payment/2;
            interest24 = round((balance24 * (ir/PayperYear24)));
            principle24 = round(payment24 - interest24);
            //set up for 26 payemnts a years
            ir26 = super.rate;
            balance26 = super.balance;
            time26 = super.time;
            payment26 = MortgageCalculator.CalculatePayment(ir26, balance26, time26, PayperYear26);           
            interest26 = round((balance26 * (ir26/PayperYear26)));                   
            principle26 = round(payment26 - interest26);
         double totalPrinciple = 0;              //set to zero
         double totalInterest = 0;          //set to zero       
         for( int n = 0; n < time; n++)     //check Year of Loan
                totalPrinciple = 0;          //reset to zero for totaling Year n totals
                totalInterest = 0;          //reset to zero for totaling Year n totals
                writejTextArea.append("-----Based on 12 Payments Per Year-----\n");
                writejTextArea.append("          "+"          "+"Principle" + "    " +
                    "Interest"+ "    "+
                    "Balance"+"\n");            
                //loops through the monthly payments
                for(int i = 1; i <= PayperYear12; i++ )
                //Calculate applied amounts for chart to be printed
                interest = round((balance * ir)/PayperYear12);
                principle = round(payment - interest);
                balance = round(balance - principle);
                //total year end amounts
                totalPrinciple = totalPrinciple + principle;
                totalInterest = totalInterest + interest;
                writejTextArea.append("Payment " + i + " $" + currency.format(principle) + "     " +
                    currency.format(interest) + "      $" +
                    currency.format(balance)+"\n");     
                }//end for 12 payments per year
                //print 12 payments Totals          
                int yr = n + 1;
                writejTextArea.append("\n---Year " + yr + " Totals Based on 12 Payments Per Year---");
                writejTextArea.append("\nYear Total Principle: $" + currency.format(totalPrinciple));
                writejTextArea.append("\nYear Total Interest: $" + currency.format(totalInterest));
                writejTextArea.append("\nRemaining Balance: $" + currency.format(balance)+"\n");
                writejTextArea.append("\n-------------------------------------------------------\n");     
                //Start 13 PAYMENTS A YEAR TABLE
                double totalPrinciple13 = 0;          //reset to zero for totaling Year n totals
                double totalInterest13 = 0;          //reset to zero for totaling Year n totals
                writejTextArea.append("-----Based on 13 Payments Per Year-----\n");   
                writejTextArea.append("          "+"          "+"Principle" + "    " +
                    "Interest"+ "    "+
                    "Balance"+"\n");            
                //loops through the monthly 13 payments           
                for(int j = 1; j <= PayperYear13; j++ )
                //Calculate applied amounts for chart to be printed
                interest13 = round((balance13 * ir13)/PayperYear13);
                principle13 = round(payment13 - interest13);
                balance13 = round(balance13 - principle13);
                //total year end amounts
                totalPrinciple13 = totalPrinciple13 + principle13;
                totalInterest13 = totalInterest13 + interest13;
                //System.out.printf("\n%-10s %-10s %-10s %-10s %-10s", n + 1 , i + 1,Principle, Interest, Balance);
                //System.out.printf("\n%-10s %-10s %-10.2f %-10.2f %-10.2f", n + 1 , i + 1,round(principle), round(interest), balance);
                writejTextArea.append("Payment " + j + " $" + currency.format(principle13) + "     " +
                    currency.format(interest13) + "      $" +
                    currency.format(balance13)+"\n");         
                }//end for 13 payments per year
                //Print totals for 13 payments a year          
                yr = n + 1;
                writejTextArea.append("\n---Year " + yr + " Totals Based on 13 Payments Per Year---");
                writejTextArea.append("\nYear Total Principle: $" + currency.format(totalPrinciple13));
                writejTextArea.append("\nYear Total Interest: $" + currency.format(totalInterest13));
                writejTextArea.append("\nRemaining Balance: $" + currency.format(balance13)+"\n");
                writejTextArea.append("\n-------------------------------------------------------\n");             
                //Start 24 PAYMENTS A YEAR TABLE
                double totalPrinciple24 = 0;          //reset to zero for totaling Year n totals
                double totalInterest24 = 0;          //reset to zero for totaling Year n totals
                writejTextArea.append("-----Based on 24 Payments Per Year-----\n");
                writejTextArea.append("          "+"          "+"Principle" + "    " +
                    "Interest"+ "    "+
                    "Balance"+"\n");            
                //loops through the monthly payments
                for(int i = 1; i <= PayperYear24; i++ )
                //Calculate applied amounts for chart to be printed
                interest24 = round((balance24 * ir24)/PayperYear24);
                principle24 = round(payment24 - interest24);
                balance24 = round(balance24 - principle24);
                //total year end amounts
                totalPrinciple = totalPrinciple + principle24;
                totalInterest = totalInterest + interest24;
                writejTextArea.append("Payment " + i + " $" + currency.format(principle24) + "     " +
                    currency.format(interest24) + "      $" +
                    currency.format(balance24)+"\n"); 
                }//end for 24 payments per year
                //print 24 payments Totals
                yr = n +1;
                writejTextArea.append("\n---Year " + yr + " Totals Based on 24 Payments Per Year---");
                writejTextArea.append("\nYear Total Principle: $" + currency.format(totalPrinciple24));
                writejTextArea.append("\nYear Total Interest: $" + currency.format(totalInterest24));
                writejTextArea.append("\nRemaining Balance: $" + currency.format(balance24)+"\n");
                writejTextArea.append("\n-------------------------------------------------------\n");                        
                //Start 26 PAYMENTS A YEAR TABLE
                double totalPrinciple26 = 0;//reset to zero for totaling Year n totals
                double totalInterest26 = 0;     //reset to zero for totaling Year n totals
                writejTextArea.append("------Based on 26 Payments Per Year-----\n");
                writejTextArea.append("          "+"          "+"Principle" + "    " +
                    "Interest"+ "    "+
                    "Balance"+"\n");            
                //loops through the monthly payments 26 times
                for(int i = 1; i <= PayperYear26; i++ )
                //Calculate applied amounts for chart to be printed
                interest26 = round((balance26 * ir24)/PayperYear26);
                principle26 = round(payment26 - interest26);
                balance26 = round(balance26 - principle26);
                totalPrinciple = totalPrinciple + principle26;
                totalInterest = totalInterest + interest26;
                writejTextArea.append("Payment " + i + "  $" + currency.format(principle26) + "     " +
                    currency.format(interest26) + "      $" +
                    currency.format(balance26)+"\n");
                }//end for 26 payments per year           
                yr = n + 1;
                //prints 26 payments yearly totals
                writejTextArea.append("\n---Year " + yr + " Totals Based on 26 Payments Per Year---");
                writejTextArea.append("\nYear Total Principle: $" + currency.format(totalPrinciple26));
                writejTextArea.append("\nYear Total Interest: $" + currency.format(totalInterest26));
                writejTextArea.append("\nRemaining Balance: $" + currency.format(balance26)+"\n");
                writejTextArea.append("\n-------------------------------------------------------\n");                
            }//end for years of the loan
        private void clearTextAreajButtonActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            //clear analysis field
            writejTextArea.setText("");
        public static double round(double r)//round to cents method
              return Math.ceil(r*100)/100;
         }//end round  
        /**HI micha what a long progam
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    AnalysisGUI dialog = new AnalysisGUI(new javax.swing.JFrame(), true);
                    dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                        public void windowClosing(java.awt.event.WindowEvent e) {
                            System.exit(0);
                    dialog.setVisible(true);
            });//end announymous
        }//end main mehtod
        //12 year declared varialbes
        //private double balance;   
        private double principle;
        private double ir;
        private double interest;
        private double PayperYear12 = 12;
        //Variables for 13 payments a years
        private int PayperYear13 = 13;
        private double balance13;
        private double principle13;
        private double ir13;
        private double interest13;
        private double payment13;
        private double time13;
        //Varialbes for 24 payments a year
        private int PayperYear24 = 24;
        private double balance24;
        private double principle24;
        private double ir24;
        private double interest24;
        private double payment24;
        private double time24;
        //Varialbes for 24 payments a year
        private int PayperYear26 = 26;
        private double balance26;
        private double principle26;
        private double ir26;
        private double interest26;
        private double payment26;
        private double time26;
        // Variables declaration - do not modify
        private javax.swing.JButton analysisjButton;
        private javax.swing.JButton clearTextAreajButton;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTextArea writejTextArea;

    Your original program extends "GUI" which appears to extend JFrame (correct me if I'm wrong). If so, the first thing you should do would be to re-write this so that it extends JPanel which shouldn't be that hard to do (at least it's not hard to do if you know a little Swing -- but I worry about someone coming into this from the netbeans-generated code world). Purists will tell you to not even extend this, to have your main GUI class hold an instance of JPanel instead, and this would work fine too, as long as one way or another, the main GUI program can produce your application displayed on a JPanel on demand.
    If you've done this correctly, then using your JPanel in a JFrame is trivial: in a main method create a JFrame, and then simply add your JPanel to the JFrame's contentPane and display it. Likewise using your JPanel in a JApplet is just as trivial as you'd do essentially the same thing: add your JPanel to the JApplet's contentPane, but this time do it in the JApplet's init method.

  • Accessor methods

    Hello,
    I am working on a temp class that has 2 instance variables, double tempValue, and char tempScale ('C' or 'F').
    My constructor methods are working fine. My mutator (set) methods are working fine.
    I need to write two accessor methods, one that returns the temp in Fahrenheit, and one that returns the temp in Celsius.
    I am not sure how to return both the tempValue and the tempScale for both of these methods. Here is my starting point:
    //accessor method to return the degrees Fahrenheit.
    public double getF()
    return tempF;     //tempF = (9*(tempC)/5 + 32)
    //accessor method to return the degrees Celsius
    public double getC()
    return tempC;     //tempC = 5*(tempF - 32)/9
    }Thank you,
    Eric

    If possible, I would like to stick to the program I am working on. It is much easier for me to understand.
    Is there any way you can just use my program as the example?
    Here is what I have so far:
    public class TestTemp
    //Two parameters, a temperature value (a floating-point number)
    //and a character for the scale, either 'C' for Celsius or 'F'
    //for Fahrenheit.
    private double tempValue;     //in degrees
    private char tempScale;     //in either 'C' or 'F'     
    public void writeOutput()
    System.out.println("The temperature is " + (tempValue) + " degrees " + tempScale + ".");
    //Four constructor methods, one for each instance variable,
    //(assume zero degrees if no value isspecified and Celsius
    // if no scale is specified), one with two parameters for the
    //two instance variables, and a default constructor (set to
    //zero degreees Celsius.
    //constructor method for the instance variable tempValue
    public TestTemp(double initialTempValue)
    tempScale = 'C';
    if(initialTempValue < 0)
    System.out.println("Error:  Negative temperature value.");
    System.exit(0);
    else
    round(initialTempValue);
    tempValue = initialTempValue;
    //constructor method for the instance variable tempScale
    public TestTemp(char initialTempScale)
    tempValue = 0;
    initialTempScale = Character.toUpperCase(initialTempScale);
    if(initialTempScale == 'C' || initialTempScale == 'F')
    tempScale = initialTempScale;
    else
    System.out.println("Error:  Must be C or F.");
    System.exit(0);
    //constructor method for both instance variables tempValue and tempScale
    public TestTemp(double initialTempValue, char initialTempScale)
    if(initialTempValue < 0)
    System.out.println("Error:  Negative temperature value.");
    System.exit(0);
    else
    round(initialTempValue);
    tempValue = initialTempValue;
    initialTempScale = Character.toUpperCase(initialTempScale);
    if(initialTempScale == 'C' || initialTempScale == 'F')
    tempScale = initialTempScale;
    else
    System.out.println("Error:  Must be C or F.");
    System.exit(0);
    //default constructor method
    public TestTemp()
    tempValue = 0.0;
    tempScale = 'C';     
    //Two accessor (get) methods, one to return the degrees Celsius,
    //and one to return the degrees Fahrenheit.
    //Round to the nearest tenth of a degree.
    //accessor method to return the degrees Fahrenheit.
    public double getF()
    if(tempScale == 'F')
    System.out.println("Error:  The temp scale is already Fahrenheit.");
    return 0;
    else
    double tempF;
    tempF = ((9 * tempValue)/5 + 32);  //tempF = ((9*tempC)/5 + 32)
    tempValue = tempF;
    tempScale = 'F';
    round(tempValue);
    return tempF;          
    //accessor method to return the degrees Celsius
    public double getC()
    if(tempScale == 'C')
    System.out.println("Error:  The temp scale is already Celsius.");
    return 0;
    else
    double tempC;
    tempC = (5 * (tempValue - 32)/9);          //tempC = 5*(tempF - 32)/9
    tempValue = tempC;
    tempScale = 'C';
    round(tempValue);
    return tempC;     
    //round method returns the tempValue rounded to tenths
    public double round(double roundTempValue)
    tempValue = Math.round(tempValue * 10.0)/10.0;
    return tempValue;
    //Three reset methods, one to reset the value, one to reset the
    //scale ('F' or 'C'), and one to reset both the value and the scale.
    //reset method to reset tempValue
    public void set(double newTempValue)
    if(newTempValue < 0)
    System.out.println("Error:  Negative temperature value.");
    System.exit(0);
    else
    round(newTempValue);
    tempValue = newTempValue;
    //tempScale is unchanged
    //reset method to reset tempScale
    public void set(char newTempScale)
    newTempScale = Character.toUpperCase(newTempScale);
    if(newTempScale == 'C' || newTempScale == 'F')
    tempScale = newTempScale;
    else
    System.out.println("Error:  Must be C or F.");
    System.exit(0);
    //tempValue is unchanged
    //reset method to reset tempValue and tempScale
    public void set(double newTempValue, char newTempScale)
    if(newTempValue < 0)
    System.out.println("Error:  Negative temperature value.");
    System.exit(0);
    else
    round(newTempValue);
    tempValue = newTempValue;
    newTempScale = Character.toUpperCase(newTempScale);
    if(newTempScale == 'C' || newTempScale == 'F')
    tempScale = newTempScale;
    else
    System.out.println("Error:  Must be C or F.");
    System.exit(0);
    //tempValue and tempScale are reset
    //Driver program that tests all the methods.
    //Use each one of the constructors.
    //Include at least one true and one false
    //case for each of the comparison methods.
    //Test the following: 
    //          0.0 degrees C = 32 degrees F
    //          -40 degrees C = -40 degrees F
    //          100 degrees C = 212 degrees F     
    public class TestTempDriver
    public static void main(String[] args)
    //t1, t2, t3, and t4 test the four constructors
    TestTemp t1 = new TestTemp();
    t1.writeOutput();
    TestTemp t2 = new TestTemp(22.222);
    t2.writeOutput();
    TestTemp t3 = new TestTemp('f');
    t3.writeOutput();
    TestTemp t4 = new TestTemp(44.444, 'f');
    t4.writeOutput();
    //t5 tests the set method with both the double and char parameters
    TestTemp t5 = new TestTemp(55.555, 'f');
    System.out.println("The initial temp for t5 is:");
    t5.writeOutput();          
    System.out.println("Please enter the correct temp:");
    double correctTemp = SavitchIn.readLineDouble( );
    System.out.println("Please enter the correct temp scale:");
    char correctScale = SavitchIn.readLineNonwhiteChar( );
    t5.set(correctTemp, correctScale);
    System.out.println("The updated temp for t5 is:");
    t5.writeOutput();          
    //t6 tests the set method with the double parameter
    TestTemp t6 = new TestTemp(66.666, 'f');
    System.out.println("The initial temp for t6 is:");
    t6.writeOutput();
    System.out.println("Please enter the correct temp:");
    correctTemp = SavitchIn.readLineDouble( );
    t6.set(correctTemp);
    System.out.println("The updated temp for t6 is:");
    t6.writeOutput();
    //t7 tests the set method with the char parameter
    TestTemp t7 = new TestTemp(77.777, 'f');
    System.out.println("The initial temp for t7 is:");
    t7.writeOutput();
    System.out.println("Please enter the correct temp scale:");
    correctScale = SavitchIn.readLineNonwhiteChar( );
    t7.set(correctScale);
    System.out.println("The updated temp for t7 is:");
    t7.writeOutput();
    //t8 tests the getF accessor method
    TestTemp t8 = new TestTemp();     
    double convertTemp = 88.888;
    char convertScale = 'c';
    t8.set(convertTemp, convertScale);
    t8.getF();     
    t8.writeOutput();
    //t9 tests the getC accessor method
    TestTemp t9 = new TestTemp();
    convertTemp = 99.999;
    convertScale = 'f';
    t9.set(convertTemp, convertScale);
    t9.getC();     
    t9.writeOutput();
    }Thanks,
    Eric

  • Wayyyyyy too many jframes opening!!

    hi all! im having a bit of trouble with the application im currently working on. what is supposed to happen is the program reads a text file or the user can start typing in the textarea. if the text file or textarea contains a certain word, a new jframe opens with the word and the percentage of the words occurence in the text. fairly straight forward.. but..............................
    lets say some of these certain words are "happy" and "joy". id like them both to be written in the same jframe, but in my current code each word opens a new jframe...
    also.......
    if the text doesnt contain one of these words, 314 new jframes open. lol, i only wanted one saying the word wasnt found! please help!
    below is the code, im a beginner so apologies if its badly written!
    thanks for the help
    Torre
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.math.BigDecimal;
    import java.util.HashMap;
    import javax.swing.*;
    public class findtext extends JFrame implements ActionListener
    private JRadioButton english;
    private JRadioButton french;
    private String number;
    private JButton submit;
    private JButton back;
    private JButton fileButton;
    private  String[] words;
    private  int[] values;
    private int num;
    private HashMap <String, Integer> hashMap;
    final JTextArea textarea;
    private String content;
        public findtext() {
            // Call super class constructor
            super("Torre's Happy Program");
            // create the layout
            JPanel contentPane = (JPanel)getContentPane();
            int bGap = 40;
            contentPane.setBorder(BorderFactory.createEmptyBorder(bGap, bGap, bGap, bGap));
            int hvGap = 30;
            contentPane.setLayout(new BorderLayout(hvGap, hvGap));
            // create panel with text, add text to container
            JPanel textpanel = new JPanel();
            JLabel text = new JLabel("Now please enter your text, or browse for a text file to analyse.");
            textpanel.add(text);
            contentPane.add(textpanel, BorderLayout.NORTH);
            // create radio buttons
            textarea = new JTextArea(8,40);
            JScrollPane scroll = new JScrollPane();
            scroll.setViewportView(textarea);
            JPanel textareapanel = new JPanel();
            textpanel.add(textarea);
            contentPane.add(textareapanel, BorderLayout.CENTER);
            submit = new JButton("Submit");
            back = new JButton ("Back");
           fileButton = new JButton("Browse");
            submit.addActionListener(this);
            back.addActionListener(this);
            fileButton.addActionListener(this);
            JPanel buttonpanel = new JPanel();
            buttonpanel.add(fileButton);
            buttonpanel.add(submit);
            buttonpanel.add(back);
            contentPane.add(buttonpanel, BorderLayout.SOUTH);
        public void actionPerformed(ActionEvent evt)
             content = textarea.getText();
             if (evt.getSource() == submit && content.length() >= 1) {
                  words = new String[]{"happy", "joy", "joyous", "fun", "faith", "hope", "warmth", "love", "good", "trust"
                            ,"soul", "happiness", "embrace", "embraced", "friend", "friends", "radiate", "put"};
                  values = new int[] {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
                  hashMap = new HashMap <String, Integer>();
                  for (int i = 0; i < words.length; i++) {
                       hashMap.put(words, values[i]);}
              content = content.replaceAll("[^a-zA-Z0-9]", " "); // need to get rid of whitespaces!
              String [] temp = content.split(" ");
              for (int i = 0; i < temp.length; i++) {
                   //System.out.println(temp[i]); test that the words in file can print separately
                   if (hashMap.containsKey(temp[i])) {
                        num++;
                        //System.out.println("Number of happy words in the text: " + num);
                        int sum = temp.length; //total length of array
                        double b = sum;
                        double a = num;
                        double ab = round((a/b)*100, 2);
                        processText pt = new processText();
                        pt.setSize(600,300);
                   pt.setVisible(true);
                   pt.addtotextarea("The text is " + ab + "% happy. Happy words found: \n" + temp[i]);
                   setVisible(false);
                   dispose();
                   processText pt = new processText();
                        pt.setSize(600,300);
                   pt.setVisible(true);
                   pt.addtotextarea("There are no happy words in this text");
                   setVisible(false);
                   dispose();
         else if (evt.getSource() == submit && content.length() < 1) {
              JOptionPane.showMessageDialog(this, "Please type or browse for a text.");
         else if (evt.getSource()==back) {
              eng_main eng = new eng_main();
              eng.setVisible(true);
              eng.setSize(600,300);
              setVisible(false);
              dispose();
         else if (evt.getSource()== fileButton) {
              JFileChooser fileChooser = new JFileChooser();
              fileChooser.setCurrentDirectory(new File("."));
    int returnValue = fileChooser.showOpenDialog(null);
    if (returnValue == JFileChooser.APPROVE_OPTION) {
    File selectedFile = fileChooser.getSelectedFile();
    String file = selectedFile.getPath();
    BufferedReader in = null;
    textarea.setText("");
    try {
         in = new BufferedReader (new FileReader (file));
         String str;
         while ((str = in.readLine()) != null)
              textarea.setText(textarea.getText() + str + "\n");
         in.close();
    catch (FileNotFoundException e) {
         e.printStackTrace();
    catch (IOException e) {
         e.printStackTrace();
    public static double round(double val, int places) {
         long factor = (long)Math.pow(10,places);
         // Shift the decimal the correct number of places
         // to the right.
         val = val * factor;
         // Round to the nearest integer.
         long tmp = Math.round(val);
         // Shift the decimal the correct number of places
         // back to the left.
         return (double)tmp / factor;
    * Sole entry point to the class and application.
    * @param args Array of String arguments.
    public static void main(String[] args) {
    findtext mainFrame = new findtext();
    mainFrame.setSize(600,300);
    mainFrame.setVisible(true);

    hi, the processText class is just a new frame which displays the results.
    below is the code.
    thanks alot
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    public class processText extends JFrame implements ActionListener
    private JRadioButton english;
    private JRadioButton french;
    private String number;
    private JButton back;
    private JLabel maintext;
        public processText() {
            // Call super class constructor
            super("Torre's Happy Program");
            // create the layout
            JPanel contentPane = (JPanel)getContentPane();
            int bGap = 40;
            contentPane.setBorder(BorderFactory.createEmptyBorder(bGap, bGap, bGap, bGap));
            int hvGap = 30;
            contentPane.setLayout(new BorderLayout(hvGap, hvGap));
            // create panel with text, add text to container
            JPanel textpanel = new JPanel();
            JLabel text = new JLabel("Here are the results:");
            textpanel.add(text);
            contentPane.add(textpanel, BorderLayout.NORTH);
            // create radio buttons
            maintext = new JLabel();
            JPanel areapanel = new JPanel();
            areapanel.add(maintext);
            contentPane.add(areapanel, BorderLayout.CENTER);
            // now add a submit button to a panel, add panel to container
            back = new JButton("Back");
            back.addActionListener(this);
            JPanel buttonpanel = new JPanel();
            buttonpanel.add(back);
            contentPane.add(buttonpanel, BorderLayout.SOUTH);
              public void addtotextarea (String s)
                   maintext.setText(s);
              public void actionPerformed(ActionEvent evt)
                   if (evt.getSource() == back)   {
                        eng_main eng = new eng_main();
                      eng.setVisible(true);
                      eng.setSize(600,300);
                      setVisible(false);
                      dispose();
         * Sole entry point to the class and application.
         * @param args Array of String arguments.
        public static void main(String[] args) {
            processText mainFrame = new processText();
            mainFrame.setSize(600,300);
            mainFrame.setVisible(true);
    }

  • [code here]Need modification:Make my DrawPanel keep what I have paint

    Hi
    please try it first
    it's to draw some random shade on a JPanel
    I just want the DrawPanel keep the random shades when resize.....
    Thank you for your patience
    DrawFrame.java
    import javax.swing.*;
    import java.awt.*;
    public class DrawFrame extends JFrame {
      public static Shade[] shades;
      static {
        shades = new Shade[] {
            new CircleType(), new RectType(), new DiamondType()
      static InfoPanel ip = new InfoPanel();
      static DrawPanel dp = new DrawPanel();
      public DrawFrame() {
        JButton draw = new JButton("draw");
        Container cp = this.getContentPane();
        cp.add(new JLabel("Created by iooirrr on 2003.4.19~4.21 version 0.3"), BorderLayout.NORTH);
        JScrollPane dpjsp = new JScrollPane(dp);
        dpjsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        dpjsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        cp.add(dpjsp, BorderLayout.CENTER);
    ScrollPaneLayout spl = new ScrollPaneLayout();
        JScrollPane ipjsp = new JScrollPane(ip);
        ipjsp.setLayout(spl);
        ipjsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        ipjsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        cp.add(ipjsp, BorderLayout.WEST);
    String[] shadename = new String[shades.length];
        for (int i = 0; i < shades.length; i ++) {
          shadename[i] = shades.getName();
    ip.shadeList.setListData(shadename);
    Rectangle max = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
    this.setLocation(0, 0);
    this.setSize(max.width, max.height);
    this.show();
    public void make(Container cp, Component c, GridBagLayout gbl, GridBagConstraints gbc) {
    // gbc.fill = GridBagConstraints.BOTH;
    gbl.setConstraints(c, gbc);
    cp.add(new JScrollPane(c));
    public static void main(String[] parameters) {
    DrawFrame df = new DrawFrame();
    df.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
    DrawPanel.java
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    public class DrawPanel extends JPanel {
      JTextArea jTextArea1 = new JTextArea();
      public DrawPanel() {
        this.setSize(this.getMaximumSize());
        this.addMouseListener(new MouseListener() {
          public void mouseClicked(MouseEvent e) {
            drawExample();
          public void mousePressed(MouseEvent e) {
          public void mouseReleased(MouseEvent e) {
          public void mouseEntered(MouseEvent e) {
          public void mouseExited(MouseEvent e) {
      public void paint(Graphics g) {
        // super.paint(g);
        setOpaque(false);
      public Graphics returnGraphics() {
        return this.getGraphics();
      public void drawExample() {
        DrawFrame.ip.sumarea = 0;
        DrawFrame.ip.sumperi = 0;
        DrawFrame.ip.areaT.setText("");
        DrawFrame.ip.periT.setText("");
        Shade.serial = 0;
        for (int i = 0; i < DrawFrame.shades.length; i ++) {
          DrawFrame.shades.number = 0;
    this.getGraphics().clearRect(0, 0, this.getSize().width, this.getSize().height);
    InfoPanel.info.setText("");
    for(int i = 0; i < InfoPanel.shadeindex.size(); i ++) {
    try {
    Shade oneshade = DrawFrame.shades[Integer.parseInt(InfoPanel.shadeindex.elementAt(i).toString())].returnclass();
    oneshade.drawself(this.getGraphics(), this.getVisibleRect().width, this.getVisibleRect().height);
    DrawFrame.ip.sumarea += oneshade.returnArea();
    DrawFrame.ip.sumperi += oneshade.returnPeri();
    DrawFrame.ip.areaT.setText(String.valueOf(DrawFrame.ip.round(DrawFrame.ip.sumarea, 3)));
    DrawFrame.ip.periT.setText(String.valueOf(DrawFrame.ip.round(DrawFrame.ip.sumperi, 3)));
    } catch (Exception e) {
    System.out.println(e.toString());
    InfoPanel.java
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class InfoPanel extends JPanel {
      static JList shadeList = new JList();
      static JList typeList = new JList();
      static JTextField amountT = new JTextField(10);
      static JButton add = new JButton("add to");
      static JButton remove = new JButton("remove");
      static JButton draw = new JButton("draw");
      static Vector type = new Vector();
      static Vector shadeindex = new Vector(); // ??????????????shades????????
      static JTextField areaT = new JTextField(10);
      static JTextField periT = new JTextField(10);
      static JTextArea info = new JTextArea(10, 10);
      double sumarea;
      double sumperi;
      public InfoPanel() {
        // get information
        JLabel amountL = new JLabel("Enter the amount you want to draw: ");
        JLabel shadeL = new JLabel("The shade you can draw: ");
        shadeList.setVisibleRowCount(5);
        JLabel typeL = new JLabel("The type you want to draw: ");
        typeList.setVisibleRowCount(5);
        // result
        JLabel periL = new JLabel("all perimeters' sum are: ");
        periT.setEditable(false);
        JLabel areaL = new JLabel("all areas' sum are: ");
        areaT.setEditable(false);
        GridBagLayout gbl = new GridBagLayout();
        GridBagConstraints gbc = new GridBagConstraints();
        setLayout(gbl);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        make(amountL, gbl, gbc);
        make(amountT, gbl, gbc);
        gbc.insets = new Insets(10, 0, 0, 0);
        make(shadeL, gbl, gbc);
        gbc.insets = new Insets(0, 0, 0, 0);
        make(new JScrollPane(shadeList), gbl, gbc);
        make(add, gbl, gbc);
        make(typeL, gbl, gbc);
        make(new JScrollPane(typeList), gbl, gbc);
        make(remove, gbl, gbc);
        gbc.insets = new Insets(10, 0, 0, 0);
        make(draw, gbl, gbc);
        gbc.insets = new Insets(0, 0, 0, 0);
        make(areaL, gbl, gbc);
        make(areaT, gbl, gbc);
        make(periL, gbl, gbc);
        make(periT, gbl, gbc);
        make(new JLabel("Each shade's information list here:"), gbl, gbc);
        JScrollPane infojsp = new JScrollPane(info);
        infojsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        infojsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        make(infojsp, gbl, gbc);
        // amountT handle mouse entered event
        amountT.addMouseListener(new MouseListener() {
          public void mouseClicked(MouseEvent e) {
          public void mousePressed(MouseEvent e) {
          public void mouseReleased(MouseEvent e) {
          public void mouseEntered(MouseEvent e) {
            amountT.setText("");
            amountT.requestFocusInWindow(); // ??requestFocus()????????????
          public void mouseExited(MouseEvent e) {
    //  add(new JList(new String[]{"1", "2", "3"}));
        this.setSize(this.getPreferredSize());
        add.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            addtoType();
        remove.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            removeType();
        draw.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            draw();
      public void make(Component c, GridBagLayout gbl, GridBagConstraints gbc) {
        gbc.gridx = 0;
        gbl.setConstraints(c, gbc);
        add(c);
      public void addtoType() {
        int[] sindex = shadeList.getSelectedIndices();
        for(int i = 0; i < sindex.length; i ++) {
          if(type.indexOf(DrawFrame.shades[sindex].getName()) == -1) {
    type.addElement(DrawFrame.shades[sindex[i]].getName());
    shadeindex.addElement(String.valueOf(sindex[i]));
    typeList.setListData(type);
    typeList.updateUI();
    public void removeType() {
    int[] tindex = typeList.getSelectedIndices();
    String[] temp = new String[tindex.length];
    for(int i = 0; i < tindex.length; i ++) {
    temp[i] = type.elementAt(tindex[i]).toString();
    for(int i = 0; i < tindex.length; i ++) {
    type.removeElement(temp[i]);
    for(int i = 0; i < temp.length; i ++) {
    for(int j = 0; j < DrawFrame.shades.length; j ++) { // ??????????????????????????
    if (DrawFrame.shades[j].getName() == temp[i]) {
    shadeindex.removeElement(String.valueOf(j));
    typeList.setListData(type);
    typeList.updateUI();
    public void draw() {
    long starttime=System.currentTimeMillis(); // ????????????????????
    for (int i = 0; i < DrawFrame.shades.length; i ++) {
    DrawFrame.shades[i].number = 0;
    info.setText("");
    int amount;
    Shade.serial = 0;
    sumarea = 0;
    sumperi = 0;
    try {
    amount = Integer.parseInt(amountT.getText());
    } catch (Exception e) {
    amount = (int)((Math.random() + 1) * 10); //????????10-20??
    amountT.setText("Random produce an int: " + amount);
    if (type.size() == 0) { // ????????????????????
    for(int i = 0; i < DrawFrame.shades.length; i ++) {
    if(type.indexOf(DrawFrame.shades[i].getName()) == -1) {
    type.addElement(DrawFrame.shades[i].getName());
    shadeindex.addElement(String.valueOf(i));
    typeList.setListData(type);
    typeList.updateUI();
    Graphics g = DrawFrame.dp.getGraphics();
    g.clearRect(0, 0, DrawFrame.dp.getSize().width, DrawFrame.dp.getSize().height);
    info.append("Each shade Information:\n");
    for(int i = 0; i < amount; i ++) {
    try {
    Shade oneshade = DrawFrame.shades[Integer.parseInt(shadeindex.elementAt((int)(Math.random() * shadeindex.size())).toString())];
    oneshade.drawself(g, DrawFrame.dp.getVisibleRect().width, DrawFrame.dp.getVisibleRect().height);
    sumarea += oneshade.returnArea();
    sumperi += oneshade.returnPeri();
    oneshade.areaSum += oneshade.returnArea();
    oneshade.periSum += oneshade.returnPeri();
    } catch (Exception e) {
    System.out.println(e.toString());
    info.append("\n");
    info.append("Each Type Information:\n");
    for(int i = 0; i < shadeindex.size(); i ++) {
    Shade eachshade = DrawFrame.shades[Integer.parseInt(shadeindex.elementAt(i).toString())];
    String name = eachshade.getName();
    int eachsum = eachshade.number;
    info.append(eachsum + " " + name + "\n");
    info.append(" " + "sum area:" + round(eachshade.areaSum, 3) + "\n");
    info.append(" " + "sum peri:" + round(eachshade.periSum, 3) + "\n");
    for(int i = 0; i < type.size(); i ++) {
    try {
    Shade oneshade = DrawFrame.shades[Integer.parseInt(shadeindex.elementAt(i).toString())].returnclass();
    oneshade.drawself(g, this.getWidth(), this.getHeight());
    sumarea += oneshade.returnArea();
    sumperi += oneshade.returnPeri();
    } catch (Exception e) {
    System.out.println(e.toString());
    areaT.setText(String.valueOf(round(sumarea, 3)));
    periT.setText(String.valueOf(round(sumperi, 3)));
    long endtime=System.currentTimeMillis();
    long totaltimetaken=endtime-starttime;//time in milliseconds
    info.append("\n");
    info.append("Total time used: " + totaltimetaken + " Millis\n");
    public double round(double d, int deci) {
    double factor = Math.pow(10, deci);
    return (Math.round(factor * d))/factor;
    Shade.java
    import java.awt.*;
    public abstract class Shade {
      public double area;
      public double peri;
      static int serial;
      public int number;
      public double areaSum;
      public double periSum;
      abstract public String getName();
      abstract public void drawself(Graphics g, double dpwidth, double dpheight);
      abstract public double returnArea();
      abstract public double returnPeri();
      public Shade returnclass() {
        return this;
    }CircleType.java
    import java.awt.*;
    public class CircleType extends Shade {
      public double r; // ????10??20
      public String getName() {
        return "Circle";
      public void setR() {
        r = (Math.random() + 1) * 10;
      public double returnArea() {
        area = Math.PI * Math.pow(r, 2);
        return area;
      public double returnPeri() {
        peri = 2 * Math.PI * r;
        return peri;
      public void drawself(Graphics g, double dpwidth, double dpheight) {
        setR();
        int x = (int)(dpwidth * Math.random()); // DrawPanel ?????????? ????????????????????
        int y = (int)(dpheight * Math.random());
        if(x < 2 * r) {
          x += 2 * r;
        } else if ( dpwidth - x < 2 * r ) {
          x -= 2 * r;
        if(y < 2 * r) {
          y += 2 * r;
        } else if (- y + 2 * r < dpwidth) {
          y -= 2 * r;
        int width = (int)(2 * r);
        int height = (int)(2 * r);
        g.setColor(Color.blue);
        g.drawOval(x, y, (int)(2 * r), (int)(2 * r));
        g.drawString(String.valueOf(++serial), x + (int)r, y + (int)r);
        InfoPanel.info.append(serial + " is " + "No." + ++ number + " " + getName() + "\n" );
        InfoPanel.info.append("    " + "Area:" + DrawFrame.ip.round(returnArea(), 3) + "\n");
        InfoPanel.info.append("    " + "Peri:" + DrawFrame.ip.round(returnPeri(), 3) + "\n");
        // g.drawString("Area:" + returnArea() + ";" + "Peri:" + returnPeri(), x, y);
    }DiamondType.java
    import java.awt.*;
    public class DiamondType extends Shade {
      public double area;
      public double peri;
      public double w, h; // ??, ??
      public void setWH() {
        w = (Math.random() + 1) * 30;
        h = (Math.random() + 1) * 30;
      public String getName() {
        return "diamond";
      public void drawself(Graphics g, double dpwidth, double dpheight) {
        int x = (int)(dpwidth * Math.random()); // DrawPanel ?????????? ????????????????????
        int y = (int)(dpheight * Math.random());
        setWH();
        if(x < w) {
          x += w;
        } else if ( dpwidth - x < w ) {
          x -= w;
        if(y < h) {
          y += h;
        } else if (- y + h < dpwidth) {
          y -= h;
        g.setColor(Color.darkGray);
        g.drawPolygon(new int[] {x, (int)(x + w/2), (int)(x + w), (int)(x + w/2)}, new int[] {(int)(y + h/2), y, (int)(y + h/2), (int)(y + h)}, 4);
        g.drawString(String.valueOf(++serial), x + (int)(w/2), y + (int)(h/2));
        // g.drawString("iooi's diamond. area:" + returnArea() + ";" + "Peri:" + returnPeri(), x, y);
        InfoPanel.info.append(serial + " is " + "No." + ++ number + " " + getName() + "\n" );
        InfoPanel.info.append("    " + "Area:" + DrawFrame.ip.round(returnArea(), 3) + "\n");
        InfoPanel.info.append("    " + "Peri:" + DrawFrame.ip.round(returnPeri(), 3) + "\n");
      public double returnArea() {
        area = w * h;
        return area/2;
      public double returnPeri() {
        peri = 2 * (w + h);
        return peri * Math.sqrt(2) / 2;
    }RectType.java
    import java.awt.*;
    public class RectType extends Shade {
      public double w, h; // ??, ??
      public String getName() {
        return "Rect";
      public void setWH() {
        w = (Math.random() + 1) * 20;
        h = (Math.random() + 1) * 20;
      public double returnArea() {
        area = w * h;
        return area;
      public double returnPeri() {
        peri = 2 * (w + h);
        return peri;
      public void drawself(Graphics g, double dpwidth, double dpheight) {
        setWH();
        int x = (int)(dpwidth * Math.random()); // DrawPanel ?????????? ????????????????????
        int y = (int)(dpheight * Math.random());
        if(x < w) {
          x += w;
        } else if ( dpwidth - x < w ) {
          x -= w;
        if(y < h) {
          y += h;
        } else if (- y + h < dpwidth) {
          y -= h;
        g.setColor(Color.red);
        g.drawRect(x, y, (int)w, (int)h);
        g.drawString(String.valueOf(++serial), x + (int)(w/2), y + (int)(h/2));
        InfoPanel.info.append(serial + " is " + "No." + ++ number + " " + getName() + "\n" );
        InfoPanel.info.append("    " + "Area:" + DrawFrame.ip.round(returnArea(), 3) + "\n");
        InfoPanel.info.append("    " + "Peri:" + DrawFrame.ip.round(returnPeri(), 3) + "\n");
        // g.drawString("Area:" + returnArea() + ";" + "Peri:" + returnPeri(), x, y);

    I really don't want to look through all that code to see how you are doing your painting, I do have some pointers though:
    1) Your drawPanel extends JPanel, meaning you should override the paintComponent(Graphics g) and NOT the paint(Graphics g) method. Swing components use paint() to call paintBorder, paintChildren, and paintComponent. If you override the paint then try to use a border or add buttons to the panel then you won't get the correct results. paint() is used for AWT components.
    2) To try to answer your question, your paintComponent method should contain ALL YOUR DRAWING. You should not call getGraphics then use that to draw anything on your panel. One thing you can do is create an image the size of the panel, draw on the image wherever you want, then use paintComponent to draw that image.
    [You can create an image using component's createImage (width, height) command]
    [You would draw on the image buy using the Image getGraphics() method, then drawing on it however you do on any other graphics object]
    [You would draw the image to the panel in the paintComponent method using the Graphics g parameter and doing a g.drawImage(...)]

  • [Solved] Can't build svgalib

    On 2.6.30-ARCH I get this error compiling svgalib:
    make[1]: Entering directory `/tmp/yaourt-tmp-joe/aur-svgalib/svgalib/src/svgalib-1.9.25/lrmi-0.6m'
    cc -c -Wall -Wstrict-prototypes -fPIC -DPIC -I/include -I. -march=athlon-xp -mtune=athlon-xp -O3 -pipe -fomit-frame-pointer -o lrmi.o lrmi.c
    gtf/gtfcalc.c:67: error: static declaration of 'round' follows non-static declaration
    make[1]: *** [gtfcalc] Error 1
    make[1]: Leaving directory `/tmp/yaourt-tmp-joe/aur-svgalib/svgalib/src/svgalib-1.9.25/utils'
    make: *** [textutils] Error 2
    make: *** Waiting for unfinished jobs....
    cc -Wall -Wstrict-prototypes -fPIC -DPIC -I/include -I. -march=athlon-xp -mtune=athlon-xp -O3 -pipe -fomit-frame-pointer -o vbetest vbetest.c lrmi.o
    cc -Wall -Wstrict-prototypes -fPIC -DPIC -I/include -I. -march=athlon-xp -mtune=athlon-xp -O3 -pipe -fomit-frame-pointer -o mode3 mode3.c lrmi.o
    cc -Wall -Wstrict-prototypes -fPIC -DPIC -I/include -I. -march=athlon-xp -mtune=athlon-xp -O3 -pipe -fomit-frame-pointer -o vga_reset vga_reset.c lrmi.o
    cc -Wall -Wstrict-prototypes -fPIC -DPIC -I/include -I. -march=athlon-xp -mtune=athlon-xp -O3 -pipe -fomit-frame-pointer -o vbemodeinfo vbemodeinfo.c lrmi.o
    cc -Wall -Wstrict-prototypes -fPIC -DPIC -I/include -I. -march=athlon-xp -mtune=athlon-xp -O3 -pipe -fomit-frame-pointer -o dosint dosint.c lrmi.o
    dosint.c:10: warning: function declaration isn't a prototype
    dosint.c: In function 'main':
    dosint.c:51: warning: control reaches end of non-void function
    make[1]: Leaving directory `/tmp/yaourt-tmp-joe/aur-svgalib/svgalib/src/svgalib-1.9.25/lrmi-0.6m'
    ==> ERROR: Build Failed.
    Please help. Thanks.
    Last edited by slyson (2009-07-16 17:54:07)

    Patch:
    --- svgalib-1.9.25/utils/gtf/gtfcalc.c
    +++ svgalib-1.9.25/utils/gtf/gtfcalc.c
    @@ -68,5 +68,5 @@
    -static double round(double v)
    +double round(double v)
    return floor(v + 0.5);
    Save this patch somewhere in the PKGBUILD directory of abs/yaourt-tmp, then point the patch line in the PKGBUILD to the file.
    Then makepkg -sef in the PKGBUILD directory.
    Last edited by slyson (2009-07-16 18:07:27)

  • 2 Decimal Places (that's all)

    My output from my calculations is:
    2.74594
    1.343434343434
    14.4758395065893849
    How can I limit my digits after the decimal point to only 2 places?
    Above answers would be:
    2.74
    1.34
    14.47
    Would appreciate any help.

    Well your code does exactly what you say it will ;-)
    It truncates the number to just 2 places.
    But if you want to get the "standard" behaviour of ROUND_HALF_UP then you should use Math.round(), as can be seen in the following.for (int i = 0; i < 100; i++) {
      double d = 2.74594 * i;
      double d2 = d;
      double d3 = d;
      //this code truncates to 2 decimal places
      d2 = d > 0 ? Math.floor(d * 100) / 100.0 : Math.ceil(d * 100) / 100.0;
      d3 = Math.round(d * 100) / 100.0;
      System.out.println("d = " + d + "\td2 = " + d2 + "\td3 = " + d3);
    }I usually leave doubles at their default precision until I need to presist or present them(to a db for instance), and then I use a class along the following lines...class Formatter {
      public static final int DEFAULT_PRECISION = 2;
      public static final String DEFAULT_PATTERN = "#.00";
      public static final String ZEROS = "0000000000000000";
      public static String convertDoubleToString(Double d) {
        return convertDoubleToString(round(d, DEFAULT_PRECISION), DEFAULT_PATTERN);
      public static String convertDoubleToString(double d) {
        return convertDoubleToString(round(d, DEFAULT_PRECISION), DEFAULT_PATTERN);
      public static String convertDoubleToString(Double d, int precision) {
        return convertDoubleToString(round(d, precision), "#." + ZEROS.substring(precision));
      public static String convertDoubleToString(double d, int precision) {
        return convertDoubleToString(round(d, precision), "#." + ZEROS.substring(precision));
      public static String convertDoubleToString(Double d, String pattern) {
        return new DecimalFormat(pattern).format(d.doubleValue());
      public static String convertDoubleToString(double d, String pattern) {
        return new DecimalFormat(pattern).format(d);
      private static final double round(Double d, int precision) {
        double factor = Math.pow(10, precision);
        return Math.round((d.doubleValue() * factor)) / factor;
      private static final double round(double d, int precision) {
        double factor = Math.pow(10, precision);
        return Math.round((d * factor)) / factor;
    }

Maybe you are looking for

  • Help Needed in At selection screen output

    Hi Experts, I need your help in AT SELECTION SCREEN OUTPUT event. My issue is i have 4 radio button and with each radio button couple of parameters that need to be filled in selection screen of report. My requirement is that sometimes user enters det

  • How to create a view for all Service Requests that are not approved by reviewer

    Hallo, I want to create a view in the Service Requests library that shows all SRs that are not approved. How to configure condition that says: if a SR has related Review Activity which is In Progress, show that SRs? I couldn't find this when creating

  • Posting Period error in delivery document

    Following data in OMSY Screen Co Cd     Company     Year   Pe     Fyr     LM     Fyr     LM 9001     L                   2007   3     2007     2     2006     12 Following data in MMRV Screen Company Code    9001   L Current period                03 2

  • I cant sync songs on a new computer because it'll replace my ipod with only the songs on that itunes

    Every time I try to sync my music, it says itunes will replace ipod contents with contents from itunes library but i have alot of songs on there so I don't want to lose them.  I do have a new computer but my old one is dead so I can't do that "home s

  • Calling custom Infotype method from Webdynpro Abap

    Hi Experts, I am working on an application where i need to call a method of a custom defined infotype. I have done this --> 1. Create a custom infotype 9111 2. SAP creates a class of that infotype ZCL_HRPA_INFOTYPE_9111 3. Inside this method there ar