Calculator Can't have Decimal - java

My code now works for sum, subtract, multiple, divide.
However it doesn't show the decimal when I put 10.0 and 2.0 or 5.4 and 2.
How should I change, then it can be used for decimal??
This is my code now.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
// instance variables
JLabel num1Label = null;
JTextField num1Text = null;
JLabel num2Label = null;
JTextField num2Text = null;
JButton sumButton = null;
JButton multipleButton=null;
JButton divideButton=null;
JButton subtractButton = null;
JLabel ansLabel = null;
// constructor
public Calculator() {
setLayout(new GridBagLayout()); // set layout (how elements are arranged in window)
// **** label: num 1
GridBagConstraints layoutCon = new GridBagConstraints();
layoutCon.gridx = 0;
layoutCon.gridy = 0;
layoutCon.insets = new Insets(10,10,10,10);
num1Label = new JLabel("Num 1:");
add(num1Label,layoutCon); // added label to JFrame
// **** text field: num 1
layoutCon = new GridBagConstraints();
layoutCon.gridx = 1;
layoutCon.gridy = 0;
layoutCon.insets = new Insets(10,10,10,10);
num1Text = new JTextField(20);
add(num1Text, layoutCon);
// **** label: num 2
layoutCon = new GridBagConstraints();
layoutCon.gridx = 0;
layoutCon.gridy = 1;
layoutCon.insets = new Insets(10,10,10,10);
num2Label = new JLabel("Num 2:");
add(num2Label,layoutCon); // added label to JFrame
// **** text field: num 2
layoutCon = new GridBagConstraints();
layoutCon.gridx = 1;
layoutCon.gridy = 1;
layoutCon.insets = new Insets(10,10,10,10);
num2Text = new JTextField(20);
add(num2Text, layoutCon);
// **** Sum Button
layoutCon = new GridBagConstraints();
layoutCon.gridx = 0;
layoutCon.gridy = 2;
layoutCon.insets = new Insets(10,10,10,10);
sumButton = new JButton("Sum");
add(sumButton, layoutCon);
sumButton.addActionListener(this); // register sumButton with the ActionListener in Calculator
// Multiple Button
layoutCon= new GridBagConstraints();
layoutCon.gridx=0;
layoutCon.gridy=4;
layoutCon.insets=new Insets(10,10,10,10);
multipleButton= new JButton("Multiple");
add(multipleButton, layoutCon);
multipleButton.addActionListener(this);
// Divide Button
layoutCon = new GridBagConstraints();
layoutCon.gridx = 0;
layoutCon.gridy = 5;
layoutCon.insets = new Insets(10,10,10,10);
divideButton = new JButton("Divide");
add(divideButton, layoutCon);
divideButton.addActionListener(this);
// **** label: answer
layoutCon = new GridBagConstraints();
layoutCon.gridx = 1;
layoutCon.gridy = 2;
layoutCon.insets = new Insets(10,10,10,10);
ansLabel = new JLabel("Answer");
add(ansLabel,layoutCon); // added label to JFrame
// **** Subtract Button
layoutCon = new GridBagConstraints();
layoutCon.gridx = 0;
layoutCon.gridy = 3;
layoutCon.insets = new Insets(10,10,10,10);
subtractButton = new JButton("Subtract");
add(subtractButton, layoutCon);
subtractButton.addActionListener(this); // register subtractButton with the ActionListener in Calculator
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Sum")) {
ansLabel.setText("" + (Integer.parseInt(num1Text.getText()) + Integer.parseInt(num2Text.getText())));
}
else if (e.getActionCommand().equals("Subtract")) {
ansLabel.setText("" + (Integer.parseInt(num1Text.getText()) - Integer.parseInt(num2Text.getText())));
}
else if (e.getActionCommand().equals("Multiple")){
ansLabel.setText(""+(double)(Integer.parseInt(num1Text.getText())*Integer.parseInt(num2Text.getText())));
}
else if (e.getActionCommand().equals("Divide")){
ansLabel.setText(""+(Integer.parseInt(num1Text.getText())/Integer.parseInt(num2Text.getText())));
}
}
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.pack(); // resizes window (JFrame) so you can see the elements in it
calc.setVisible(true); // make window visible
calc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //exit program when close window
}
}

actionPerformed is parsing its inputs as int and operating on them as such. If you want to use floating-point numbers, try using double instead.

