Troubleshooting Decimal Inputs in Java Applets

  • Context: Java 
  • Thread starter Thread starter FritoTaco
  • Start date Start date
  • Tags Tags
    Java
Click For Summary

Discussion Overview

The discussion focuses on troubleshooting issues related to decimal inputs in a Java applet program designed to calculate tuition fees based on user inputs for credits and cost per credit. Participants explore the handling of decimal values and the implications for data types used in the program.

Discussion Character

  • Technical explanation
  • Exploratory
  • Conceptual clarification

Main Points Raised

  • One participant describes an issue where entering decimal values results in a blank applet, while integer inputs work correctly.
  • Another participant points out that the use of Integer.parseInt(input) for decimal inputs leads to truncation, suggesting the use of Double.parseDouble(input) instead.
  • Concerns are raised about variable naming conventions, with suggestions for more descriptive names to improve code readability.
  • A participant mentions the need to format the output to two decimal places, indicating that the current implementation only formats to one decimal.
  • There is a discussion about declaring constants for fees instead of hard-coding them, with suggestions for using final variables.

Areas of Agreement / Disagreement

Participants generally agree on the need to change the data type for handling decimal inputs and to improve variable naming. However, the discussion remains unresolved regarding the best approach to formatting the output to two decimal places.

Contextual Notes

Limitations include unresolved issues with output formatting and the potential for hard-coded values to become outdated. The discussion does not reach a consensus on the best practices for variable naming and code structure.

FritoTaco
Messages
132
Reaction score
23
Hello,

I am writing a program that takes a users input of how many credits they're taking, and the number of dollars each credit is. The book and parking fee is a constant number (no change). I'm using JOptionPane so users can enter 2 values, 1 for number of credits, and the other for dollars per credit. I want to enter a number such as; 135.65 into the input. When I do that I get (you can see in the screenshot) a blank applet. When I use just integers it runs fine and outputs total and everything, except when I enter a decimal it doesn't execute properly. I'm new to Java Applet and was wondering why can't 'double' work. Also, how can I fix it so I can enter decimal numbers? I'm using BlueJ if you're wondering.

Java:
import java.awt.*;
import java.applet.Applet;
import javax.swing.*;
public class Tuition extends JApplet {
 
    int number1, number2, number3, number4;
    int sum;
    int NOC; // Number of credits
    double DPC; // dollars per credit
    int PF; // Parking fee
    int BF; // Book(s) fee
    int Multiply;
    int total;
 
    String numberInStringFormat;
 
    String Message = "Tuition Fee for school";
 
    public void init() {
        String input;
 
        input =JOptionPane.showInputDialog (null, numberInStringFormat, "Enter Number of Credits",  JOptionPane.QUESTION_MESSAGE);
        number1 =Integer.parseInt(input);
        input =JOptionPane.showInputDialog (null, numberInStringFormat, "Enter cost Per Credit",  JOptionPane.QUESTION_MESSAGE);
        number2 =Integer.parseInt(input);
    
        sum = 60 + 400; // parking fee + book fee
        Multiply = number1 * number2; // number of credits * dollars per credit
        total = Multiply + sum;
    
        NOC = number1;
        DPC = number2;
    
        JOptionPane.showMessageDialog(null, "Total Fee = " +total);
    
    }
    
        public void paint(Graphics g) {
        Font f = new Font("Serif", Font.PLAIN, 16);
        Font fb = new Font("TimesRoman", Font.BOLD, 18);
    
        g.setFont(f);  //set new font
        g.drawString("Number of Credits entered: " + NOC, 70, 220);
        g.drawString("Dollars per credit: " + DPC, 70, 240);
        g.drawString("Parking fee amount: 60", 70, 260);
        g.drawString("Book(s) fee: 400", 70, 280);
        g.setFont(fb);
        g.drawString("Total cost: $"+total, 70, 310); //total Number of credits * dollars per credit + Book/parking fee.
    }
}
 

