How do I fix java.lang.NumberFormatException? [duplicate] - java

This question already has answers here:
What is a NumberFormatException and how can I fix it?
(9 answers)
Closed 3 years ago.
I'm trying to make this "Overall Grade Calculator" using javax.swing.*; that I recently learned. However, I can't find what is wrong with my code. My IDE, which is Ecliple, isn't detecting any error on my codes but it won't run when I try to run my codes. Where did I mess up?
BTW: This is by far my latest knowledge of Java Coding because I am self taught so I might not know any codes that are more advanced that these.
import javax.swing.*;
public class gradeCalcMk3 {
public static double average(double a, double b, double c, double d) {
double ave = a*0.3 + b*0.5 + c*0.1 + d*0.1;
return ave;
}
public static void main(String[] args) {
double grade[] = {0,0,0,0,0};
JTextField name = new JTextField(10);
JTextField q = new JTextField(3);
JTextField ex = new JTextField(3);
JTextField cs = new JTextField(3);
JTextField ilm = new JTextField(3);
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("Name:"));
myPanel.add(name);
myPanel.add(new JLabel("Q:"));
myPanel.add(q);
myPanel.add(new JLabel("Ex:"));
myPanel.add(ex);
myPanel.add(new JLabel("CS:"));
myPanel.add(cs);
myPanel.add(new JLabel("ILM:"));
myPanel.add(ilm);
grade[0] = Double.parseDouble(q.getText());
grade[1] = Double.parseDouble(ex.getText());
grade[2] = Double.parseDouble(cs.getText());
grade[3] = Double.parseDouble(ilm.getText());
grade[4] = average(grade[0], grade[1], grade[2], grade[3]);
double confirm = JOptionPane.showConfirmDialog
(null, myPanel, "Enter Values", JOptionPane.OK_CANCEL_OPTION);
if(confirm == JOptionPane.OK_OPTION) {
JOptionPane.showMessageDialog(null, "Name: " + name.getText()
+ "\n\nQuiz: " + grade[0]
+ "\n\nExam: " + grade[1]
+ "\n\nCS: " + grade[2]
+ "\n\nILM: " + grade[3]
+ "Average: " + grade[4]);
}
}
}
Here's the output when I try to run it
Exception in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at gradeCalcMk3.main(gradeCalcMk3.java:32)

You will need a bit more to make this work.
Basically all of the code that extracts the values from the text field needs to be placed into a method that is triggered when you click on a button or menu (or something else to activate it). i.e. you need at least two methods, a "setup form" method and a "process the inputs" method.
As posted, your JTextFields contain no text (the constructor you are using does not set the text - it sets the "number of columns").
Once all of the text fields have been created and added to the form, the very next step is to extract the empty strings from them and attempt to parse them as doubles. This will generate the exception you encountered.
Because the code is all contained in a single method, there is zero chance to allow you to enter any values into the fields before they are read and processed.
At the very least, comment out (for now) the code that attempts to extract values, parse them and compute the average. This extract, parse and calculate code can later be moved into the event handler attached to a button or menu that I mentioned above.
I hope this helps.

You're simply using the wrong constructor when creating instances of JTextField
JTextField(int columns)
Constructs a new empty TextField with the specified number of columns.
Instead of providing an int, use a string, for example new JTextField("10")
JTextField(String text)
Constructs a new TextField initialized with the specified text.

Nvm, I found where I messed up and fixed it by doing this:
if(confirm == JOptionPane.OK_OPTION) {
grade[0] = Double.parseDouble(q.getText());
grade[1] = Double.parseDouble(ex.getText());
grade[2] = Double.parseDouble(cs.getText());
grade[3] = Double.parseDouble(ilm.getText());
grade[4] = average(grade[0], grade[1], grade[2], grade[3]);
JOptionPane.showMessageDialog(null, "Name: " + name.getText()
+ "\n\nQuiz: " + grade[0]
+ "\n\nExam: " + grade[1]
+ "\n\nCS: " + grade[2]
+ "\n\nILM: " + grade[3]
+ "Average: " + grade[4]);
}

Related

How to wrap text in multilple JLables in Java? [duplicate]