Parsing as an integer cannot handle double's or any floating point number (decimal) as such change your actionPerformed to parse double's instead or parse int's:
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Sum")) {
ansLabel.setText("" + (Double.parseDouble(num1Text.getText()) + Double.parseDouble(num2Text.getText())));
}
else if (e.getActionCommand().equals("Subtract")) {
ansLabel.setText("" + (Double.parseDouble(num1Text.getText()) - Double.parseDouble(num2Text.getText())));
}
else if (e.getActionCommand().equals("Multiple")){
ansLabel.setText(""+(double)(Double.parseDouble(num1Text.getText())*Double.parseDouble(num2Text.getText())));
}
else if (e.getActionCommand().equals("Divide")){
ansLabel.setText(""+(Double.parseDouble(num1Text.getText())/Double.parseDouble(num2Text.getText())));
}
}

You use
Integer.parseInt(num1Text.getText());
which parses a String to an int.
With
Double.parseDouble(num1Text.getText());
you get a double.
Note that you might want to catch the NumberFormatException, since you most likley don't want your program to stop on malformed user input:
double num1;
try
{
num1 = Double.parseDouble(num1Text.getText());
} catch (NumberFormatException e)
{
// either use a default value or give feedback to the user on what he did wrong
// for example
num1 = 1;
}
If you don't want to print a double value, if only integer values are entered by the user, then you could first try to parse to int, catch the exception (if any) and then parse to double.
Another error in your divison line:
ansLabel.setText(
""+(Integer.parseInt(num1Text.getText())/Integer.parseInt(num2Text.getText())));
You do not check if the second parameter is != 0, otherwise you might divide by 0!
To keep your code more readable you might want to create an extra method for parsing a String to a number:
private static double parseDouble(String s)
{
double num;
try
{
num = Double.parseDouble(num1Text.getText());
} catch (NumberFormatException e)
{
// either use a default value or give feedback to the user on what he did wrong
// for example
num = 1;
}
return num;
}
A possible fix for the division by 0 could be:
double num1 = parseDouble(num1Text.getText());
double num2 = parseDouble(num2Text.getText());
String command = e.getActionCommand();
if (command.equals("Sum"))
{
ansLabel.setText("" + (num1 + num2));
} else if (command.equals("Subtract"))
{
ansLabel.setText("" + (num1 - num2));
} else if (command.equals("Multiple"))
{
ansLabel.setText("" + (num1 * num2));
} else if (command.equals("Divide"))
{
if (num2 == 0)
{
ansLabel.setText("ERROR: Division by zero!");
} else
{
ansLabel.setText("" + (num1 / num2));
}
}

you should use double data type instead of integer for 4 operations

Like this:
public void actionPerformed( ActionEvent e )
{
if( e.getActionCommand().equals( "Sum" ) )
ansLabel.setText( "" + ( Double.
parseDouble(num1Text.getText() ) + Double.parseDouble(
num2Text.getText() ) ) );
// etc.

Related

Random Number won't appear in a JTextField

I have a problem.I created a program that will add two random numbers. I'm trying to put a Math.random() in a JTextField but it won't appear. Here's my code by the way:
public class RandomMathGame extends JFrame {
public RandomMathGame(){
super("Random Math Game");
int random2;
JButton lvl1 = new JButton("LEVEL 1");
JButton lvl2 = new JButton("LEVEL 2");
JButton lvl3 = new JButton("LEVEL 3");
JLabel line1 = new JLabel("Line 1: ");
final JTextField jtf1 = new JTextField(10);
JLabel line2 = new JLabel("Line 2: ");
final JTextField jtf2 = new JTextField(10);
JLabel result = new JLabel("Result: ");
final JTextField jtf3 = new JTextField(10);
JButton ans = new JButton("Answer");
JLabel score = new JLabel("Score: ");
JTextField jtf4 = new JTextField(3);
JLabel itm = new JLabel("Number of Items: ");
JTextField items = new JTextField(3);
FlowLayout flo = new FlowLayout();
setLayout(flo);
add(lvl1);
add(lvl2);
add(lvl3);
add(line1);
add(jtf1);
add(line2);
add(jtf2);
add(result);
add(jtf3);
add(ans);
add(score);
add(jtf4);
add(itm);
add(items);
setSize(140,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
lvl1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int i, j = 10;
int i1 = Integer.valueOf(jtf1.getText());
int i2 = Integer.valueOf(jtf2.getText());
int i3 = i1 + i2;
final int random1 = (int)(Math.random() * 10 + 1);
for (i = 0; i <= j + 1; i++){
try{
jtf1.setText(String.valueOf(random1));
jtf2.setText(String.valueOf(random1));
jtf3.setText(String.valueOf(i3));
}catch(Exception ex){
ex.printStackTrace();
}
}
}
});
}
Never mind the lvl2 and lvl3 because it's the same in lvl1. And also, I want to loop them 10 times. I'm having difficulties on putting up those codes. Can someone help me? Thanks for your help. :)
Updating text fields in a loop won't produce the animated display that you likely want; only the last update will be seen. Instead, use a javax.swing.Timer to periodically update the fields. Related examples may be found here, here and here.

