Apache Poi: Exception when reading spreadsheet data - java

I'm reading data from a spreadsheet and an exception is occurring, but I can't figure out where it is.
int quantidade_linhas = sheet.getLastRowNum();
for (int i = 0; i < quantidade_linhas; i++) {
String nomes = sheet.getRow(i).getCell(0).getStringCellValue();
String sobrenomes = sheet.getRow(i).getCell(1).getStringCellValue();
System.out.println("Dados: " + nomes + " " + sobrenomes);
}
PlanilhaSerLida.close();
System.out.println("Fechando a planilha!\n");
}
Error Console:
Exception in thread "main" java.lang.NullPointerException at
arquivo.lerDados.main(lerDados.java:32)
Line 32 where the error is pointed out is precisely the string nomes

An excel spreadsheet can have blank rows that are empty and thus have no cell values. I'd first debug your program with this code, put it right under the for-loop declaration:
System.out.println("Row " + i + " null?: " + (sheet.getRow(i) == null))
That prints for each row the index and whether the row is null or not. After that you can decide to either fix the spreadsheet, make your program ignore empty (null) rows or do both.
Also a tip, if one of the rows contains a numerical value it will cause an exception since it won't auto convert the int to a string. Make a utility function that checks cell.getCellType() for a (CellType) string or a numerical value and then converts when needed.

Related

IndexOutOfBoundsException when writing a list of players to a file

I'm working on assignment for OOP and am stuck on the last step which is, "Write all players to an output file that has a similar format of the input file."
I need to know how to print all the info in the main to an output file with the same format as the input file and I use here ArrayList. it's working fine when I print the name and the height but when I want to print season or score, an exception appears.
pw.write(t1.getName() + "; " + t1.getCity() + "\n");
for (int m = 0; m < p2.size(); m++) {
pw.print(t1.getPlayerList().get(m).getName() + "; " + t1.getPlayerList().get(m).getHeight() + "; ");
pw.println(t1.getPlayerList().get(m).getSeasonalRecords().get(m).getScores());
}
it works well, but when I write
pw.println(t1.getPlayerList().get(m).getSeasonalRecords().get(m).getScores());
appear something is wrong
that the exceptions that I got
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.rangeCheck(ArrayList.java:657)
at java.util.ArrayList.get(ArrayList.java:433)
The root cause of the issue is described in the comments: index m exceeds the number of seasonal records and definitely it may take another nested loop to print the seasonal records.
It may be better to replace for loops with indexes with for-each to make the code shorter, more readable and less prone to the mentioned errors:
for (var player : t1.getPlayerList()) {
pw.println(player.getName() + "; " + player.getHeight() + "; ");
for (var seasonRecord : player.getSeasonalRecords()) {
pw.println(seasonalRecord.getScores());
}
}

How to remove blank lines in middle of a string Android

String Address[] = mSelectedaddress.split("\\|");
address.setText(
Address[1] + "\n"
+ Address[2] + "\n"
+ Address[3] + "\n"
+ Address[4]);
Actual Output:
Address 1
Address 2
=> Blank line
City
Wanted Output:
Address 1
Address 2
City
If u can see my above code there are some scenario where Address[positon] may return blank text that time how can i remove that line if it is blank.
String adjusted = adress.replaceAll("(?m)^[ \t]*\r?\n", "");
When you build your string, check to see if the string is empty before you add it.
StringBuilder builder = new StringBuilder();
for(int it = 0; i < Address.length; i++) {
if(Address[i] != "")
builder.append(Address[i]);
}
address.setText(builder.toString());
}
The simplest thing I can think of that should do the trick most of the time:
mSelectedaddress.replaceAll("[\\|\\s]+", "|").split("\\|");
This will remove multiple |'s (with or without spaces) in a row. Those are the cause of your empty lines.
Example:
"a|b|c|d|e||g" -> works
"a|b|c|d|e| |g" -> works
"a|b|c|d|e|||g" -> works

Having trouble with string concatenation

