Solved

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

Posted on 2006-11-20
11
189 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
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 
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
 

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

Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Protect jar file - windows app 2 53
JavaScript/Java - Changing an image background color 4 67
type mismatch (Object[] to double[] 4 24
Android development question 2 37
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
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:

809 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