pressing ENTER key do not work for JTextField in applet

I have a JTextField in a JApplet with a ActionListener. I compiled it using Eclipse and it works fine. But when I try to load it in a .html file using applet, the JTextField does not register/recognize the ENTER key when I press it. It seems like the ActionListener did not work. I used:
public void init() {
textField = new JTextField(20);
textField.setText("Enter your question here.");
textField.selectAll();
textField.addActionListener(this);
textArea = new JTextArea(10, 20);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
// Add Components to the Applet.
GridBagLayout gridBag = new GridBagLayout();
Container contentPane = getContentPane();
contentPane.setLayout(gridBag);
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
gridBag.setConstraints(textField, c);
contentPane.add(textField);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
gridBag.setConstraints(scrollPane, c);
contentPane.add(scrollPane);
newline = System.getProperty("line.separator");
}
public void actionPerformed(ActionEvent event) {
String text = textField.getText();
String question = "";
String answer = "";
question = textField.getText();
question = ProcessString(question);
answer = Answer(question);
textArea.append(text + newline);
textArea.append(answer + newline);
textField.selectAll();
}
static String noAnswer;
static boolean knowAnswer = true;
// process the question string, take out non-ACSII characters, spaces, to
// lower space
public String ProcessString(String question) {
question = question.toLowerCase();
String[] words = question.split("\\s+");
question = "";
for (int wordCount = 0; wordCount < words.length; wordCount++) {
words[wordCount] = words[wordCount].replaceAll("[^A-Za-z]", "");
if (wordCount != words.length - 1)
question = question + words[wordCount] + " ";
else
question = question + words[wordCount];
// System.out.println(words[wordCount]);
}
return question;
}
public String Answer(String question) {
String answer = "";
/*
if the database know the answer (did not not know), then return the
answer. if the database does not know the answer, then recover the
answer in database.
*/
if (knowAnswer == true) {
// open the database file and search if questions matches any one in
// the
// database
Scanner sc = null;
try {
sc = new Scanner(new File("database.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int answerFrequency = 0;
boolean matchFound = false;
while (sc.hasNext()) {
int questionCount = sc.nextInt();
String line = sc.nextLine();
String[] databaseLine = line.split("\\s+");
String databaseQuestion = "";
String databaseAnswer = "";
// collect words for database questions
for (int wordCount = 1; wordCount <= questionCount; wordCount++) {
if (wordCount != questionCount)
databaseQuestion = databaseQuestion
+ databaseLine[wordCount] + " ";
else
databaseQuestion = databaseQuestion
+ databaseLine[wordCount];
}
// collect words for database answer
for (int wordCount = questionCount + 2; wordCount < databaseLine.length; wordCount++) {
databaseAnswer = databaseAnswer + databaseLine[wordCount]
+ " ";
}
// if the question is found in database, print answer
if (question.equals(databaseQuestion)) {
matchFound = true;
// the current answer is more frequency than the previous
// found
// answer, reassign the current answer the find answer
if (answerFrequency < Integer
.parseInt(databaseLine[questionCount + 1])) {
answerFrequency = Integer
.parseInt(databaseLine[questionCount + 1]);
answer = databaseAnswer;
}
}
}
if (matchFound == true) {
// System.out.println(answer);
knowAnswer = true;
} else {
// System.out.println("I don't know what you mean. How should I answer your question?");
knowAnswer = false;
noAnswer = question;
answer = "I don't know how to respond. How should I answer that?";
}
sc.close();
} else if (knowAnswer == false) {
String[] word = noAnswer.split(" ");
BufferedWriter writer = null;
answer = question;
try {
writer = new BufferedWriter(
new FileWriter("database.txt", true));
writer.newLine();
writer.write(word.length + " " + noAnswer + " 1 " + answer);
} catch (IOException e) {
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
System.out.println("Cannot write to file");
}
}
answer = "I got that.";
knowAnswer = true;
}
return answer;
}
Really appreciate the help.
This seems to work for me....
public class TestApplet04 extends JApplet implements ActionListener {
private JTextField textField;
private JTextArea textArea;
private String newline;
public void init() {
textField = new JTextField(20);
textField.setText("Enter your question here.");
textField.selectAll();
textField.addActionListener(this);
textArea = new JTextArea(10, 20);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
// Add Components to the Applet.
GridBagLayout gridBag = new GridBagLayout();
Container contentPane = getContentPane();
contentPane.setLayout(gridBag);
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
gridBag.setConstraints(textField, c);
contentPane.add(textField);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
gridBag.setConstraints(scrollPane, c);
contentPane.add(scrollPane);
newline = System.getProperty("line.separator");
}
public void actionPerformed(ActionEvent event) {
String text = textField.getText();
String question = "";
String answer = "";
question = textField.getText();
// question = ProcessString(question);
// answer = Answer(question);
textArea.append(text + newline);
textArea.append(answer + newline);
textField.selectAll();
}
}
Updated after feedback
Here's you major problem...
sc = new Scanner(new File("database.txt"));
This is going to cause you a number of problems. First of all, the applet isn't likely to have access rights to read from the client machine, so you're likely to run into a security exception. Secondly, as the previous statement may have suggested, the file ins't likely to exist on the client machine.
You need to embed this resource within the Jar of your application and use getClass().getResource("...") to gain access to it. This will return a URL, from which you can use URL#openConnection to gain access to a InputStream, which can use in your scanner.
Try adding an Action to the ActionMap and setting the InputMap up for ENTER key.
textField.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter" );
textField.getActionMap().put("enter", new AbstractAction() {...} );
The field will have to have focus.
I'm also a newbie to Java, but found out that JTextfield is only a single line entry.
If you want a multiline entry, you would need to use a JTextArea instead.
Hope this helps :)

Exceptions with JAVA loan calculator using JFrame?

I think I almost got it if I can just get rid of a few exceptions the program gives me when I try to run it. Here's the code I have:
package RandomMathGame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class RandomMathGame {
public static void main(String[] args) {
RandomProblemGenerator randomProblems = new RandomProblemGenerator(10);
final int numberProblems = 10;
int correctScore = 0;
JPanel panel = new JPanel();
int answer;
int correctAnswer;
JLabel[] mathProblems = new JLabel[numberProblems];
final JTextField[] mathAnswers = new JTextField[numberProblems];
JLabel[] correctYesNo = new JLabel[numberProblems];
final JLabel score = new JLabel(correctScore + "/10");
JButton submit = new JButton("Submit");
for (int i = 1; i <= numberProblems; i++)
{
final int X = randomProblems.createNumberX();
final int Y = randomProblems.createNumberY();
mathProblems[i] = new JLabel("" + X + " * " + Y + " = ");
mathAnswers[i] = new JTextField();
answer = Integer.parseInt(mathAnswers[i].getText());
correctAnswer = X * Y;
if (answer == correctAnswer)
{
correctYesNo[i] = new JLabel("Correct answer; good job!");
correctScore = correctScore + 1;
}
else
{
correctYesNo[i] = new JLabel("Incorrect answer; try again!");
}
panel.add(mathProblems[i]);
panel.add(mathAnswers[i]);
panel.add(correctYesNo[i]);
}
final int temp = correctScore;
submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
score.setText("Score: " + temp + "/10");
}
});
panel.add(submit);
panel.add(score);
JFrame gameFrame = new JFrame();
gameFrame.setTitle("Random Math Game");
gameFrame.setSize(150, 150);
gameFrame.setVisible(true);
gameFrame.setContentPane(panel);
}
}
And these are the exceptions it's giving me when I run it:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:504)
at java.lang.Integer.parseInt(Integer.java:527)
at RandomMathGame.RandomMathGame.main(RandomMathGame.java:33)
Java Result: 1
I'm crunched for time, so any help would be much appreciated.
You are trying to get from a field you just created which is blank.
mathAnswers[i] = new JTextField();
answer = Integer.parseInt(mathAnswers[i].getText());
So in this you are just checking from wrong place.
Seems like on first step you want to create the text fields and the second line should be there at some other event.
Hope it helps
String answerStr = mathAnswers[i].getText();
if(answerStr.isEmpty()){
correctYesNo[i] = new JLabel("Not a valid answer/answer field empty!");
} else {
answer = Integer.parseInt(answerStr);
correctAnswer = X * Y;
//Rest of your code goes here
}
Hope this helps you!
answer = Integer.parseInt(mathAnswers[i].getText());
Is what's causing the error. This is because one of your textfields is blank. Do some validation before accepting user input, unless you want your application to go awry.