Attachments

  • Tuition1.PNG
    Tuition1.PNG
    13.1 KB · Views: 628
  • Tuition2.PNG
    Tuition2.PNG
    8.3 KB · Views: 587
  • Capture3.PNG
    Capture3.PNG
    3.5 KB · Views: 604
Last edited:
Technology news on Phys.org
FritoTaco said:
I am writing a program that takes a users input of how many credits they're taking, and the number of dollars each credit is. The book and parking fee is a constant number (no change). I'm using JOptionPane so users can enter 2 values, 1 for number of credits, and the other for dollars per credit. I want to enter a number such as; 135.65 into the input. When I do that I get (you can see in the screenshot) a blank applet. When I use just integers it runs fine and outputs total and everything, except when I enter a decimal it doesn't execute properly. I'm new to Java Applet and was wondering why can't 'double' work. Also, how can I fix it so I can enter decimal numbers? I'm using BlueJ if you're wondering.
From your code:
Java:
input =JOptionPane.showInputDialog (null, numberInStringFormat, "Enter cost Per Credit",  JOptionPane.QUESTION_MESSAGE);
        number2 =Integer.parseInt(input);
   
        sum = 60 + 400; // parking fee + book fee
        Multiply = number1 * number2; // number of credits * dollars per credit
        total = Multiply + sum;
   
        NOC = number1;
        DPC = number2;
number2 is type int. If in the first line above you entered something like 123.45, the call to Integer.parseInt(input); will return the truncated version of the input string that is appropriate to store in an int variable. IOW, input will be the string "123" in this case, and number2 will be the integer value 123. The fact that DPC is type double is really irrelevant here, since number2 can't contain the fractional part of the input number. What gets stored in DPC is just 123.0.

Instead of using Integer.parseInt(input), use Double.parseDouble(input).

BTW, your choices for variable names are not very good. number1, number2, number3, and number4 should have names that suggest what they are going to hold. Multiply is an awful name. A better name would be something that suggests it will contain the total cost of however many credits are being taken. sum is also a terrible name. A better name would indicate that this is being used to hold the total fees, which should not be hard-coded into your program. It's a safe bet that these fees won't remain constant over time, so you should have these as constants, which in Java is done by declaring them as final double BOOK_FEE = 400, and final double PARKING_FEE = 60.
NOC and DPC aren't awful, but better names would be NoOfCredits and CostPerCredit.
 
  • Like
Likes   Reactions: FritoTaco
Mark44 said:
number2 is type int. If in the first line above you entered something like 123.45, the call to Integer.parseInt(input); will return the truncated version of the input string that is appropriate to store in an int variable. IOW, input will be the string "123" in this case, and number2 will be the integer value 123. The fact that DPC is type double is really irrelevant here, since number2 can't contain the fractional part of the input number. What gets stored in DPC is just 123.0.

Instead of using Integer.parseInt(input), use Double.parseDouble(input).

BTW, your choices for variable names are not very good. number1, number2, number3, and number4 should have names that suggest what they are going to hold. Multiply is an awful name. A better name would be something that suggests it will contain the total cost of however many credits are being taken. sum is also a terrible name. A better name would indicate that this is being used to hold the total fees, which should not be hard-coded into your program. It's a safe bet that these fees won't remain constant over time, so you should have these as constants, which in Java is done by declaring them as final double BOOK_FEE = 400, and final double PARKING_FEE = 60.
NOC and DPC aren't awful, but better names would be NoOfCredits and CostPerCredit.

Okay, I took your suggestion in renaming the variables. Also, I changed it to Double.parseDouble which helped a lot. In my assignment, it wants the output to be formatted to 2 decimals. If you see in my picture, it formats to one decimal. I added this to my code to see if it works

At the top in public class tuition extends JApplet
Code:
DecimalFormat myFormat = new DecimalFormat(".0");

And this, which is in public void paint(Graphics g)
Code:
 String formattedTotal;
        formattedTotal = myFormat.format(total);
