Results 1 to 8 of 8
  1. #1
    intrepid604 is offline Member
    Join Date
    Feb 2011
    Posts
    9
    Rep Power
    0

    Question looking for OO advice

    I'm trying to teach myself Java and I'm trying to do my best at keeping everything OO where I can.

    The program below is meant to do the following exercise:

    (Creating an investment-value calculator) Write a program that calculates the future value of an investment at a given interest rate for a specified number of years. **note: I have the formula to implement this, but I'm concerned that my code below is getting off the OO-track, especially at the inner class called "CalcListener" below (see my comment there--it seems like it would be wasteful to copy and paste for each case (as there will be 4 fields)):

    Java Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class Q165 extends JFrame {
    	JLabel investment = new JLabel("Investment Amount:");
    	JLabel years = new JLabel("Years:");
    	JLabel interest = new JLabel("Annual Interest Rate: ");
    	JLabel fValue = new JLabel("Future Value: ");
    	
    	JTextField investmentInput = new JTextField();
    	JTextField yearsInput = new JTextField();
    	JTextField interestInput = new JTextField();
    	JTextField fValueOutput = new JTextField();
    	
    	Q165() 
    	{
    		setLayout(new BorderLayout());
    		addTextFields();
    		addButtonFields();
    		
    	}
    	
    	protected void addTextFields()
    	{
    		JPanel upper = new JPanel();
    		upper.setLayout(new GridLayout(5,2));
    		
    		upper.add(investment);
    		upper.add(investmentInput);
    		
    		upper.add(years);
    		upper.add(yearsInput); 
    		
    		upper.add(interest);
    		upper.add(interestInput);
    		
    		upper.add(fValue);
    		upper.add(fValueOutput);
    	
    		add(upper, BorderLayout.NORTH);
    	}
    	
    	protected void addButtonFields()
    	{
    		JPanel lower = new JPanel();
    		lower.setLayout(new BorderLayout());
    		JButton calculate = new JButton("calculate");
    		lower.add(calculate, BorderLayout.EAST);
    		//lower.setSize(width, height)
    		add(lower, BorderLayout.SOUTH);
    		
    		//register the listener
    		calculate.addActionListener(new CalcListener());
    	}
    	
    	private class CalcListener implements ActionListener 
    	{
    		public void actionPerformed(ActionEvent e) throws InvalidInputException
    		{	
    			//check if the inputs are numeric (should I repeat this for each field? or is there a way to make it so that this applies to all fields?)
    			try
    			{
    				if(isInteger(investmentInput.getText()))
    				{
    					int investmentAmt = Integer.parseInt(investmentInput.getText());
    				}
    				else throw new InvalidInputException("this is invalid, sir!");
    			}
    			catch(InvalidInputException iIE)
    			{
    				investmentInput.setText("invalid input, try again");
    			}
    		}
    	}
    	
    	public boolean isInteger(String s)
    	{
    		try
    		{
    			Integer.parseInt(investmentInput.getText());
    			return true;
    		}
    		catch(Exception e)
    		{
    			return false;
    		}
    	}
    	
    	public static void main(String[] args) {
    		Q165 frame = new Q165();
    		frame.setSize(400, 200);
    		frame.setLocationRelativeTo(null);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setVisible(true);
    	}
    }
    thanks for any suggestions!! :):confused:

  2. #2
    Debugger is offline Member
    Join Date
    Jan 2011
    Posts
    27
    Rep Power
    0

    Default

    Well this is my thought, i may be mistaken, but what i think is there should be a class called say "Investment" this is where you want your constructors, and overriding constructors so that in the main program you may instantiate on investment, and pass it the variables that the user inputs, and write getters and setters.

    So say the main program has the GUI, and the user puts in that the interest rate is 5% and the number of years is ten. Then when they hit calculate a new object is created by calling

    Investment myInvestment( intrestRate, numOfYears);

    Then you use myInvestment.getSomeValue();
    where getSomeValue is the method in the Investment class that does the calculating you need.

  3. #3
    intrepid604 is offline Member
    Join Date
    Feb 2011
    Posts
    9
    Rep Power
    0

    Default

    Ok, thank you, I've implemented your suggestion as a method in the inner class called getValue() which takes three doubles.

    My problem is that I think it's still not very OO--there are still 3 separate try-catch blocks. I think there must be a way to make all of those into one function. I'm just not seeing it.

    Revised code below:

    Java Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class Q165 extends JFrame {
    	JLabel investment = new JLabel("Investment Amount:");
    	JLabel years = new JLabel("Years:");
    	JLabel interest = new JLabel("Annual Interest Rate: ");
    	JLabel fValue = new JLabel("Future Value: ");
    	
    	JTextField investmentInput = new JTextField();
    	JTextField yearsInput = new JTextField();
    	JTextField interestInput = new JTextField();
    	JTextField fValueOutput = new JTextField();
    	
    	Q165() 
    	{
    		setLayout(new BorderLayout());
    		addTextFields();
    		addButtonFields();
    		
    	}
    	
    	protected void addTextFields()
    	{
    		JPanel upper = new JPanel();
    		upper.setLayout(new GridLayout(5,2));
    		
    		upper.add(investment);
    		upper.add(investmentInput);
    		
    		upper.add(years);
    		upper.add(yearsInput); 
    		
    		upper.add(interest);
    		upper.add(interestInput);
    		
    		upper.add(fValue);
    		upper.add(fValueOutput);
    	
    		add(upper, BorderLayout.NORTH);
    	}
    	
    	protected void addButtonFields()
    	{
    		JPanel lower = new JPanel();
    		lower.setLayout(new BorderLayout());
    		JButton calculate = new JButton("calculate");
    		lower.add(calculate, BorderLayout.EAST);
    		//lower.setSize(width, height)
    		add(lower, BorderLayout.SOUTH);
    		
    		//register the listener
    		calculate.addActionListener(new CalcListener());
    	}
    	
    	private class CalcListener implements ActionListener 
    	{
    		double investmentAmt = 0;
    		double yearsAmt = 0;
    		double interestAmt = 0;
    		
    		
    		public void actionPerformed(ActionEvent e) throws InvalidInputException
    		{	
    			//check if the inputs are numeric (should I repeat this for each field? or is there a way to make it so that this applies to all fields?)
    			try
    			{
    				if(isDouble(investmentInput.getText()))
    				{
    					investmentAmt = Double.parseDouble(investmentInput.getText());
    				}
    				else throw new InvalidInputException("this is invalid, sir!");
    			}
    			catch(InvalidInputException iIE)
    			{
    				investmentInput.setText("invalid input, try again");
    			}
    			//////////////////
    			try
    			{
    				if(isDouble(yearsInput.getText()))
    				{
    					yearsAmt = Double.parseDouble(yearsInput.getText());
    				}
    				else throw new InvalidInputException("this is invalid, sir!");
    			}
    			catch(InvalidInputException iIE)
    			{
    				yearsInput.setText("invalid input, try again");
    			}
    			///////////////////
    			try
    			{
    				if(isDouble(interestInput.getText()))
    				{
    					interestAmt = Double.parseDouble(interestInput.getText());
    				}
    				else throw new InvalidInputException("this is invalid, sir!");
    			}
    			catch(InvalidInputException iIE)
    			{
    				interestInput.setText("invalid input, try again");
    			}
    			////////////////////
    			
    			double fValue = getValue(investmentAmt, yearsAmt, interestAmt);
    			fValueOutput.setText(Double.toString(fValue));
    		}
    		
    	
    		public double getValue(double investmentAmt, double yearsAmt, double interestAmt)
    		{
    			double futureValue = investmentAmt * Math.pow((1 + interestAmt), (yearsAmt * 12));
    			return futureValue;
    		}
    	}
    	
    	public boolean isDouble(String s)
    	{
    		try
    		{
    			Double.parseDouble(investmentInput.getText());
    			return true;
    		}
    		catch(Exception e)
    		{
    			return false;
    		}
    	}
    	
    	public static void main(String[] args) {
    		Q165 frame = new Q165();
    		frame.setSize(400, 200);
    		frame.setLocationRelativeTo(null);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setVisible(true);
    	}
    }

  4. #4
    Petr's Avatar
    Petr is offline Senior Member
    Join Date
    Jan 2011
    Location
    Russia
    Posts
    618
    Rep Power
    4

    Default

    Well you need separate code on the logical party and gui party and you need use MVC pattern. because now all code is mix. if you will want change only gui or formula you need change all code. It is bad.
    Skype: petrarsentev
    http://TrackStudio.com

  5. #5
    Debugger is offline Member
    Join Date
    Jan 2011
    Posts
    27
    Rep Power
    0

    Default

    you can combine them all into one try

    try{
    if(this)
    do this //parse
    if(this)
    do this//parse
    }
    then if all the if's do not pass catch the exception

  6. #6
    intrepid604 is offline Member
    Join Date
    Feb 2011
    Posts
    9
    Rep Power
    0

    Default

    Thanks Debugger. That reduced my number of lines and made it more efficient!

    Petr, I'm curious what you mean by your post. I looked up the MVC pattern online and it looks like the OO approach that I should use... but how would you suggest I implement that?

    I understand the theory, but I'm not sure where to begin..

    Java Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class Q165 extends JFrame {
    	JLabel investment = new JLabel("Investment Amount:");
    	JLabel years = new JLabel("Years:");
    	JLabel interest = new JLabel("Annual Interest Rate: ");
    	JLabel fValue = new JLabel("Future Value: ");
    	
    	JTextField investmentInput = new JTextField();
    	JTextField yearsInput = new JTextField();
    	JTextField interestInput = new JTextField();
    	JTextField fValueOutput = new JTextField();
    	
    	Q165() 
    	{
    		setLayout(new BorderLayout());
    		addTextFields();
    		addButtonFields();
    		
    	}
    	
    	protected void addTextFields()
    	{
    		JPanel upper = new JPanel();
    		upper.setLayout(new GridLayout(5,2));
    		
    		upper.add(investment);
    		upper.add(investmentInput);
    		
    		upper.add(years);
    		upper.add(yearsInput); 
    		
    		upper.add(interest);
    		upper.add(interestInput);
    		
    		upper.add(fValue);
    		upper.add(fValueOutput);
    	
    		add(upper, BorderLayout.NORTH);
    	}
    	
    	protected void addButtonFields()
    	{
    		JPanel lower = new JPanel();
    		lower.setLayout(new BorderLayout());
    		JButton calculate = new JButton("calculate");
    		lower.add(calculate, BorderLayout.EAST);
    		//lower.setSize(width, height)
    		add(lower, BorderLayout.SOUTH);
    		
    		//register the listener
    		calculate.addActionListener(new CalcListener());
    	}
    	
    	private class CalcListener implements ActionListener 
    	{
    		double investmentAmt = 0;
    		double yearsAmt = 0;
    		double interestAmt = 0;
    		
    		
    		public void actionPerformed(ActionEvent e) throws InvalidInputException
    		{	
    			//check if the inputs are numeric (should I repeat this for each field? or is there a way to make it so that this applies to all fields?)
    			try
    			{
    				if(isDouble(investmentInput.getText()))
    				{
    					investmentAmt = Double.parseDouble(investmentInput.getText());
    				}
    				else throw new InvalidInputException("this is invalid, sir!");
    				
    				if(isDouble(yearsInput.getText()))
    				{
    					yearsAmt = Double.parseDouble(yearsInput.getText());
    				}
    				else throw new InvalidInputException("this is invalid, sir!");
    				
    				if(isDouble(interestInput.getText()))
    				{
    					interestAmt = Double.parseDouble(interestInput.getText());
    				}
    				else throw new InvalidInputException("this is invalid, sir!");
    			}
    			
    			catch(InvalidInputException iIE)
    			{
    				fValueOutput.setText("invalid input, try again");
    			}
    			
    			double fValue = getValue(investmentAmt, yearsAmt, interestAmt);
    			fValueOutput.setText(Double.toString(fValue));
    		}
    		
    	
    		public double getValue(double investmentAmt, double yearsAmt, double interestAmt)
    		{
    			double futureValue = investmentAmt * Math.pow((1 + interestAmt), (yearsAmt * 12));
    			return futureValue;
    		}
    	}
    	
    	public boolean isDouble(String s)
    	{
    		try
    		{
    			Double.parseDouble(investmentInput.getText());
    			return true;
    		}
    		catch(Exception e)
    		{
    			return false;
    		}
    	}
    	
    	public static void main(String[] args) {
    		Q165 frame = new Q165();
    		frame.setSize(400, 200);
    		frame.setLocationRelativeTo(null);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setVisible(true);
    	}
    }
    Last edited by intrepid604; 02-15-2011 at 08:35 PM. Reason: add code

  7. #7
    milovan is offline Senior Member
    Join Date
    Jan 2011
    Location
    Belgrade, Serbia
    Posts
    301
    Rep Power
    4

    Default

    In this situation I would use something like

    Java Code:
    try{
        investmentAmt = getDouble(investmentInput.getText());
        yearsAmt = getDouble(yearsInput.getText());
        interestAmt = getDouble(interestInput.getText());
    }
    catch(Exception e){
        fValueOutput.setText("invalid input, try again");
    }

    And my method getDouble() would looks like:

    Java Code:
    public double getDouble(String s){
        double n = Double.parseDouble(s);
        return n;
    }

  8. #8
    Petr's Avatar
    Petr is offline Senior Member
    Join Date
    Jan 2011
    Location
    Russia
    Posts
    618
    Rep Power
    4

    Default

    I'm curious what you mean by your post.
    I will try explain, You said that you use OO approach, but Java is OOP, you will not able to write another way.
    OO approach - this approach,which use follows concepts :
    Objects
    Encapsulation
    Class and Inheritance
    Instances and Instantiation
    Methods and Messages
    there are all.
    I advice you use Design Patterns as look like Builder and MVC pattern.
    see Design Patterns - Wikipedia, the free encyclopedia
    Skype: petrarsentev
    http://TrackStudio.com

Similar Threads

  1. need for some advice
    By kasiopi in forum AWT / Swing
    Replies: 3
    Last Post: 01-26-2011, 12:36 PM
  2. Advice on writing a bot to...?
    By Krooger in forum Advanced Java
    Replies: 1
    Last Post: 07-22-2010, 01:20 PM
  3. Im new n looking for an advice
    By azlynn in forum New To Java
    Replies: 2
    Last Post: 12-10-2009, 02:47 AM
  4. Need advice on JSP with bean
    By butterhero in forum JavaServer Pages (JSP) and JSTL
    Replies: 1
    Last Post: 07-18-2009, 11:40 AM
  5. Some advice please!
    By awebbtt in forum New To Java
    Replies: 3
    Last Post: 02-02-2009, 07:23 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •