I am trying to change the value in a jTextField when I press the UP and DOWN arrow keys on the keyboard. When UP is pressed the value goes up by a set amount and when DOWN is pressed it goes down.
This is what I so far:
private void engineTxtKeyPressed(java.awt.event.KeyEvent evt) {
try{
int code = evt.getKeyCode();
double value = Double.parseDouble(engineTxt.getText());
if (code == KeyEvent.VK_UP) {
value = value + 25.00;
if ((value) > 100.00) {
value = 100.00;
engineTxt.setText(String.format("%.2f", value));
}
}
else if(code == KeyEvent.VK_DOWN){
value = value - 25.00;
if ((value) < 0.00) {
value = 0.00;
engineTxt.setText(String.format("%.2f", value));
}
}
} catch(Exception e){
System.out.println("error");
}
}
Before I put the try/catch in there, the error I got was:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "0,00"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
The list goes all the way down for many lines, basically it would flag anything with parsing and formats throughout the process.
The thing is that I have the same parsing for another 10 TextFields and there is no problem, but this is the only one with a keyEvent. After adding the try/catch I get my sout() message every time i press a key and the rest of the program continues just fine.
When you get to the line :
double value = Double.parseDouble(engineTxt.getText());
The string engineTxt.getText() returns (String) 0,00, which raises an error.
While
double value = Double.parseDouble("0");
System.out.println(value);
Wont raise an exception,
double value = Double.parseDouble("0,00");
System.out.println(value);
does.
Somewhere along the line, there is a , that should'nt be there.
Since this will work:
double value = Double.parseDouble("0.05");
System.out.println(value);
EDIT:
Like someone said in the comments, while the OP is not aware of it, it is a Possible duplicate of parseDouble in Java results to NumberFormatException
Related
Can someone tell me, why my app keep getting crashed. Cannot find solution for this and why its happening when TextField is empty
public void contanges(View v){
TextView wynik = (TextView)findViewById(R.id.wynik);
double b = Double.parseDouble(wynik.getText().toString());
if(wynik.getText().length() == 0 ){
wynik.setText("Bad opperand!");
}else if(b % 180 ==0){
wynik.setText("Bad opperand!");
}else {
BigDecimal a = new BigDecimal(wynik.getText().toString());
BigDecimal result = new BigDecimal("0");
result = new BigDecimal(1 / Math.tan(Math.toRadians(a.doubleValue())));
wynik.setText(result.toString());
}
}
Don't check for 0 length. Instead use TextTextUtils.isEmpty(). This way, you can check if the TextView actually has text to parse before you parse it.
TextView wynik = (TextView)findViewById(R.id.wynik);
if (TextUtils.isEmpty(wynik.toString().trim())) {
// Do your stuff here
}
Your error is in this line :
Double.parseDouble(wynik.getText().toString());
You are trying to parse an empty string to double which is not valid.
Add this line before that
if(wynik.getText().length() > 0){
Double.parseDouble(wynik.getText().toString());
}
Also it depends what you are passing as a textview value because if it is not been able to parse than also it will throw an exception
Try passing a double value to edittext when not empty.
I have a project and my Java program in Swing uses a double array to accept values from the user and print the total of the items, kind of like an order form.
Say the user enters no value in the text box, this shows an error and prevents further calculations.
My question is ,what should I code in order for the computer to understand that there is nothing entered in the text box , so just take the value as 0. I want to either do this by comparing/converting the double array value to a string and then continuing with calculations .
Here is my code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
double price[]=new double[]{0.25,8.55,0.50,0.25};
double amount[]=new double[4];
double quantity[]=new double[4];
quantity[0]=Double.parseDouble(jTextField1.getText());
quantity[1]=Double.parseDouble(jTextField2.getText());
quantity[2]=Double.parseDouble(jTextField3.getText());
quantity[3]=Double.parseDouble(jTextField4.getText());
for(int i=0;i<4;i++) // I want to use a for-loop or if-statement to
check if there is a value entered or not
{
if()
{
quantity[i] //no clue what to do here.
}
}
for(int i=0;i<4;i++)
{
{
amount[i]=quantity[i]*price[i];
}
}
jTextField5.setText(String.valueOf(amount[0]));
jTextField6.setText(String.valueOf(amount[1]));
jTextField7.setText(String.valueOf(amount[2]));
jTextField8.setText(String.valueOf(amount[3]));
First you would want to check if the text fields are empty or a String value before parsing them. And you will likely need to do it for all of the fields.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// check the values of the text fields including an or condition for regular expressions
if (jTextField1.isEmpty() || jTextField1.getText().matches("\\d+.?\\d*") {
// you can use something like a modal to alert
JOptionPane.showMessage(null,"Must enter a decimal value");
} else {
// do something with jTextField1
}
}
You can use
if (!jTextField1.getText().isEmpty())
I'm writing a method that will return an integer value. In the method I am prompting the user for the integer via console through the scanner class.
Because I am using the scanner method "scan.nextInt()", I am also checking for "InputMismatchException" error. I have placed the exception handling in a loop so that if the exception is caught the user is notified and the loop is reiterated. This will require the user to keep entering values until only an integer value has been entered.
However, my issue is after the first time it checks for the error, when it loops back, something is happening and the user is not prompted to enter a new value and the exception is thrown again. This of course results in an infinite loop.
I've researched and found a few cases related to the issue and I've tried performing relevant fixes but nothing I do seems to work and I don't understand what exactly is happening. Is the try block being skipped? Is there something wrong with my notation for the try block?
public static int inputCheck() {
int check=0;
int money = 0;
while (check==0) {
boolean error = false;
System.out.println("Please enter the amount of money your player has.");
while (true) {
try {
money = scan.nextInt();
}catch (InputMismatchException wrongInput) {
System.out.println("Error. Please enter an integer value." + wrongInput);
error = true;
}
break;
}
if (error==false)
check++;
}
return money;
}
EDIT Code has been edited and the "error" boolean value has been adjusted
The problem is in your catch when you set error equal to true. Once error is set to true, your loop is constructed in a way that has no way of exiting because error is never set to false therefore check is never incremented. I would re-structure this this loop system in general, there are much better approaches to handling this.
Try with this:
public static int inputCheck() {
int check = 0;
int money = 0;
while (check == 0) {
boolean error = false;
System.out.println("Please enter the amount of money your player has.");
try {
money = Integer.parseInt(scan.next());
} catch (Exception e) {
System.out.println("Error. Please enter an integer value." + e);
error = true;
}
if (error == false) {
check++;
}
}
return money;
}
while(true) is never false, so the loop never terminates if it doesn't hit the break statement
In the following if statement from a loop in my code, if the given oldsalary[i] doesn't meet these guidelines, I want to restore the previous numerical value of oldsalary[i] to "Error". However I want it to stay as oldsalary[i] since I will be displaying all the oldsalary[i] later in my code.
So basically when all the oldsalary[i] are displayed in another loop, I want to be able to see "Error" so it's know that something was wrong with that value.
I know the way I have it is completely wrong, I just put it like this to make sense. Sorry if it doesn't make any sense.
if(oldsalary[i] < 25000 || oldsalary[i] > 1000000){
JOptionPane.showMessageDialog(null, userinput[i]+"'s salary is not within
necessary limit.\n Must be between $25,000 and $1,000,000. \n If salary is
correct, empolyee is not eligible for a salary increase.");
double oldsalary[i] = "Error";
}
You can't store both the numerical value and an error indicator in a single double value.
Your best bet is to wrap the salary as an object that contains both the salary value and a boolean that indicates the error condition:
class Salary {
private double value;
private boolean error = false;
... constructor, getters and setters
}
And update your code to use the object instead. I.e.
if(oldsalary[i].getValue() < 25000 || oldsalary[i].getValue() > 1000000) {
oldsalary[i].setError(true);
...
}
So later you can do
if (oldsalary[i].isError()) {
// display error message
}
You can use an extra List that stores the indices that are no pass your requirement test.
List<Integer> invalidIndices = new ArrayList<>();
for (...){
if(oldsalary[i] < 25000 || oldsalary[i] > 1000000){
JOptionPane.showMessageDialog(null, userinput[i]+"'s salary is not within
necessary limit.\n Must be between $25,000 and $1,000,000. \n If salary is
correct, empolyee is not eligible for a salary increase.");
invalidIndices.add(i);
}
}
I'm trying to learn something about GUI, using NetBeans6.8, starting with the GUI section in The java tutorial.
There is a simple exercise for a Celsius-Fahrenheit converter. I want that to have two TextFields, one for Celsius and one for Fahrenheit temperature; if the user types in the celsius text field he got the result "printed" in the fahrenheit text filed. and vice versa.
So, i put on both the textfields one KeyTyped event, here's the code:
private void celsiusTextKeyTyped(java.awt.event.KeyEvent evt) {
int cels = Integer.parseInt(celsiusText.getText());
int fahr = (int)(cels * 1.8 + 32);
fahrText.setText(fahr + "");
}
private void fahrTextKeyTyped(java.awt.event.KeyEvent evt) {
int fahr = Integer.parseInt(fahrText.getText());
int cels = (int)(fahr / 1.8 - 32);
celsiusText.setText(cels + "");
}
It doesn't work. If i type something in a textfield i got this exception: java.lang.NumberFormatException: For input string: ""
The code that attach the listeners:
celsiusText.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
celsiusTextKeyTyped(evt);
}
});
fahrText.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
fahrTextKeyTyped(evt);
}
});
[However, i can't modify it, it's autogenerated.]
Method .getText() returns a string not a number, if that string contains non-numeric characters (i.e. a letter, a space, nothing at all) then parseInt will throw a NumberFormatException. Since your using KeyEvent, as soon as you press say "7", the event is fired before 7 is entered into the text box. Thus the text box still only contains "", which is where the error comes from. You may wish to also listen to the keyUp event instead.
You need to enclose your code in a try catch block.
private void fahrTextKeyTyped(java.awt.event.KeyEvent evt)
{
try
{
int fahr = Integer.parseInt(fahrText.getText());
int cels = (int)(fahr / 1.8 - 32);
celsiusText.setText(cels + "");
}
catch(NumberFormatException ex)
{
//Error handling code here, i.e. informative message to the user
}
}
An alternative is you could filter out non-numbers on keydown event, see example here - http://www.javacoffeebreak.com/java107/java107.html (Creating a custom component - NumberTextField)
I suspect that what's happened is that you added these handlers with something like celsiusText.addKeyListener, yes?
The thing is, that'll give you not just the KEY_TYPED events you wanted, but also KEY_DOWN and KEY_UP. The KEY_DOWN event will happen before the text is really entered into the field, so your code firing on that will see the field as blank still. Trying to convert the empty string to a number gives you a format exception.
The easiest way to fix this is the try/catch construct other people have been posting.
You probably set action to keyDown, this mean that even occur before the key value is "added" to textbox, while You retrieve the value from it is still empty "".
There is a simple exercise for a
Celsius-Fahrenheit converter
That is a really old example. The better approach is to use a DocumentListener, not a KeyListener.