This question already has answers here:
JLabel - Show longer text as multiple lines?
(4 answers)
How to format JLabel/JTextField so text wraps [duplicate]
(1 answer)
Closed 4 years ago.
I have 12 labels and 12 car objects in an ArrayList. The for loop sets the for each label and its corresponding car object. However the text in the labels does not wrap and just carries on.
What do I have to put in the loop to make the text wrap?
In theory the text is supposed to look like this:
2012 Toyota Corolla
70000 Miles
$12,000.00
But instead in the labels all I get in a single line is:
2012 Toyota Corolla 700...
Code
InventoryFileReader reader = new InventoryFileReader();
ArrayList<Car> cars = reader.getAllCars();
//will format getPrice to currency.
Locale locale = new Locale("en", "US");
NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
JLabel[] labels = new JLabel[]{jLabel1, jLabel2, jLabel3, jLabel4,
jLabel5, jLabel6, jLabel7, jLabel8,
jLabel9, jLabel10, jLabel11, jLabel12};
for(int i = 0; labels.length > i; i ++){
labels[i].setText(cars.get(i).getYear() + " " + cars.get(i).getMake() +
" " + cars.get(i).getModel() + " " + "\n" + cars.get(i).getMiles()
+ " miles" + '\n' + " " + formatter.format(cars.get(i).getPrice()));
}
The getYear(), getMiles(), and getPrice(), actually return integer values.

Can someone show me how to handle java.lang.NullPointerException in my code below [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I get the exception whenever I run the program without passing in the usDollarAmount or cancel the program... I'm using swing components to accept user input. The program works fine otherwise.
Please show me how to handle this... Thanks
THE Currency CALCULATOR
Exception in thread "main" java.lang.NullPointerException
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at Currency.main(Currency.java:28)
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
public class Currency{
public static void main(String[] args)
{
// declare and construct variables
double usDollarAmount, poundsAmount,eurosAmount,rublesAmount;
DecimalFormat twoDigits = new DecimalFormat("####.00");
//print prompts and get input
System.out.println("\tTHE Currency CALCULATOR");
//print prompts and get input
usDollarAmount = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter your dollar amount:"));
// calculations
poundsAmount = 0.64 * usDollarAmount;
eurosAmount = 0.91 * usDollarAmount ;
rublesAmount = 61.73 * usDollarAmount ;
// output
JOptionPane.showMessageDialog(null, "YOUR DOLLAR AMOUNT OF " + twoDigits.format(usDollarAmount) + " is equal to " + twoDigits.format(eurosAmount) + " euros" + " ," + twoDigits.format(poundsAmount) + " pounds" + " " + " and " + twoDigits.format(rublesAmount) + " rubles" );
System.exit(0);
}
}
First assign the input to a variable and then do a null check. If not null do the parsing
String input = JOptionPane.showInputDialog(null, "Enter your dollar amount:");
if(input != null && !input.trim().isEmpty())
usDollarAmount = Double.parseDouble();

How do i append a new text at JLabel?

I read, some StackOverflow questions that I need to use HTML stuffs.
But what would be the easiest it without any of HTML stuff.
Here's the code
label.setText(label.getText() + (String)boxTimes.getSelectedItem() + input);
This code will produce this
What I want is:
You must know a bit of basic String format:
\n line break
\t tab
So your code will be like:
String myLabel =
// 4
label.getText() + "\n\n" +
// 7:00
(String)boxTimes.getSelectedItem() + "\t" +
// - Going out....
"- " + input;
label.setText(myLabel);
But as long as JLabel does not accept \n as Abishek Manoharan pointed, you must use <br>.
String myLabel =
"<html>" +
label.getText() +
"<br/><br/>" +
(String)boxTimes.getSelectedItem() + " - " + input +
"</html>;
label.setText(myLabel);
I was faced with the same problem too and couldn't find a viable solution.
So I went ahead and used a JTextArea instead of JLabel.
JTextArea label = new JTextArea();
label.setEditable(false);
label.setBackground(null);
It gives the same look and feel of a JLabel
You can use '\n' and '\t' as you like,
and what more, the text is selectable which is not possible in JLabel.

How to save information from JTable to a File?

Here is my case:
So far my group and I, managed to read information from an external file and place it in a JTable. But we need an update button. So we guess we should take all the information from JTable after editting something inside it, and replace it with the current information in the same file. So we kind of think we have to overwrite the old file.
So far we got this: (for int i... is a part of the code but can't get it inside the grey area :P)
for(int i = 0; i < model.getRowCount(); i++) {
p += model.getValueAt(i, 0) + " "
+ model.getValueAt(i, 1) + " "
+ (Integer) model.getValueAt(i, 2) + " "
+ model.getValueAt(i, 3) + " "
+ (Integer)model.getValueAt(i, 4) + " "
+ model.getValueAt(i, 5) + " "
+ model.getValueAt(i, 6) + " "
+ model.getValueAt(i, 7) + " "
+ (Integer)model.getValueAt(i, 8) + "\n";
}
// Update File
SaveMember sm = new SaveMember();
sm.update(p);
Inside our SaveMember.java we got:
public void update(String x) throws Exception {
File f = new File("Members/Members.txt");
PrintStream output = new PrintStream(f);
output.print(x);
So by now when we go and change the data and press the button update, it doesn't do anything at all, and doesn't replace the old data with the new.. Thanks for reading! :)
I'm not sure. If you have double checked that your code is executed at all (maybe you forgot to attach the ActionListener to your button - we all do that from time to time...) try flush the output stream and close the stream afterwards.
First check if your code in the for loop is executed at all. Set a breakpoint after the for loop and inspect the string p. If you are not familiar with debugging, print the string to the console with System.out.println(p).
If your code is NOT executed: Check why the method your code is in is not called. Perhaps you forgot to attach an action listener to your update button or the action listener has an early return under some circumstances.
If your code is executed: What do you do with the exception that is thrown by the method update? Make sure to log it with your logger or print it to the console (again via System.out.println(exc)). If you get a FileNotFoundException the path to the file is not correct.

How do I run this program in an applet?

package Homework;
import java.util.Scanner;
class FantasyGame{
public static void main ( String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to Supercalifragilisticexpialidocious Quest!");
System.out.println("Enter the name of your character: ");
String name;
name = scan.nextLine();
System.out.println("Welcome to Supercalifragilisticexpialidocious Quest, " + (name) + "! " + "You will now assign attributes to your character, the total value assigned must not exceed 15 or be under 0, or the points will be assigned by default! (Type any NUMBER to continue)");
int ans = scan.nextInt();
System.out.println("Enter Strength (0-15): ");
int str = scan.nextInt();
System.out.println("Enter Health (0-15): ");
int hp = scan.nextInt();
System.out.println("Enter Luck (0-15): ");
int lck = scan.nextInt();
if (str + hp + lck <= 15)
{
System.out.println("Congratulations! You have successfully created your character!");
System.out.println("Name: " + (name));
System.out.println("Strength: " + (str));
System.out.println("Health: " + (hp));
System.out.println("Luck: " + (lck));
}
if (str + hp + lck > 15)
{
System.out.println("You have give your character too many attribute points! Default values have been assigned.");
System.out.println("Name: " + (name));
System.out.println("Strength: " + (5));
System.out.println("Health: " + (5));
System.out.println("Luck: " + (5));
}
}
}
I want to make a text-based game for my history class and I know basic Java enough to make a small one with just variables and stuff but I don't know how I can make it so that it runs directly as an applet with a black background and white text that shows up and responds to what you type, like the code above does in the console.
I've tried the command prompt method but all I get is "Access is Denied."
Also, when I try to export in eclipse, the launch configuration always goes to a class I don't want. Sorry but I am really confused and need a lot of help on this.
to write a simple applet, http://docs.oracle.com/javase/tutorial/deployment/applet/ this tutorial from oracle will walk you through it fairly well, it shouldn't be too hard to rearrange your code then
I figured it out. I just exported my program as a .jar and used Jar2Exe and it worked perfectly. Thanks!
You have not made you class public and that is why you are getting error "Access is denied" because it is not visible any more. Compiler is not able to find that class. Just write
....
//change is here
public class FantasyGame
{
....
}
....
Thanks !

Categories