Checkbox Compilation Error

I am to stimulate a java applet of a menu with checkboxes and checkboxgroups, with calories listed next to each food choice. My problem is I cannot figure out why I keep getting this error message when i compile it:
AnAppletWithCheckboxes.java:188: illegal forward reference
int crepeVal = Integer.parseInt(textField.getText());
I get that for every line that I have is converting the textField into an int, so hence there are 17 errors. Any idea of why will be appreciated!
Here is my Code:: it is very long because there are plenty checkboxes and textFields. I commented Out My place of Error! :
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class AnAppletWithCheckboxes extends Applet implements ItemListener {
public void init() {
setLayout(new GridLayout(1, 0));
CheckboxGroup dinnerType = new CheckboxGroup();
standard = new Checkbox("standard", dinnerType, false);
standard.addItemListener(this);
deluxe = new Checkbox("deluxe", dinnerType, true);
deluxe.addItemListener(this);
CheckboxGroup appetizers = new CheckboxGroup();
crepe = new Checkbox("crepe", appetizers, false);
crepe.addItemListener(this);
quiche = new Checkbox("quiche", appetizers, false);
quiche.addItemListener(this);
dumpling = new Checkbox("dumpling", appetizers, false);
dumpling.addItemListener(this);
textField = new TextField("300");
textField.setEditable(false);
textField2 = new TextField("330");
textField2.setEditable(false);
textField3 = new TextField("98");
textField3.setEditable(false);
CheckboxGroup soupOrSalad = new CheckboxGroup();
soup = new Checkbox("Soup", soupOrSalad, false);
soup.addItemListener(this);
CheckboxGroup soups = new CheckboxGroup();
cream = new Checkbox("cream", soups, false);
cream.addItemListener(this);
broth = new Checkbox("broth", soups, false);
broth.addItemListener(this);
gumbo = new Checkbox("gumbo", soups, false);
gumbo.addItemListener(this);
textField4 = new TextField("190");
textField4.setEditable(false);
textField5 = new TextField("20");
textField5.setEditable(false);
textField6 = new TextField("110");
textField6.setEditable(false);
salad = new Checkbox("Salad", soupOrSalad, false);
salad.addItemListener(this);
CheckboxGroup salads = new CheckboxGroup();
tossed = new Checkbox("tossed", salads, false);
tossed.addItemListener(this);
caesar = new Checkbox("caesar", salads, false);
caesar.addItemListener(this);
croutons = new Checkbox("croutons");
croutons.addItemListener(this);
lite = new Checkbox("lite dressing");
lite.addItemListener(this);
textField7 = new TextField("35");
textField7.setEditable(false);
textField8 = new TextField("90");
textField8.setEditable(false);
textField9 = new TextField("60");
textField9.setEditable(false);
textField10 = new TextField("50");
textField10.setEditable(false);
CheckboxGroup entrees = new CheckboxGroup();
chicken = new Checkbox("chicken", entrees, false);
chicken.addItemListener(this);
beef = new Checkbox("beef", entrees, false);
beef.addItemListener(this);
lamb = new Checkbox("lamb", entrees, false);
lamb.addItemListener(this);
fish = new Checkbox("fish", entrees, false);
fish.addItemListener(this);
textField11 = new TextField("200");
textField11.setEditable(false);
textField12 = new TextField("170");
textField12.setEditable(false);
textField13 = new TextField("65");
textField13.setEditable(false);
textField14 = new TextField("150");
textField14.setEditable(false);
CheckboxGroup deserts = new CheckboxGroup();
pie = new Checkbox("pie", deserts, false);
pie.addItemListener(this);
fruit = new Checkbox("fruit", deserts, false);
fruit.addItemListener(this);
sherbet = new Checkbox("sherbet", deserts, false);
sherbet.addItemListener(this);
textField15 = new TextField("80");
textField15.setEditable(false);
textField16 = new TextField("60");
textField16.setEditable(false);
textField17 = new TextField("107");
textField17.setEditable(false);
calories = new Button("Calories");
calTextField = new TextField("0"+total);
calTextField.setEditable(false);
setLayout(new GridLayout(0, 1));
Panel p = new Panel();
add(p);
p.add(standard);
p.add(deluxe);
appetizerPanel = new Panel();
add(appetizerPanel);
label = new Label("Appetizer");
appetizerPanel.add(label);
appetizerPanel.add(crepe);
appetizerPanel.add(textField);
appetizerPanel.add(quiche);
appetizerPanel.add(textField2);
appetizerPanel.add(dumpling);
appetizerPanel.add(textField3);
soupPanel = new Panel();
add(soupPanel);
soupPanel.add(soup);
soupPanel.add(cream);
soupPanel.add(textField4);
soupPanel.add(broth);
soupPanel.add(textField5);
soupPanel.add(gumbo);
soupPanel.add(textField6);
saladPanel = new Panel();
add(saladPanel);
saladPanel.add(salad);
saladPanel.add(tossed);
saladPanel.add(textField7);
saladPanel.add(caesar);
saladPanel.add(textField8);
saladPanel.add(croutons);
saladPanel.add(textField9);
saladPanel.add(lite);
saladPanel.add(textField10);
entreePanel = new Panel();
add(entreePanel);
label2 = new Label("Entree");
entreePanel.add(label2);
entreePanel.add(chicken);
entreePanel.add(textField11);
entreePanel.add(beef);
entreePanel.add(textField12);
entreePanel.add(lamb);
entreePanel.add(textField13);
entreePanel.add(fish);
entreePanel.add(textField14);
desertPanel = new Panel();
add(desertPanel);
label3 = new Label("Desert");
desertPanel.add(label3);
desertPanel.add(pie);
desertPanel.add(textField15);
desertPanel.add(fruit);
desertPanel.add(textField16);
desertPanel.add(sherbet);
desertPanel.add(textField17);
caloriesPanel = new Panel();
add(caloriesPanel);
caloriesPanel.add(calories);
caloriesPanel.add(calTextField);
}
public void LabelChange(Label b) {
if (b ==label3)
b.setForeground(Color.lightGray);
else
label3.setForeground(Color.black);
}
/* This is where i get those errors!! */
int crepeVal = Integer.parseInt(textField.getText());
int quicheVal = Integer.parseInt(textField2.getText());
int dumplingVal = Integer.parseInt(textField3.getText());
int creamVal = Integer.parseInt(textField4.getText());
int brothVal = Integer.parseInt(textField5.getText());
int gumboVal = Integer.parseInt(textField6.getText());
int tossedVal = Integer.parseInt(textField7.getText());
int caesarVal = Integer.parseInt(textField8.getText());
int croutonsVal = Integer.parseInt(textField9.getText());
int liteVal = Integer.parseInt(textField10.getText());
int chickenVal = Integer.parseInt(textField11.getText());
int beefVal = Integer.parseInt(textField12.getText());
int lambVal = Integer.parseInt(textField13.getText());
int fishVal = Integer.parseInt(textField14.getText());
int pieVal = Integer.parseInt(textField15.getText());
int fruitVal = Integer.parseInt(textField16.getText());
int sherbetVal = Integer.parseInt(textField17.getText());
public boolean action(Event evt, Object whatAction){
if(!(evt.target instanceof Button)){
return false;
}
else {
calorieCount();
return true;
}
}
public void calorieCount () {
if (crepe.getState())
crepeVal += total;
else
crepeVal = 0;
if (quiche.getState())
quicheVal += total;
else
quicheVal = 0;
if (dumpling.getState())
dumplingVal += total;
else
dumplingVal= 0;
if (cream.getState())
creamVal += total;
else
creamVal = 0;
if (broth.getState())
brothVal += total;
else
brothVal = 0;
if (gumbo.getState())
gumboVal += total;
else
gumboVal = 0;
if (tossed.getState())
tossedVal += total;
else
tossedVal = 0;
if (caesar.getState())
caesarVal += total;
else
caesarVal = 0;
if (croutons.getState())
croutonsVal += total;
else
croutonsVal = 0;
if (lite.getState())
liteVal += total;
else
liteVal = 0;
if (chicken.getState())
chickenVal += total;
else
chickenVal = 0;
if (beef.getState())
beefVal += total;
else
beefVal = 0;
if (lamb.getState())
lambVal += total;
else
lambVal = 0;
if (fish.getState())
fishVal += total;
else
fishVal = 0;
if (pie.getState())
pieVal += total;
else
pieVal = 0;
if (fruit.getState())
fruitVal += total;
else
fruitVal = 0;
if (sherbet.getState())
sherbetVal += total;
else
sherbetVal = 0;
}
public void itemStateChanged(ItemEvent e) {
if (e.getSource() == standard || e.getSource() == deluxe)
handleDinnerType((Checkbox)e.getSource());
else if (e.getSource() == soup || e.getSource() == salad)
handleSoupSaladChoice((Checkbox)e.getSource());
}
void handleDinnerType(Checkbox selectedType) {
boolean enabled;
if (selectedType == standard){
enabled = false;
LabelChange(label3);
}
else{
enabled = true;
LabelChange(label);
}
soup.setEnabled(enabled);
salad.setEnabled(enabled);
pie.setEnabled(enabled);
fruit.setEnabled(enabled);
sherbet.setEnabled(enabled);
cream.setEnabled(enabled);
broth.setEnabled(enabled);
gumbo.setEnabled(enabled);
tossed.setEnabled(enabled);
caesar.setEnabled(enabled);
croutons.setEnabled(enabled);
lite.setEnabled(enabled);
}
void handleSoupSaladChoice(Checkbox selectedCourse) {
boolean soupEnabled, saladEnabled;
if (selectedCourse == soup) {
soupEnabled = true;
saladEnabled = false;
soup.setForeground(Color.BLACK);
salad.setForeground(Color.lightGray);
}
else {
soupEnabled = false;
saladEnabled = true;
soup.setForeground(Color.lightGray);
salad.setForeground(Color.BLACK);
}
cream.setEnabled(soupEnabled);
broth.setEnabled(soupEnabled);
gumbo.setEnabled(soupEnabled);
tossed.setEnabled(saladEnabled);
caesar.setEnabled(saladEnabled);
croutons.setEnabled(saladEnabled);
lite.setEnabled(saladEnabled);
}
Label
label, label2, label3;
Panel
appetizerPanel, soupPanel, saladPanel, entreePanel, desertPanel, caloriesPanel;
Checkbox
standard, deluxe,
soup, salad,
crepe, quiche, dumpling,
cream, broth, gumbo,
tossed, caesar,
croutons, lite,
chicken, beef, lamb, fish,
pie, fruit, sherbet;
Button calories;
int total = 0;
TextField
textField, textField2, textField3,
textField4, textField5, textField6,
textField7, textField8, textField9,
textField10, textField11, textField12,
textField13, textField14, textField15,
textField16, textField17, calTextField;
}
In Java, you are not allowed to refer to a field a in an initializer of another field b if b is declared before a in the source code. That is, this is allowed:
int b = 3;
int a = b;
but this is not allowed:
int a = b;
int b = 3;
By the way, if Java had some magic way of figuring out that textField had to be initialized before crepeVal, you would still get a NullPointerException since textField is null after object construction.

