Having converting and getting data problems [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I wrote a program that calculates Acceleration. This is how it looks:
http://prntscr.com/57yngo
when you press that button it show a dialog message that is a part of JOptionPane. The data you enter in fields are Strings I convert them to double by doing :
double name = Double.valueOf(String);
The problem is if you inserted a String value instead of a double value in the fields you and pressed the button that sends the acceleration total the program badly crash. I really need a solution to fix that!
If you said why did you set the inserted value as String I will answer
that this is the only way to do the
Textfieldname.gettext();
If you knew a way to get a double only from a text field please tell me it.

Try something like this:
public static void main(String[] args) {
String[] values = {"1.0", "2.0", "a"};
for (String value: values) {
System.out.println(getValue(value));
}
}
private static Double getValue(String valueString) {
Double result;
try {
result = Double.valueOf(valueString);
} catch (NumberFormatException e) {
result = 0.0;
}
return result;
}

You have to catch NumberFormatException to handle wrong input
Example:
try {
result = Double.valueOf(valueString);
} catch (NumberFormatException e) {
//show alert and clean field or something else
}

Check IF the String in the textfield can be parsed to Double before the conversion. If you expect simple String values like 3.01 or 150 then a simple regular expression would do:
import java.util.regex.Pattern;
// some stuff in your class
// and in your action listner
Pattern p = Pattern.compile("\\d+|\\d+\\.\\d+"); //digits or digits dot digits
String valueToTest = Textfieldname.gettext();
boolean canBoConverted = p.matcher(valueToTest).matches();
if (canBoConverted) {
double name = Double.valueOf(String);
// do something with name
} else {
// idicate a bad input value to the user
}
If you need a wider range o possible values than you can use the pattern from the Double class documentation
Also please remember that a programmer should always validate user input against whats acceptable.

Related

Is there any other possibility to convert String to double? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm learning a Java and I have a problem in one of my project called "point of sale". When the program reads a barcode from the user, it starts to search for the proper product in products.txt. When it finds the product, next it should set the values to the created object. The problem occurs when I try to convert String to double. I spend almost 2 hours to solve it and I didn't succeed. I need your help.
So I have tried:
double dbl = Double.valueOf(parts[2]);
p.set_price(dbl);
double dbl = Double.parseDouble(parts[2]);
p.set_price(dbl);
double dbl = new Double(parts[2]);
p.set_price(dbl);
And also tried a combinations like this (but it doesn't work):
p.set_price(Double.valueOf(parts[2].ToString()));
There is only a method
public void newSale() {
Products p = new Products();
// Barcode
System.out.print("Barcode:");
p.set_barcode(scan.next());
// Find the product
try{
File file = new File("products.txt");
Scanner scan = new Scanner(file);
while(scan.hasNextLine()) {
String x = scan.next();
if(x.contains(p.get_barcode())) {
String[] parts = x.split(";");
p.set_barcode(parts[0]);
p.set_name(parts[1]);
try{
double dbl = Double.valueOf(parts[2]);
p.set_price(dbl);
}catch(NumberFormatException ex){
System.err.println("Error: " + ex.getMessage());
}
}
}
}catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
System.out.print(p.get_name()+"\t"+p.get_price());
}
It will be good if anyone will help me to understand why conversion and assigning don't work.
Dot devides integer with fraction in Double. In products.txt, change commas to dots in prices. That should help :)

How do I check for an empty string in a Boolean statement? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have an assignment where I have to attach the letters "un" to any word that the user inputs (unless the inputted word already has "un" in front of it, in which case I just return the inputted word). I'm testing my method but I encountered one problem: my program keeps returning an error if I were to test for an empty input. Here is my code:
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter: ");
String input = keyboard.nextLine();
if(input.substring(0,2).equalsIgnoreCase("un"))
{
System.out.println(input);
}
else if(input.equals(""))
{
System.out.println("un");
}
else
{
System.out.println("un" + input);
}
So I wanted to ask how I can test for an empty input/blank string since, evidently, the "" quotations do not work.
There's nothing wrong with checking input.equals("") per-se. The problem is that you have another test beforehand that throws an exception if input is shorter than 2 characters.
There are several ways to solve this, but I'd just simplify things and use startsWith. An empty string doesn't really need a special case of its own - just slap un before it, and you'll get un:
if (input.toLowerCase().startsWith("un")) {
System.out.println(input);
} else {
System.out.println("un" + input);
}
You are having this problem because you are trying to get the substring of string that doesnt have the required length. Put the empty string check first.
if(input.equals("")||input.length==1)
{
System.out.println("un");
}
else if(input.substring(0,2).equalsIgnoreCase("un"))
{
System.out.println(input);
}
else
{
System.out.println("un" + input);
}
If this weren't homework, and the library could be used for other things ( using it in this single purpose may be overkill ), you could use StringUtils.PrependIfMissing().
It does exactly this and handles nulls as well.

How to limit user to input only numbers?

I am currently creating this java GUI that will ask the user to input 10 entries, then use the values to execte the next action.
I want only numbers or decimal point to be inputted inside such that it can only be a float value.
If it is not number or decimal point, it should prompt the user to input that specific entry again before the next action is executed.
How should I do it?
Wong,
not sure whether you are using Swing or not...
Ages ago I had the same problem and I solved it with creating a class RestrictedTextField extending JTextField. In the constructor I added a key listener (addKeyListener(new RestrictedKeyAdapter());)
private class RestrictedKeyAdapter extends KeyAdapter {
#Override
public void keyReleased(KeyEvent e) {
if (getText().equals("")) {
oldString = "";
return;
} else {
// if you cannot parse the string as an int, or float,
// then change the text to the text before (means: ignore
// the user input)
try {
if (type.equals("int")) {
int i = Integer.parseInt(getText());
oldString = getText();
} else if (type.equals("float")) {
float f = Float.parseFloat(getText());
oldString = getText();
} else {
// do nothing
}
} catch (NumberFormatException el) {
setText(oldString);
}
// if the text is identical to the initial text of this
// textfield paint it yellow. If the text was changed
// paint it red.
if (initialString.equals(getText())) {
setForeground(Color.YELLOW);
} else {
setForeground(Color.RED);
}
}
}
}
The idea is, that every time the user presses a key in the textfield (and releases it then), the text in the textfield is parsed. If the component should accept only floats for example then the component tries to parse it as an float (Float.parseFloat(..)). If this parsing is successful everything is fine. If the parsing fails (an NumberFormatException is thrown) then the old text is written back into the textfield (literally ignoring the user input).
I think you can add the KeyAdapter directly to the JTextField without creating a dedicated class for that, but with this solution you can remember the initial string and the old string.
you can play around with the code.. you can change the colour of the textfield if the input is valid or not (or like in my code snippet if the text is identical to the initial string).
one additional comment: I set the 'type' of the textfield in a variable with the name 'type', which is simply a String with the values "int", "float", etc.... a better solution would be here for example an enum of course...
I hope this is helpful...
timo
There are various options for what you would like to do. You can check here for one example of doing so. Another example could be to use Formatted TextFields, as shown here.
On the other hand, upon submission, you can try to parse the value to a float or double. If you get any exceptions, then, the value is not a number.
Lastly, you can use Regular Expressions. An expression such as ^\\d+(\\.\\d+)?$ should match any integer or floating point number.

How to check an empty Double JTextField

I've been working this for 2 days but I can't still figure how to check if the jtextfield is empty (Double not String) before passing it to my database.
I figured it out how to validate String if the field is empty, but I need to put the right code on how to validate Double if the field is empty.
Thanks in advance.
Here's my code:
private void saveButton3ActionPerformed(java.awt.event.ActionEvent evt) {
String inventcodef = inventCodeField.getText();
String inventnamef = inventNameField.getText();
String categ = cmbname.getSelectedItem().toString();
double inventreorderf = Double.parseDouble(inventReorderField.getText());
..............
if ((inventCodeField.trim().Length()==0) || (inventNameField.trim().Length()==0)
To enforce formatting (numeric etc) you can use JFormattedTextField.
To ensure values are not blank see No blanks in JTextField
You are reading the double at first as a String. So, you can do something like this:
double inventreorderf;
if (inventReorderField.getText().trim().length == 0)
{
//Do something which should happen when the field is empty
}
else
{
try
{
inventreorderf = Double.parseDouble(inventReorderField.getText());
}
catch (Exception e)
{
//The user has entered an invalid number. Notify him/her here.
}
}

How to validate if Text entered is a numeric number?

I have a calculation application which I need to validate the fields to check if the values entered are numeric numbers and not alphanumeric. I have some ideas about the codes.
Please guide me if I have done anything wrong or seem noob as this is my first time trying out Swing.
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
String text1 = jTextField1.getText(); // TODO add your handling code here:
}
private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {
String text2 = jTextField2.getText(); // TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (text1 and text2 != <numeric number>){
JOptionPane.showConfirmDialog(null, "Please enter numbers only", "naughty", JOptionPane.CANCEL_OPTION);
}
// First we define float variables.
float num1, num2, result;
// We have to parse the text to a type float.
num1 = Float.parseFloat(jTextField1.getText());
num2 = Float.parseFloat(jTextField2.getText());
// Now we can perform the addition.
result = num1+num2;
// We will now pass the value of result to jTextField3.
// At the same time, we are going to
// change the value of result from a float to a string.
jTextField3.setText(String.valueOf(result));
// TODO add your handling code here:
}
Please do help. By the way why does my NetBeans keep informing me that it does not recognize the "JOptionPane" Command?
Float.parseFloat() will throw a NumberFormatException if the String isn't numeric and cannot be parsed into a Float. You can add a try-catch block to check for this condition:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
float num1, num2, result;
try {
num1 = Float.parseFloat(jTextField1.getText());
num2 = Float.parseFloat(jTextField2.getText());
result = num1+num2;
jTextField3.setText(String.valueOf(result));
} catch (NumberFormatException e) {
JOptionPane.showConfirmDialog(null, "Please enter numbers only", "naughty", JOptionPane.CANCEL_OPTION);
}
}
If alphanumeric input is not valid for the Swing component in the first place, then instead of validating this post-entry, you should restrict the component to accept only certain format in the first place.
Using the formatters that Swing provides, you can set up formatted text fields to type dates and numbers in localized formats. Another kind of formatter enables you to use a character mask to specify the set of characters that can be typed at each position in the field. For example, you can specify a mask for typing phone numbers in a particular format, such as (XX) X-XX-XX-XX-XX.
That said, you can, among other things, use Integer.parseInt(String s) to see if an arbitrary string can be parsed into an int; the method throws NumberFormatException if it can't. There are also Double.parseDouble, etc.
See also
Java Tutorials/Swing/How to use Formatted Text Field
How to use the Focus Subsystem/Input Validation
Java Tutorials/Internationalization/Formatting - Numbers and Currencies
Related questions
A simple way to create a text field (or such) that only allows the user to enter ints/doubles in Java?
A textbox class only accept integers in Java
Validating an integer or String without try-catch - java.util.Scanner option
try {
Integer.parseInt(foo);
} catch (NumberFormatException e) {
// Naughty
}
Try this:
String temp = txtField.getText();
try
{
int val = Integer.parseInt(temp);
}
catch(NumberFormatException e) {
System.out.println("Invalid");
}
To make it more enjoyable, use JOptionPane (makes it more more interactive)
textFieldCrDays = new JTextField();
textFieldCrDays.addKeyListener(new KeyAdapter() {
//// validate onlu numeric value
public void keyTyped(KeyEvent e) {
if (textFieldCrDays.getText().length() < 3 && e.getKeyChar() >='0' && e.getKeyChar() <= '9')
{
// Optional
super.keyTyped(e);
}
else
{
// Discard the event
e.consume();
}
}
});
A relatively old question, but I figured I would take a shot at it, to maybe help out the random Google Searches.
Another approach someone could take to minimise code and reduce the number of additional classes is to add a KeyListener for the keyType event and check for the Char value. This isn't very portable (you can't use region specific formatting such as numerical punctuation), but this could be quite helpful for straight integers.
You could also do a relative length here as well:
textField.addKeyListener(new KeyAdapter()
{
#Override
public void keyTyped(KeyEvent keyEvent)
{
if (textField.getText().length() < 3 && keyEvent.getKeyChar() >= '0' && keyEvent.getKeyChar() <= '9')
{
// Optional
super.keyTyped(keyEvent);
}
else
{
// Discard the event
keyEvent.consume();
}
}
});
You can also add another event listener to validate the entire integer for further processing (the entire number must be > 800 and < 5220 for example).
A good place for this would be on the focusLost event(?).
If you are doing these features frequently, it would be best to subclass the JTextField class to provide this functionality.
EDIT: Using Character.isLetter(keyEvent.getKeyChar()) is even more clear.

Categories

Resources