Java Troubleshooting Decimal Inputs in Java Applets

  • Thread starter Thread starter FritoTaco
  • Start date Start date
  • Tags Tags
    Java
AI Thread Summary
The discussion revolves around a Java applet program designed to calculate tuition fees based on user input for the number of credits and the cost per credit. The initial issue was that the program only accepted integer inputs, causing it to malfunction when decimal values were entered. The solution involved changing the data type for the cost per credit from an integer to a double by using Double.parseDouble instead of Integer.parseInt. This adjustment allowed the program to handle decimal inputs correctly.Additionally, there were suggestions for improving variable names to enhance code readability, such as renaming variables to reflect their purpose more clearly. The user also sought to format the total output to two decimal places, which was addressed by implementing DecimalFormat. The final code included a method for calculating tuition, and the user was encouraged to refine variable names further for clarity. Overall, the program was successfully modified to accept decimal inputs and format the output as required.
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: 592
  • Tuition2.PNG
    Tuition2.PNG
    8.3 KB · Views: 563
  • Capture3.PNG
    Capture3.PNG
    3.5 KB · Views: 570
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 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: 617
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 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: 589
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I had a Microsoft Technical interview this past Friday, the question I was asked was this : How do you find the middle value for a dataset that is too big to fit in RAM? I was not able to figure this out during the interview, but I have been look in this all weekend and I read something online that said it can be done at O(N) using something called the counting sort histogram algorithm ( I did not learn that in my advanced data structures and algorithms class). I have watched some youtube...

Similar threads

Replies
34
Views
21K
Replies
5
Views
3K
Replies
7
Views
3K
Replies
2
Views
12K
Back
Top