Java Mortgage Calculator Reading a Sequential File [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I populate jcombobox from a textfile?
OK, I have an issue here that I cannot quiet figure out. I have a file that has variables on each line of: 5.35, 5.5, 5.75 in a file called apr.txt. I am reading the file and need to populate the file into a JComboBox. So far I have the file being read fine but cannot figure how to populate it into the JComboBox. This must be something easy. Can someone help point me in the proper direction?
Thank you for your help in advance.
import java.awt.*;
import java.text.NumberFormat;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.StringTokenizer;
import javax.swing.*;
import javax.swing.JComboBox;
public class MortgageCalculatorGUI9 extends JFrame implements ActionListener
{
// Declarations
//double [] Interest = {5.35, 5.5, 5.75};
int [] Length = {7, 15, 30};
double [] file_data = new double[3];
JLabel mortgagelabel = new JLabel( "Principal Amount:$ " );
JLabel paymentLabel = new JLabel( "Monthly Payment: " );
JLabel intRateLabel = new JLabel( "Interest Rate %: " );
JLabel termLabel = new JLabel( "Length of Loan of Loan in Years: " );
JTextField mortgagePrincipal = new JTextField(7);
JTextField Payment = new JTextField(7);
//JTextField intRateText = new JTextField(3);
JComboBox intRateBox = new JComboBox();
JTextField termText = new JTextField(3);
JButton b7_535 = new JButton( "7 years at 5.35%" );
JButton b15_55 = new JButton( "15 years at 5.50%" );
JButton b30_575 = new JButton( "30 years at 5.75%");
JButton exitButton = new JButton( "Exit" );
JButton clearButton = new JButton( "Clear All" );
JButton calculateButton = new JButton( "Calculate Loan" );
JTextArea LoanPayments = new JTextArea(20,50);
JScrollPane scroll = new JScrollPane(LoanPayments);
public MortgageCalculatorGUI9()
{
//GUI setup
super("Mortgage Calculator 1.0.5");
setSize(800, 400);
setLocation(500, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel(new GridLayout(3,1)); Container grid = getContentPane();
grid.setLayout(new GridLayout(4,0,4,4)); pane.add(grid);
pane.add(scroll);
grid.add(mortgagelabel);
grid.add(mortgagePrincipal);
grid.add(intRateLabel);
//grid.add(intRateText);
grid.add (intRateBox);
grid.add(termLabel);
grid.add(termText);
grid.add(paymentLabel);
grid.add(Payment);
grid.add(b7_535);
grid.add(b15_55);
grid.add(b30_575);
grid.add(calculateButton);
grid.add(clearButton);
grid.add(exitButton);
Payment.setEditable(false);
setContentPane(pane);
setContentPane(pane);
setVisible(true);
//add GUI functionality
calculateButton.addActionListener (this);
exitButton.addActionListener(this);
clearButton.addActionListener(this);
b7_535.addActionListener(this);
b15_55.addActionListener(this);
b30_575.addActionListener(this);
mortgagePrincipal.addActionListener(this);
//intRateText.addActionListener(this);
intRateBox.addActionListener (this);
termText.addActionListener(this);
Payment.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
Object command = e.getSource();
if (command == exitButton)
{
System.exit(0);
}
else if (command == b7_535)
{
calcLoan(Length[0], file_data[0]);
}
else if (command == b15_55)
{
calcLoan(Length[1], file_data[1]);
}
else if (command == b30_575)
{
calcLoan(Length[2], file_data[2]);
}
else if (command == calculateButton )
{
double terms = 0;
double rates = 0;
try
{
terms = Double.parseDouble(termText.getText());
//rates = Double.parseDouble(intRateText.getText());
read_File ();
}
catch (Exception ex)
{
LoanPayments.setText("Invalid term or rate Amount");
return;
}
calcLoan(terms, rates);
}
else if (command == clearButton)
{
mortgagePrincipal.setText("");
Payment.setText("");
//intRateText.setText("");
termText.setText("");
LoanPayments.setText("");
}
}
//Input File
public void read_File()
{
File inFile = new File("apr.txt");
try
{
BufferedReader istream = new BufferedReader(new FileReader(inFile));
for(int x=0;x<6;x++)
{
file_data[x]=Double.parseDouble (istream.readLine());
}
}
catch (Exception ex)
{
LoanPayments.setText ("Could Not Read From File.");
return;
}
}
//this is what needs to be done
private void calcLoan(double terms, double rates)
{
termText.setText(String.valueOf(terms) );
//intRateText.setText(String.valueOf(rates));
double amount = 0;
try
{
amount = Double.parseDouble(mortgagePrincipal.getText());
}
catch (Exception ex)
{
LoanPayments.setText("Invalid mortgage Amount");
return;
}
double interestRate = rates;
// Calculations
double intRate = (interestRate / 100) / 12;
int Months = (int)terms * 12;
double rate = (intRate / 12);
double payment = amount * intRate / (1 - (Math.pow(1/(1 + intRate), Months)));
double remainingPrincipal = amount;
double MonthlyInterest = 0;
double MonthlyAmt = 0;
double[] balanceArray = new double[Months];
double[] interestArray = new double[Months];
double[] monthArray = new double[Months];
NumberFormat Money = NumberFormat.getCurrencyInstance();
Payment.setText(Money.format(payment));
LoanPayments.setText("Month\tPrincipal\tInterest\tEnding Balance\n");
int currentMonth = 0;
while(currentMonth < Months)
{
//create loop calculations
MonthlyInterest = (remainingPrincipal * intRate);
MonthlyAmt = (payment - MonthlyInterest);
remainingPrincipal = (remainingPrincipal - MonthlyAmt);
LoanPayments.append((++currentMonth) + "\t" + Money.format(MonthlyAmt) + "\t" + Money.format(MonthlyInterest) + "\t" + Money.format(remainingPrincipal) + "\n");
balanceArray[currentMonth] = MonthlyAmt;
interestArray[currentMonth] = MonthlyInterest;
monthArray[currentMonth] = currentMonth;
}
}
public static void main(String[] args)
{
MortgageCalculatorGUI9 frame= new MortgageCalculatorGUI9();
}
}
Have you looked at the JComboBox API for a suitable method? If you start there, you'll likely get the right answer faster than asking in StackOverflow (hint it starts with "add... and ends with ...Item") ;)

Categories