Creating a Search Button (Double cannot converted to String) - java

private void searchProduct()
{
try {
Product p = new Product();
//Read data
p.setId(Double.parseDouble(textID.getText()));
//Display data
textDescription.setText(String.valueOf(p.getDescription()));
textPrice.setText(String.valueOf(p.getUnitPrice()));
textUOM.setText(String.valueOf(p.getUnitOfMeasurement()));
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog(this.frame, "ID must be number", "Error",JOptionPane.ERROR_MESSAGE);
}
}
Hello recently I tried to put a button "Search" to find a product than equals to ID, but I don't know how to parse the ID than comes from the product class, I have a error.

Does the textID.getText() actually is a parseable double string? For instance "10.1" do but "10.1 " no.
Always I did this kind of conversion I use trim() to remove this extra white spaces as follow:
String stringValue = textID.getText();
if(stringValue != null) {
stringValue = stringValue.trim();
}
double doubleValue = Double.parseDouble(stringValue);
Se here http://docs.oracle.com/javase/8/docs/api/java/lang/Double.html#valueOf-java.lang.String- how to avoid NumberFormatException using a regular expression to text you string before try to convert it to double.

Related

Get double value from currency frormatted string

I'm using NumberFormat in my app to get the currency formatted Strings. Like if a user inputs 12.25 in the field then it will be changed to $12.25 based on locale. Here the Locale is en-US.
Now I want to get the 12.25 value as double form the formatted string.
To do that I have used:
NumberFormat.getCurrencyInstance().parse("$12.25").doubleValue();
Above line giving me the result of 12.25 which is my requirement. But suppose a user changed his locale to something else en-UK. Now for that locale above statement is giving me parseException. Because for the locale en-UK, currency string $12.25 is not parsable.
So is there any way to get the double value from currency formatted string irrespective of what the locale is?
I don't know either the below solution is perfect or not but it is working according to my requirement.
try {
return NumberFormat.getCurrencyInstance().parse(currency).doubleValue();
} catch (ParseException e) {
e.printStackTrace();
// Currency string is not parsable
// might be different locale
String cleanString = currency.replaceAll("\\D", "");
try {
double money = Double.parseDouble(cleanString);
return money / 100;
} catch (Exception ex) {
ex.printStackTrace();
}
}
return 0;
What about
new Double(NumberFormat.getCurrencyInstance().parse("$12.25").doubleValue());
and also you could use
Double.valueOf() creates a Double object so .doubleValue() should not be necessary.
also Double.parseDouble(NumberFormat.getCurrencyInstance().parse("$12.25"));
could work
Here's a little algorithm that may help you :
public static void main(String[] args) {
String cash = "R$1,000.75"; //The loop below will work for ANY currency as long as it does not start with a digit
boolean continueLoop = true;
char[] cashArray = cash.toCharArray();
int cpt = 0;
while(continueLoop){
try
{
double d = Double.parseDouble(cashArray[cpt]+"");
continueLoop = false;
}catch(NumberFormatException nfe){
cpt += 1;
}
}
System.out.println(cpt);
//From here you can do whatever you want....
String extracted = cash.substring(cpt);
NumberFormat format = NumberFormat.getInstance(Locale.US); //YOUR REQUIREMENTS !!!! lol
try {
Number youValue = format.parse(extracted);
System.out.println(youValue.doubleValue());
} catch (ParseException ex) {
//handle your parse error here
}
}
You should get as result here in the output:
2
1000.75

Exception Handling parse int and empty string

name = full_name_input.getText();
Fname = father_name_input.getText();
cnic = father_cnic_input.getText();
DOB = Integer.parseInt(DOB_input.getText());
Class_V = Integer.parseInt(class_input.getText());
prsnt_add = present_add_input.getText();
city = city_input.getText();
province = radio_text;
if(name.equals("") || Fname.equals("") || cnic.equals("") || DOB==0 || Class_V==0 || prsnt_add.equals("") || city.equals("") || province.equals(""))
{
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null, "Please fill all fields ! \n");
}
radio_text here is actually input from radio button and it is giving an error
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
actually i want to ensure that none of the jfields remain empty by the user
and if any field remains undefined it shows a popup please fill all fields
but when date of birth or class field or both remain unfiilled by the user it gives an error mentioned in the preeceding paragraph
What's happening is you're checking your fields after you try to set them, but the error occurs before that. For example, if DOB_input's text is "", DOB will throw an error trying to parse that (Integer.parseInt() can't deal with strings like that) before you see that it's empty. If you want to keep your if-statement, you'll have to move it above the lines where you set your values. However, to do that you'd need to tweak it a bit so you check the jfields' values. Like:
if(full_name_input.getText().equals("") || father_name_input.getText().equals("") ..... )
{
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null, "Please fill all fields ! \n");
}
I bet you have a problem here:
DOB = Integer.parseInt(DOB_input.getText());
Class_V = Integer.parseInt(class_input.getText());
Either DOB_input or class_input (or even both of them) getText() returns empty string. You should catch that exception and properly handle it like this:
try {
value = Integer.parseInt(input.getText());
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Illegal nuber format for field <field>");
return;
}
There is a problem with parsing number from String.
Did you check on which line this happened?
I suppose that here:
DOB = Integer.parseInt(DOB_input.getText());
Class_V = Integer.parseInt(class_input.getText());

