Solved

Java Swing:  (1) How to put a title and (2) a little mess with If statements

Posted on 2006-11-20
11
188 Views
Last Modified: 2013-11-23
Hi experts!

I am writing a simple code to calculate phone bill in which clients get discounts (10% each for senior citizeins (over 60) and another 10% for subcribers of 3 years or longer).

What I would like to get your help with are:

1. To put a title

2. To make if statements (toward the end of the code) work properly.

I've never used that many multiple if statements and they are a little overwhelming for me. I hope that there is a better, simple way to do the job.

Hope you experts may help me again.

Thanks a lot!

duta

_______________________ My Code _______________________________________


import javax.swing.JOptionPane;
import java.text.DecimalFormat;
import java.util.regex.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class Age extends JApplet
{
 // private JList planList;
  private JComboBox planList = new JComboBox(new Object[]
                               { "Unlimited Plan", "300 Anytime Minutes" });
 
 
  private JComboBox ageList = new JComboBox(new Object[] { "60 or older", "Below 60" });
 
  private JPanel Plength;
  private JPanel Pname;
  private JPanel Pusage;
  private JPanel Ptotal;
  private JPanel Pbutton;
 
 
  private JTextField Flength;
  private JTextField Fname;
  private JTextField Fusage;
  private JTextField Ftotal;
  private Container c = getContentPane ( );
 
 
  JComboBox plans = new JComboBox(new Object[]      { "Unlimited Plan", "300 Anytime Minutes" });
  JComboBox age = new JComboBox(new Object[] { "60 or older", "Below 60" });
 
  public void init ( )
  {
   
    // Methods to build the panels
    buildLength ();
    buildPlan ();
    buildAge ();
    buildName ();
    buildUsage ();
    buildTotal ();
    buildButton ();
   
    // Create a layout manager
    setLayout ( new GridLayout (7, 1 ) );
   
    // Add the panels to the content pane
    add (Plength);
    add ( Pname);
    add ( planList );
    add ( ageList );
    add ( Pusage);
    add ( Ptotal );
    add ( Pbutton );
  }
 
  private void buildPlan ()
  {
      plans.setSelectedIndex (0);
  }
 
  private void buildAge ()
  {
      age.setSelectedIndex (0);
  }
 
 
  private void buildLength ()
  {
    Plength         = new JPanel ( );
    JLabel message5 = new JLabel ("Length of Subscription : " );
    Flength          =  new JTextField ( 20 );
   
    Plength.setLayout ( new FlowLayout ( FlowLayout.RIGHT ) );
    Plength.add (message5);
    Plength.add ( Flength );
  }
 
  private void buildName ()
  {
    Pname           = new JPanel ( );
    JLabel message1 = new JLabel ("Your Name : " );
    Fname           =  new JTextField ( 20 );
   
    Pname.setLayout ( new FlowLayout ( FlowLayout.RIGHT ) );
    Pname.add (message1);
    Pname.add ( Fname );
  }
 
  private void buildUsage ()
  {
    Pusage          = new JPanel ( );
    JLabel message2 = new JLabel ("Your Anytime Usage : " );
    Fusage          =  new JTextField ( 20 );
   
    Pusage.setLayout ( new FlowLayout ( FlowLayout.RIGHT ) );
    Pusage.add (message2);
    Pusage.add ( Fusage );
  }
 
  private void buildTotal ()
  {
    Ptotal          = new JPanel ( );
    JLabel message3 = new JLabel ("Your Total Charge: " );
    Ftotal          =  new JTextField ( 20 );
    Ftotal.setEditable ( false );
   
    Ptotal.setLayout ( new FlowLayout ( FlowLayout.RIGHT ) );
    Ptotal.add (message3);
    Ptotal.add ( Ftotal );
  }
 
 private void buildButton ()
  {
    Pbutton = new JPanel ( );
    JButton calcButton = new JButton ( "Calculate");
    calcButton.addActionListener ( new ButtonListener ( ) );
    Pbutton.add ( calcButton );
  }
 
 // Private inner class that andles the action event that is generated
 // when the user clicks "Calculate" button.
 
 
 private class ButtonListener implements ActionListener
 {
   public void actionPerformed ( ActionEvent e )
   {
     String name   = " ";
     int mins_used = 0;
     int plan      = 0;
     float total   = 0.0f;
     int age       = 0;
     int length    = 0;
     name = Fname.getText ();
     final float SENIOR_DISCOUNT = 0.9f;
     final float LENGTH_DISCOUNT = 0.9f; // gets 10% discount
     try
     {
          mins_used = Integer.parseInt (Fusage.getText () );
 
          plan = planList.getSelectedIndex ();
          length = Integer.parseInt (Flength.getText () );
          age  = ageList.getSelectedIndex ();
         
  // plan 1: Unlimited airtime
  // plan 2: 300 anytime minutes a month
  // age  1: Over 60 in age: gets 10% discount
  // age  2: Below 60 in age
  // length : Clients who subscribed this phone company for 3 years or longer gets 10% discount
     
           if (plan==0 )
           {      
              if (age ==0)   // Over 60
               {
                      if (mins_used <= 300 )
                      {
                             total = (length > 3) ? LENGTH_DISCOUNT * SENIOR_DISCOUNT *39.99f
                                        : 39.99f * SENIOR_DISCOUNT;
                             Ftotal.setText (""+total);
                      }
                      else
                      {
                           total = (length > 3) ? LENGTH_DISCOUNT * SENIOR_DISCOUNT * ( 39.99f + ((mins_used - 300) * 0.45f) ):
                                           SENIOR_DISCOUNT * ( 39.99f + ((mins_used - 300) * 0.45f) );
                           Ftotal.setText (""+total);
                       }
               }
             else if (age ==1)
               {
                     if (mins_used <= 300 )
                      {
                            total = (length > 3) ? LENGTH_DISCOUNT *39.99f : 39.99f;
                            Ftotal.setText (""+total);
                      }
                     else
                      {
                             total =  (length > 3) ? LENGTH_DISCOUNT *(39.99f + ((mins_used - 300) * 0.45f)):
                                                39.99f + ((mins_used - 300) * 0.45f);
                             Ftotal.setText (""+total);
                      }
             
             }
             
          else      
           {
                    total = 69.99f;
                    Ftotal.setText (""+total);
            }
   
       }
     }
     catch(NumberFormatException nfe)
     {
          Ftotal.setText ("Please enter an integer by usage.");
     }
         
    }
 }
}    