Java:
import java.awt.*;
import javax.swing.*;
import java.text.*;
import java.applet.Applet;

public class Tuition extends JApplet
{
    String welcomeMessage = "Welcome!";
    String numberInStringFormat;
 
    private Image NHCC = null;
 
    double totbookparking;
    double NumofCreds;
    double DollarsperCred;
    double ParkingFee;
    double BookFee;
    double NumofCredsnDollarsperCred;
    double total;

    DecimalFormat myFormat = new DecimalFormat(".0");

    public void init() {
        String input;
 
        input =JOptionPane.showInputDialog (null, numberInStringFormat, "Enter Number of Credits",  JOptionPane.QUESTION_MESSAGE);
        NumofCreds =Double.parseDouble(input);
        input =JOptionPane.showInputDialog (null, numberInStringFormat, "Enter Number of Credits",  JOptionPane.QUESTION_MESSAGE);
        DollarsperCred =Double.parseDouble(input);
 
        final double BookFee = 400;
        final double ParkingFee = 60;
 
        total = (NumofCreds * DollarsperCred) + BookFee + ParkingFee;
 
        JOptionPane.showMessageDialog(null, "Total Fee = " +total);
    }
 
    public void paint(Graphics g) {
        super.paint(g);
        Font f = new Font("Serif", Font.PLAIN, 16);
        Font fb = new Font("TimesRoman", Font.BOLD, 18);
 
        g.setFont(f);
        g.drawString("Number of Credits entered: " + NumofCreds, 70, 220);
        g.drawString("Dollars per credit: " + DollarsperCred, 70, 240);
        g.drawString("Parking fee amount: 60", 70, 260);
        g.drawString("Book(s) fee: 400", 70, 280);
 
        String formattedTotal;
        formattedTotal = myFormat.format(total);
 
        g.setFont(fb);
        g.drawString("Total tuition fee: $" + calculateTuition(60, 400), 70, 320);
 
    }
 
    public double calculateTuition(double books, double parking){
     
        double totalfee = (NumofCreds * DollarsperCred)+ books + parking; //double totalfee: 60 + 400
        return totalfee;
 
    }

 
}

Edit: Made a few updates to code, created a method class called calculateTuition but still can't add a leading zero at the end of the total.
 

Attachments

  • Capture4.PNG
    Capture4.PNG
    3.7 KB · Views: 649
Last edited:
FritoTaco said:
Edit: Made a few updates to code, created a method class called calculateTuition but still can't add a leading zero at the end of the total.
That's not a leading zero--it's a trailing zero.
Try this:
Java:
NumberFormat numberFormat = new DecimalFormat("#,###.00");
This format pattern will give you two decimal places and will add a comma separator at the thousands place. For more info, see http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html.

The new variable names look a lot better.
totbookparking
NumofCreds
DollarsperCred
ParkingFee
BookFee
NumofCredsnDollarsperCred

Some suggestions:
The variables are easier to read if each word that makes up the variable is capitalized. E.g., NumOfCreds (or even NumCreds -- 'of' isn't really necessary)
CostPerCred instead of DollarsperCred
ParkingFee and BookFee are fine
NumofCredsnDollarsperCred should be changed. I have no idea what it is supposed to represent. Is it the number of credits or the cost per credit?

Edit: I suspected that you might have listed the last one in error. Sure enough, I can't find it being used in your code. If a variable isn't being used, it should be deleted.
 
Last edited:
  • Like
Likes   Reactions: FritoTaco
Alright, thanks. I'll keep that in mind for creating variables in my next assignment. Thank you, I got it working as you can see in the snapshot.
 

Attachments

  • Capture6.PNG
    Capture6.PNG
    1.1 KB · Views: 617

Similar threads

  • · Replies 34 ·
2
Replies
34
Views
22K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 2 ·
Replies
2
Views
12K
  • · Replies 2 ·
Replies
2
Views
18K
Replies
1
Views
2K