Troubleshooting Decimal Inputs in Java Applets

  • Java
  • Thread starter FritoTaco
  • Start date
  • Tags
    Java
In summary: Integer.parseInt(input); will returnthe 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.In summary, the conversation discusses a program being written in Java Applet that takes user input for the number of credits and the cost per credit, along with constant fees for books and parking. The code uses JOptionPane for user input and has a
  • #1
FritoTaco
132
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: 532
  • Tuition2.PNG
    Tuition2.PNG
    8.3 KB · Views: 508
  • Capture3.PNG
    Capture3.PNG
    3.5 KB · Views: 499
Last edited:
Technology news on Phys.org
  • #2
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 FritoTaco
  • #3
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: 546
Last edited:
  • #4
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 FritoTaco
  • #5
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: 527

1. What is a Java applet?

A Java applet is a small program written in the Java programming language that is embedded into a web page. It runs within a web browser and is used to provide interactive and dynamic content on a website.

2. How do you use decimals in a Java applet?

To use decimals in a Java applet, you can declare a variable with a data type of "double" or "float". These data types allow you to store and manipulate decimal numbers in your applet code.

3. Why is it important to use decimals in a Java applet?

Decimals are important in a Java applet because they allow for more precise calculations and data representation. They are particularly useful when dealing with financial or scientific data.

4. Can you give an example of using decimals in a Java applet?

Yes, for example, you can use decimals to calculate the area of a circle in a Java applet. You would declare a variable for the radius of the circle as a double, and then use the formula: area = π * radius * radius. This will give you a more accurate result compared to using only whole numbers.

5. Are there any limitations to using decimals in a Java applet?

Yes, there are some limitations to using decimals in a Java applet. One limitation is that the precision of decimal numbers is limited by the data type used. For example, a float can only store up to 6-7 digits after the decimal point, while a double can store up to 15-16 digits. Additionally, using decimals in calculations can sometimes result in rounding errors, so it is important to be aware of this when using them in your applet code.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
5
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
2K
  • Programming and Computer Science
Replies
34
Views
20K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
12K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
17K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
2K
Back
Top