Solved

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

Posted on 2006-11-20
11
185 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
> 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
Comment Utility
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
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 

Author Comment

by:duta
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Dear objects:

Thanks a lot!

I will try your tip and come back.

Thanks again!

duta
0
 

Author Comment

by:duta
Comment Utility
Thank you so much, objects.

duta
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

772 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

12 Experts available now in Live!

Get 1:1 Help Now