Okay so I am stuck and I am sure it is a simple solution. Basically I am beginning my initial conversion, or at least constructing a demo, to a keyword driven framework for selenium testing. Each row will contain data that will be used to drive the test. After the row is complete, the next row will contain the next test and so on. So I just started and I am having a little bit of trouble. Here is my code:
public List<String> getRowData(String row){
Sheet sheet = null;
List<String> getContents = new ArrayList<>();
try{
sheet = getWorkBook().getSheet("test");
for(int i=0; i<sheet.getRow(i).length; i++){
getRowData = sheet.getRow(i);
for(Cell rowData : getRowData){
System.out.print(String.format("Row info: %s\n", rowData.getContents()));
getContents.add(rowData.getContents());
}
}
}catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.print("This is an exception!");
} catch (NullPointerException np){
System.out.print("File does not exist!");
}return getContents;
}
The strings for the exceptions are just placeholders, not going to be final. But I am getting an ArrayIndex....Exception. I do understand a little why I am getting the error, but I am trying to obviously break out of the loop once the row or row content is empty. I implemented a condition such that
if(sheet.getRow(i) == null){
break;
}
But it still evaluated and provides the same exception. I am stuck and would like your help in trying to break out of the loop when there are no contents. Thank you
change for(int i=0; i<sheet.getRow(i).length; i++)
to:
for(int i = 0; i < sheet.getRows(); i++){
if(sheet.getRow(i) == null) break;
//rest of the code
}
But are you sure you want to break the loop on an empty row and not continue to the next row?
Related
I have a problem with reading xls files into Java usin jxl library.
Could you tell me what is wrong my code? I attached below. Something is wrong wif fillData method. The console returns:
Exception in thread "Thread-1" java.lang.NullPointerException
at StudentLogin.fillData(StudentLogin.java:104)
at StudentLogin.<init>(StudentLogin.java:70)
at Login$PBar.run(Login.java:103)
at java.base/java.lang.Thread.run(Unknown Source)
Thank you in advance for your help.
public void fillData(File file) {
Workbook workbook = null;
try {
workbook = Workbook.getWorkbook(file);
}
catch (Exception e) {
}
Sheet sheet = workbook.getSheet(0);
headers.clear();
for (int i = 0; i < sheet.getColumns(); i++) {
Cell cell = sheet.getCell(i, 0);
headers.add(cell.getContents());
}
data.clear();
for (int j = 1; j < sheet.getRows(); j++) {
Vector<String> d = new Vector<String>();
for (int i = 0; i < sheet.getColumns(); i++) {
Cell cell = sheet.getCell(i, j);
d.add(cell.getContents());
}
d.add("\n");
data.add(d);
}
}
I would recommend you to take a look at two parts of the method fillData:
1) try-catch probably hides the problem: in the beginning, you call the method getWorkbook which, according to its java doc, can throw an exception if, for instance, the file does not exist. However, you call the getWorkbook in a try-catch block which does not even print the exception. Consequently, if anything goes wrong you will get a null pointer at workbook.getSheet(0) cause the variable workbook keeps holding a null value (as you assign null in the first line of the method). To avoid this problem you can add a printStackTrace in the catch block. Another option is to add a throws Exception in the method definition and remove the try-catch block. Doing this, you may find the real cause of the null pointer.
try {
workbook = Workbook.getWorkbook(file);
} catch (Exception e) {
e.printStackTrace();
}
OR
public void fillData(File file) throws Exception {
Workbook workbook = Workbook.getWorkbook(file);
....
}
2) Is the variable headers globally initialized? I can't see in your code where you initialize the variable headers (doing like headers = new ArrayList()). If you did not do it, you will get a null pointer at headers.clear(). Moreover, the same problem can happen with the variable data if you don't initialize it.
the following method produces an output.
The only problem with this code is that after the end of report, it adds two extra lines to the file, while the need is only of one empty line.
i have tried various combinations but uanble to proceed.
Can anybody help here?
private static void save_player_info(String[][] data, String player) {
player=player.toLowerCase();
try {
PrintWriter printWriter= new PrintWriter(new File("out4.txt"));
for(int row=1;row<data.length;row++){
String playerName=data[row][0].toLowerCase();
if(playerName.indexOf(player)!=-1){
String[] fields=data[0];
String[] values=data[row];
for (int i=0;i<fields.length;i++){
printWriter.printf("%21s : %s\n",fields[i],values[i]);
}
printWriter.print("\n");
}
}
printWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Instead of unconditionally adding a blank line after the inner for loop, you should conditionally add a blank line before the inner for loop, if not the first time.
Also, you should use %n in printf for the newline, and println() for the blank line. And you should put the close() in a finally block, or use try-with-resources. Showing finally block solution here for Java version independence.
PrintWriter printWriter= new PrintWriter(new File("out4.txt"));
try {
boolean first = true;
for(int row=1;row<data.length;row++){
String playerName=data[row][0].toLowerCase();
if(playerName.indexOf(player)!=-1){
String[] fields=data[0];
String[] values=data[row];
if (first)
first = false;
else
printWriter.println();
for (int i=0;i<fields.length;i++){
printWriter.printf("%21s : %s%n",fields[i],values[i]);
}
}
}
} finally {
printWriter.close();
}
Since you are using new line in
printWriter.printf("%21s : %s\n",fields[i],values[i]);
So you can skip
printWriter.print("\n");
You can wrap an if statement around the line which prints a newline character to check if row is less than data.length. Also, you can use println() instead of print("\n").
for(int row=1;row<data.length;row++){
...
if(row < data.length - 1){
printWriter.println();
}
}
I am trying to write a new document based on the Objects I have in my side2[] array.
Now unfortunately, some indexes are null in this array, and when it hits one of them, it just gives me a NullPointerException. This array has 10 indexes, but in this case not all of them are needed. I have tried the try catch statement in hopes of continuing after it comes across a null, but it still stops execution and doesn't write a new document.
The stack (srail) that is part of the object contains the data I want to print out.
Here is my code:
// Write to the file
for(int y=0; y<=side2.length; y++)
{
String g = side2[y].toString();
if(side2[y]!=null){
while(!side2[y].sRail.isEmpty())
{
out.write(side2[y].sRail.pop().toString());
out.newLine();
out.newLine();
}
out.write(g);
}
}
//Close the output stream/file
out.close();
}
catch (Exception e) {System.err.println("Error: " + e.getMessage());}
The problem is that the code calls toString() on the side2[y] object before checking it for null. You can skip null objects by adding a condition at the top of the loop, like this:
for(int y=0; y<=side2.length; y++) {
if(side2[y] == null) {
continue;
}
String g = side2[y].toString();
// No further checks for null are necessary on side2[y]
while(!side2[y].sRail.isEmpty()) {
out.write(side2[y].sRail.pop().toString());
out.newLine();
out.newLine();
}
out.write(g);
}
Here is my method so far:
public void readfile(JTable table) {
try{
BufferedReader in = new BufferedReader( new FileReader("out.txt"));
for(int i = 0; i<10; i++) {
for(int j = 0; j<5; j++) {
table.setValueAt(in.readLine(), i, j);
}
}
in.close();
}catch (Exception e) {
System.err.println("error: " + e.getMessage());
}
}
Here are the contents of out.txt:
test1
test2
test3
test4
test5
Where I run the program and attempt to load the file to the table, nothing happens. I also get an output that says the following:
error: 0 >= 0
Help me please?
I would narrow your problem down to a smaller problem, solve this smaller problem, and then widen it until you have want you want.
Think of the contents of a File as a big blob of text.
Think of the table as a Vector of Vectors.
Smaller problem: How do I convert a big blob of text into a Vector of Vectors? You need to be able to sove this problem first before tackling File I/O or DefaultTableModels.
I have a method wherein i have to return a 2D String array.
The part of code for that method is as follow:-
public String[][] retrieveData(){
try{
int noOfRows = 0;
pstmt = con.prepareStatement("select * from category");
ResultSet rs = pstmt.executeQuery();
while(rs.next())
noOfRows++;
rs.first();
categoryContent = new String[noOfRows][noOfCols];
for(int i = 0 ; i < noOfRows ; i++){
for(int j = 0 ; j < noOfCols ; j++){
if(j == 0){
Integer categoryNo = new Integer(rs.getInt(1));
categoryContent[i][j] = categoryNo.toString();
}
else{
categoryContent[i][j] = rs.getString(j+1);
}
}
rs.next();
}
return categoryContent ;
}
catch(Exception e){
e.printStackTrace();
}
}
The error which i am getting at compile time is as follows:-
I:\DynamicWebpageCreator\WEB-INF\classes>javac *.java
Category.java:134: missing return statement
public String[][] retrieveData(){
^**
1 error
Please help me soon. I am stuck with it.
All the answers are highly appreciated!
If an exception is thrown, you'll print the stack trace, but never return anything. That's what the compiler is complaining about.
In general, "handling" exceptions like this is a really bad idea:
Log any exception information somewhere more appropriate than just the console
Don't catch bare Exception - catch specific exceptions
If you can't actually handle an exception, let it propagate up the call stack
In this case I'd suggest you should probably just change your method to declare which exceptions might be thrown, and remove the try/catch block.
If you genuinely want to catch exceptions (specific ones, mind) then you'll need to work out what you want to return in that case.
You have indicated the return command in side the try statement try this way it will work.
public int x(){
try{
}catch (Exception e){}
return x;
}