I was trying to concatenate a string to itself + something else, like this:
String example = " "
for (int i = 0; i < 5; i++) {
if (condition OK) {
example = example + "\nAnother text";
}
}
JOptionPane.showMessageDialog(null, example);
In my mind, it should've print " (new line)Another text" but it seems to work only with the last entry in my "Another text". Like, if the condition inside the "for" loop is OK 3 times, it prints " (new line)Another text(3)" instead of " (new line) Another Text(1) (new line) Another text(2)...
Any idea of what may be happening?
EDIT: after realizing that my code was fine, I followed afzalex recommendation and found out the error was in my condition. Thanks bro
I used below program I got expected output.
String example = " ";
for (int i = 0; i < 5; i++) {
if (i == 1 || i == 3) {
example = example + "\nAnother text";
}
}
System.out.println(example);
Output:
Another text
Another text
So, probably it could be something wrong with JOptionPane.showMessageDialog(null, example); If it is being interpreted as HTML in the end, then better use </br> instead of \n, that can give you new line.

Loop not iterating full length

I'm passing a String to a method that has commas in as delimiters.
"TMJ,Emma,Sarah"
I tokenize this String using ',' as the regular expression to split.
I then iterate the length of the tokenized array comparing each element against a HashMap of all possible values. If the value being tested is a key in the HashMap then i get the key's value and store that in another String.
I want to append each value of the key to the String that holds the values.
It seems to iterate only once, then jumps out of the loop and returns only the first thing it finds in the hashmap.
Could anyone explain why? Thanks in advance Matt.
public static String getrecipientIntergerValues(String recipient) {
Log.e(TAG, "recipient string list passed in to app obj = " + recipient);
String[] tokenizedRecipient = recipient.split(",");
String recipientAsInteger = "";
for(int i = 0; i < tokenizedRecipient.length; i++){
Log.e(TAG, "tokenizedRecipient = " + tokenizedRecipient[i].toString());
}
Log.e(TAG, "tokenizedRecipient length = " + tokenizedRecipient.length);
for(int i = 0; i < tokenizedRecipient.length; i++){
if(recipients.containsKey(tokenizedRecipient[i].toString())){
Log.e(TAG, "hashmap contains key " + tokenizedRecipient[i].toString() + "with value " + recipients.get(tokenizedRecipient[i].toString()));
String integerValueOfName = recipients.get(tokenizedRecipient[i].toString());
recipientAsInteger = recipientAsInteger + integerValueOfName + ",";
}
}
Log.e(TAG, "recipient list as integers = " + recipientAsInteger);
return recipientAsInteger;
}
.
09-20 16:33:51.039: E/NfcScannerApplication(25835): recipient string list passed in to app obj = Emma, TMJ,
09-20 16:33:51.039: E/NfcScannerApplication(25835): tokenizedRecipient = Emma
09-20 16:33:51.064: E/NfcScannerApplication(25835): tokenizedRecipient = TMJ
09-20 16:33:51.064: E/NfcScannerApplication(25835): tokenizedRecipient =
09-20 16:33:51.079: E/NfcScannerApplication(25835): tokenizedRecipient length = 3
09-20 16:33:51.079: E/NfcScannerApplication(25835): hashmap contains key Emmawith value 3
09-20 16:33:51.089: E/NfcScannerApplication(25835): recipient list as integers = 3,
Your logging suggests that the string you are passing is "Emma, TMJ, " which is not what you suggest.
09-20 16:33:51.039: ... recipient string list passed in to app obj = Emma, TMJ,
I believe the solution to your problem would be to use String.split(",",0) as this will remove empty strings at the end. You may also wish to use String.trim() before looking up the string in your map.
Without seeing what recipients contains, you can safely assume that
if(recipients.containsKey(tokenizedRecipient[i].toString())){
Log.e(TAG, "hashmap contains key " + tokenizedRecipient[i].toString() + "with value " + recipients.get(tokenizedRecipient[i].toString()));
String integerValueOfName = recipients.get(tokenizedRecipient[i].toString());
recipientAsInteger = recipientAsInteger + integerValueOfName + ",";
}
only executes once because recipients only contains a key for Emma. The for loop loops 3 times, but only matches the if once.
If your recipients map contains keys for Emma and TMJ then you're problem is your split() method, take a look at the other answers.
If the input string is "Emma, TMJ," then the split will return an array containing these two strings:
"Emma"
" TMJ"
The last one will not match "TMJ". Try using ", *" (or, better, "\\s*,\\s*") as the regex to use for split (this will treat extra spaces as part of the delimiter and not include them in the resulting strings); or use the .trim() method on the resulting strings (which removes leading and trailing whitespace).

