This is My code:
Workbook workbook = new Workbook();
workbook.open(filename);
Worksheet worksheet = workbook.getWorksheets().getSheet(sheetno);
Cells cells=worksheet.getCells();
int num=cells.getMaxDataRow();
int num1=cells.getMaxDataColumn();
int OCount=1;
for (int n1=startpos+1;n1<endpos;n1++)
{ if (cells.checkCell(n1, Colno).getValue()==null )
{ Cell cell=cells.getCell(n1,Colno);
Style style = cells.getCell( n1,Colno).getStyle();
style.setColor(Color.TEAL);
cell.setStyle(style);
} else if(cells.checkCell(n1, Colno).getValue().toString().length()==0) { Cell cell=cells.getCell(n1,Colno);
Style style = cells.getCell( n1,Colno).getStyle();
style.setColor(Color.TEAL);
cell.setStyle(style); } else{ double intCounter = Double.parseDouble(cells.checkCell(n1,Colno).getValue().toString());
System.out.println(cells.checkCell(n1,Colno).getValue().toString());
if(intCounter!=Count){
Cell cell=cells.getCell(n1,Colno);
Style style = cells.getCell( n1,Colno).getStyle();
style.setColor(Color.YELLOW);
cell.setStyle(style);
}
}
Count=Count+1;
} workbook.save("C:\\output.xls",FileFormatType.EXCEL97TO2003);
I am trying to check that Sr no is in sequential order or not. it is working fine if there is no empty string " ". For empty string it throws
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String.
Thanks in Advance....
The problem is this line of code:
Double.parseDouble(cells.checkCell(n1,Colno).getValue().toString());
There you try to make a Double out of an empty String. Check the documentation and you will see that the NumberFormatException is the intended behavior. So you either have to check first if the String is empty or implement proper error handling.
Here a quote from the API for the method Double.parseDouble(...):
Throws: NumberFormatException - if the string does not contain a
parsable double.
its better to handle these cases by using a utility method.
private Double getCorrectedDouble(CellValues... ){
//check and handle empty fields
//return new Double(0) if the target is empty
}
Related
i am trying to get text of dynamic web table to excel sheet , sometimes text is present in rows of column and sometime it is not.. when text is present in the table row , i want to get text of that cell..using getText Method, But when Text is not present i want to write empty text and keep cell blank.. But it is giving NoSuchElementException.. how to handle that..?? any help would be appreciated.. thanks in advance..
String actualXpath_SL = beforeXpath_SL + j + afterXpath_SL;
String SL = driver.findElements(By.xpath(actualXpath_SL)).getText()
currentRow.createCell(0).setCellValue(SL);
To continue your programme when selenium doesn't find an element you can do two things.
Put the code inside a try block and handle the NoSuchElementException in the catch block.
String OneA = "";
try{
//find element
OneA = driver.findElement(By.xpath(actualXpath_1A)).getText();
}catch (NoSuchElementException e){
//stacktrace and other code after catching the exception
e.printStackTrace();
}
Or, you can use findElements and check the returned list is empty or not.
List<WebElement> elements = driver.findElements(By.xpath(actualXpath_1A));
String OneA = "";
if(!elements.isEmpty()){
OneA = elements.get(0).getText();
} else {
//Handle if no element present
}
the second solution avoids the exception and it is faster than waiting for the exception.
You should use .size()>0 rather isEmpty()
String actualXpath_2S = beforeXpath_2S + j + afterXpath_2S;
List<WebElement> eight = driver.findElements(By.xpath(actualXpath_2S));
String TwoS="";
if(eight.size()>0){
TwoS = eight.get(0).getText();
}
You have to update the logic for all if conditions that are using isEmpty.
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.
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());
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 !
I need to read data from the table JTable. The problem is that this table may contain empty cells. In this case the error message is:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
How to avoid this error message?
mdArrivals = new QueryTableModelFS();
tbArrivals = new JTable(mdArrivals);
String STA = mdArrivals.getValueAt(i,1).toString();
Just check it, Read object mdArrivals.getValueAt(i,1) and after it check if not null call toString
Object value = mdArrivals.getValueAt(i,1);
if (value!=null)
{
String sta = value.toString();
}
String value= String.valueOf(jTable1.getValueAt(row, col));