Java netbeans adding comma to the table

Hi i am new to this and i am locked in this problem, i am trying to figure out whether you can add a set of values (1,000 ....) to another value. Though i successfully linked an input that automatically changed into comma to the table in SQL, it seems that it cannot add two values that has that format, my client wants to see a comma in a table and when inputting values.
Can you guide me where to change my code, is there an automatic format of these in SQL? Or probably in the java code, I read some articles that you cannot do a comma format before adding as it is done after that.
Here is the code I added to automatically change the numbers into having a comma:
private void FaremoKeyReleased(java.awt.event.KeyEvent evt)
{
String a = Faremo.getText();
if (a.isEmpty())
{
a = "";
}
else
{
a = a.replace(",","");
a = NumberFormat.getNumberInstance(Locale.ENGLISH).format(Double.parseDouble(a));
a = a.replace(".", ",");
}
Faremo.setText(a);
}
My problem is i cannot add values linked to my SQL with that format.
[Sample data - http://i.stack.imgur.com/kVQII.png]
When i am getting the sum of it I am using these:
private void SumActionPerformed(java.awt.event.ActionEvent evt) {
try{
String sql = "Select sum(Faremo),sum(Eatery),sum(Admin),sum(Jisoo),sum(Cav1),sum(Cav2),sum(Reliance1),sum(Reliance2)from Dataa";
pst = conn.prepareStatement(sql);
rs=pst.executeQuery();
if(rs.next()){
String sum1 = rs.getString("sum(Faremo)");
SFaremo.setText(sum1);
String sum2 = rs.getString("sum(Eatery)");
SEatery.setText(sum2);
String sum3 = rs.getString("sum(Admin)");
SAdmin.setText(sum3);
String sum4 = rs.getString("sum(Jisoo)");
SJisoo.setText(sum4);
String sum5 = rs.getString("sum(Cav1)");
SCav1.setText(sum5);
String sum6 = rs.getString("sum(Cav2)");
SCav2.setText(sum6);
String sum7 = rs.getString("sum(Reliance1)");
SReliance1.setText(sum7);
String sum8 = rs.getString("sum(Reliance2)");
SReliance2.setText(sum8);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
Update_table();
}
Are the table columns where you want to save the numbers defined as float?
If you are sure that a value will only be a number make the table columns int. Depending on the kind of numbers, you can choose a variety of Data Types:
float, decimal,real.
These could all work. It is all depending on what the numbers represent.
If you are going to do math IN the cells, a double gives rounding problems (link).
For more info on Data Types check Data Types.

Java - Parse delimited file and find column datatypes

Is it possible to parse a delimited file and find column datatypes? e.g
Delimited file:
Email,FirstName,DOB,Age,CreateDate
test#test1.com,Test User1,20/01/2001,24,23/02/2015 14:06:45
test#test2.com,Test User2,14/02/2001,24,23/02/2015 14:06:45
test#test3.com,Test User3,15/01/2001,24,23/02/2015 14:06:45
test#test4.com,Test User4,23/05/2001,24,23/02/2015 14:06:45
Output:
Email datatype: email
FirstName datatype: Text
DOB datatype: date
Age datatype: int
CreateDate datatype: Timestamp
The purpose of this is to read a delimited file and construct a table creation query on the fly and insert data into that table.
I tried using apache validator, I believe we need to parse the complete file in order to determine each column data type.
EDIT: The code that I've tried:
CSVReader csvReader = new CSVReader(new FileReader(fileName),',');
String[] row = null;
int[] colLength=(int[]) null;
int colCount = 0;
String[] colDataType = null;
String[] colHeaders = null;
String[] header = csvReader.readNext();
if (header != null) {
colCount = header.length;
}
colLength = new int[colCount];
colDataType = new String[colCount];
colHeaders = new String[colCount];
for (int i=0;i<colCount;i++){
colHeaders[i]=header[i];
}
int templength=0;
String tempType = null;
IntegerValidator intValidator = new IntegerValidator();
DateValidator dateValidator = new DateValidator();
TimeValidator timeValidator = new TimeValidator();
while((row = csvReader.readNext()) != null) {
for(int i=0;i<colCount;i++) {
templength = row[i].length();
colLength[i] = templength > colLength[i] ? templength : colLength[i];
if(colHeaders[i].equalsIgnoreCase("email")){
logger.info("Col "+i+" is Email");
} else if(intValidator.isValid(row[i])){
tempType="Integer";
logger.info("Col "+i+" is Integer");
} else if(timeValidator.isValid(row[i])){
tempType="Time";
logger.info("Col "+i+" is Time");
} else if(dateValidator.isValid(row[i])){
tempType="Date";
logger.info("Col "+i+" is Date");
} else {
tempType="Text";
logger.info("Col "+i+" is Text");
}
logger.info(row[i].length()+"");
}
Not sure if this is the best way of doing this, any pointers in the right direction would be of help
If you wish to write this yourself rather than use a third party library then probably the easiest mechanism is to define a regular expression for each data type and then check if all fields satisfy it. Here's some sample code to get you started (using Java 8).
public enum DataType {
DATETIME("dd/dd/dddd dd:dd:dd"),
DATE("dd/dd/dddd",
EMAIL("\\w+#\\w+"),
TEXT(".*");
private final Predicate<String> tester;
DateType(String regexp) {
tester = Pattern.compile(regexp).asPredicate();
}
public static Optional<DataType> getTypeOfField(String[] fieldValues) {
return Arrays.stream(values())
.filter(dt -> Arrays.stream(fieldValues).allMatch(dt.tester)
.findFirst();
}
}
Note that this relies on the order of the enum values (e.g. testing for datetime before date).
Yes it is possible and you do have to parse the entire file first. Have a set of rules for each data type. Iterate over every row in the column. Start of with every column having every data type and cancel of data types if a row in that column violates a rule of that data type. After iterating the column check what data type is left for the column. Eg. Lets say we have two data types integer and text... rules for integer... well it must only contain numbers 0-9 and may begin with '-'. Text can be anything.
Our column:
345
-1ab
123
The integer data type would be removed by the second row so it would be text. If row two was just -1 then you would be left with integer and text so it would be integer because text would never be removed as our rule says text can be anything... you dont have to check for text basically if you left with no other data type the answer is text. Hope this answers your question
I have slight similar kind of logic needed for my project. Searched lot but did not get right solution. For me i need to pass string object to the method that should return datatype of the obj. finally i found post from #sprinter, it looks similar to my logic but i need to pass string instead of string array.
Modified the code for my need and posted below.
public enum DataType {
DATE("dd/dd/dddd"),
EMAIL("#gmail"),
NUMBER("[0-9]+"),
STRING("^[A-Za-z0-9? ,_-]+$");
private final String regEx;
public String getRegEx() {
return regEx;
}
DataType(String regEx) {
this.regEx = regEx;
}
public static Optional<DataType> getTypeOfField(String str) {
return Arrays.stream(DataType.values())
.filter(dt -> {
return Pattern.compile(dt.getRegEx()).matcher(str).matches();
})
.findFirst();
}
}
For example:
Optional<DataType> dataType = getTypeOfField("Bharathiraja");
System.out.println(dataType);
System.out.println(dataType .get());
Output:
Optional[STRING]
STRING
Please note, regular exp pattern is vary based on requirements, so modify the pattern as per your need don't take as it is.
Happy Coding !

Creating multiple identical text verify listeners in eclipse-rcp/swt

I'm trying to validate the input of multiple text boxes (i.e. they should be a number), and found the useful code snippet below here.
However, if I have three text boxes (text, moreText and evenMoreText), how can I apply a verify listener with the same functionality to each, without having to repeat the (.addVerifyListener(new VerifyListener() {...) code three times?
I don't want to implement a switch statement or similar (to decide which text box to apply it to), I want something more generic (that I can perhaps make available for other classes to use in the future).
text.addVerifyListener(new VerifyListener() {
#Override
public void verifyText(VerifyEvent e) {
final String oldS = text.getText();
final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
try {
BigDecimal bd = new BigDecimal(newS);
// value is decimal
// Test value range
} catch (final NumberFormatException numberFormatException) {
// value is not decimal
e.doit = false;
}
}
});
Define the VerifyListener beforehand and get the actual Text from the VerifyEvent:
VerifyListener listener = new VerifyListener()
{
#Override
public void verifyText(VerifyEvent e)
{
// Get the source widget
Text source = (Text) e.getSource();
// Get the text
final String oldS = source.getText();
final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
try
{
BigDecimal bd = new BigDecimal(newS);
// value is decimal
// Test value range
}
catch (final NumberFormatException numberFormatException)
{
// value is not decimal
e.doit = false;
}
}
};
// Add listener to both texts
text.addVerifyListener(listener);
anotherText.addVerifyListener(listener);
If you want to use it in other places as well, create a new class:
public class MyVerifyListener implements VerifyListener
{
// The above code in here
}
and then use:
MyVerifyListener listener = new MyVerifyListener();
text.addVerifyListener(listener);
anotherText.addVerifyListener(listener);

Categories

Resources