java: 'string index out of range: -1' exception using indexOf()

Weird problem. I run this (very elementary) procedure to find a username and password in a file, and the program should compare the password entered to the password saved. Every time, however, i get a strange String index out of range: -1 exception. I've suffered a similar problem before, however this time the indexOf('.') call is returning -1; which it doesn't like. Why is indexOf() returning -1 if it causes an error? Here's the source:
public String loginToClient() throws FileNotFoundException, IOException {
//decryptUsers();
int tries;
tries = 5;
while (tries > 0) {
System.out.println("LOGIN");
String usnm = c.readLine("Username: ");
char [] passwd = c.readPassword("Password: ");
users = new FileInputStream("users.fra");
DataInputStream dis = new DataInputStream(users);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String logindat = br.readLine();
System.out.println(logindat);
if (logindat.contains(usnm) == null) {
System.err.println("Username not recognised, please try another or create user.");
usnm = "INV";
return usnm;
}
else {
int startUsnm = logindat.indexOf(usnm);
System.out.println("startUsnm: " + startUsnm);
String logdat = logindat.substring(startUsnm, logindat.indexOf("."));
System.out.println("logdat: " + logdat);
int endUsnm = logdat.indexOf(':');
System.out.println("endUsnm: " + endUsnm);
int usnmend = endUsnm - 1;
System.out.println("usnmend: " + usnmend);
int startPass = endUsnm + 1;
System.out.println("startPass: " + startPass);
int endPass = logdat.indexOf('.');
System.out.println("endPass: " + endPass);
String Usnm = logdat.substring(0, usnmend);
System.out.println("Usnm: " + Usnm);
int passend = endPass - 1;
System.out.println("passend: " + passend);
String Pass = logdat.substring(startPass, passend);
System.out.println("Pass: " + Pass);
char [] Passwd = Pass.toCharArray();
if (usnm.equals(Usnm)) {
if (Arrays.equals(passwd,Passwd)) {
System.out.println ("Logged in. Welcome, " + usnm + ".");
String data = "LOGIN: " + usnm;
printLog(data);
//encryptUsers();
return usnm;
}
else {
System.out.println ("Incorrect password, please try again.");
String data = "PASWFAIL: " + usnm;
printLog(data);
tries -= 1;
}
}
else {
System.out.println ("Username not recognised.");
printLog("USNAMFAIL");
usnm = "INV";
return usnm;
//encrytUsers();
}
}
}
//encryptUsers();
System.exit(2);
return usnm;
}
And here's some input/output:
Startup initiated.
Logfile exists.
Users file exists.
New user? n
ELSE
LOGIN
Username: rik
Password:
rik:55.
startUsnm: 0
endUsnm: 3
startPass: 4
endPass: -1
Usnm: rik
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -5
at java.lang.String.substring(String.java:1949)
at client0_0_2.loginToClient(client0_0_2.java:103)
at client0_0_2.general(client0_0_2.java:209)
at client0_0_2.<init>(client0_0_2.java:221)
at client0_0_2.main(client0_0_2.java:228)
EDIT : SOLUTION FOUND!
For some reason, indexOf() does not want to find a '.'- when replaced with a hyphen('-'), however, it runs perfectly, seemingly!
I think the error is in this line:
String Pass = logdat.substring(startPass, passend);
For some reason (you'll have to determine why), you compute passend by searching for . in the string. If . isn't present, indexOf returns -1 as a sentinel. This isn't the line that causes the exception, though. I think it's the above line, since if you try to compute a substring ending at passend when passend is -1, you would get the above error.
Try determining why your string doesn't contain a . in it.
Hope this helps!
When indexOf() returns -1, it means that the value couldn't be found in the String. So, in this case, you're searching a String for '.' which doesn't exist in the String.
I would recommend that you always check the values of indexOf() after the call, and handle the -1 properly. For many cases, its probably sufficient to set it to either 0 or string.length(), depending on how you will use it later in your code.
Regardless, if you're expecting a '.' to exist and there isn't one, you'll need to debug through your code to find out what the value is, and where the '.' is missing.
indexOf() returns -1 if the specified string can't be found.
The problem is in the Line:
String Pass = logdat.substring(startPass, passend);
because of negative index.

Categories

Resources