0
Comment
Question by:duta
  • 5
  • 3
  • 2
11 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 17983663
You can rationalize somewhat by using

switch(age) {
    case: 1
        // do something
        break;
    case: 2
        // do something else
        break;
}
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17983670
But sometimes you just get into this situation. After simplifying the logic as much as possible, often a rules tree is used in these situations.

http://java.sun.com/developer/technicalArticles/J2SE/JavaRule.html
0
 

Author Comment

by:duta
ID: 17983817
CEHJ, thank you so much for your kind, prompt response.

May I use nested switch?  Thanks!

for example:

switch (age)
{
case  1:
       switch  (plan)
       {
          case 1:
             switch (length)
                 {
                    case 1: if (mins_used <= 300 )
                      {
                            total = (length > 3) ? LENGTH_DISCOUNT *39.99f : 39.99f;
                            Ftotal.setText (""+total);
                      }
0
 
LVL 92

Accepted Solution

by:
objects earned 500 total points
ID: 17984174
> May I use nested switch?  Thanks!

switch is just a glorified if statement :) And doesn't really help much forthis type of p[roblem

you're overcompicating the problem, calculate the total based on the plan, anmd then apply any discounts applicable

total = getTotal(plan, mins_used);
if (age==0) total *= SENIOR_DISCOUNT;
if (length>3) total += LENGTH_DISCOUNT;
0
 
LVL 92

Expert Comment

by:objects
ID: 17984194
getTotal would look something like:


public double getTotal(int plan, int mins_used)
{
   double total = 69.99;
   if (plan==0) {
      total = 39.99;
      mins_used -= 300;
      if (mins_used>) {
         total += (mins_used * 0.45);
      }
   }
   return total;
}
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:duta
ID: 17984209
objects, thank you so much for your kind, prompt response.

I will take time to try your tip and will come back to you with feedback.

I 've got to leave now for some workout (after spending all day with Java code) :)


Thanks again!

duta
0
 

Author Comment

by:duta
ID: 17987413
TO: objects:

Hi again, I read your tips over and again.

I just wonder how I may use your code where I want to use: private class ButtonListener implements ActionListener
 {
   public void actionPerformed ( ActionEvent e )
   {

I am not sure how I may use parameters in a ActionPerformed method in Java Swing.

Thanks again!

duta
0
 
LVL 92

Expert Comment

by:objects
ID: 17990284
same way u are already

   public void actionPerformed ( ActionEvent e )
   {
       ...
       double total = getTotal(plan, mins_used);
       if (age==0) total *= SENIOR_DISCOUNT;
       if (length>3) total += LENGTH_DISCOUNT;
       ...
0
 

Author Comment

by:duta
ID: 17990370
Dear objects:

Thanks a lot!

I will try your tip and come back.

Thanks again!

duta
0
 

Author Comment

by:duta
ID: 18313846
Thank you so much, objects.

duta
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

27 Experts available now in Live!

Get 1:1 Help Now