Avoiding null indexes in my array - java

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);
}

Related

Formatting the output in desired way

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();
}
}

Where does my array change?

This seemed like a really trivial issue, but I'm trying to write an array of booleans to a file and then read them back into the array. I can verify that the file is being created properly:
true
false
true
false
false
false
But when I try to read it back, I end up with an array completely full of false. Here's my reading code:
bools = new boolean[bools.length];
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String temp;
int i = 0;
while (null != (temp = reader.readLine())) {
bools[i] = Boolean.parseBoolean(temp);
// output what you read
if (bools[i]) {
System.out.println("true!");
} else {
System.out.println("false!");
}
}
reader.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(BooleanFiles.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(BooleanFiles.class.getName()).log(Level.SEVERE, null, ex);
}
// now output the resulting array
for (int i = 0; i < bools.length; i++) {
if (bools[i]) {
System.out.println("true!");
} else {
System.out.println("false!");
}
}
And here's the output I get:
true!
false!
true!
false!
false!
false!
false!
false!
false!
false!
false!
false!
The part that drives me bonkers is the array is set properly when I check it as I read (in the while loop), but it's wrong when I check the array at the end (in the for loop).
It may also be helpful to know that bools is a property of the class
Please excuse my noobishness.
Thanks!
while (null != (temp = reader.readLine())) {
bools[i] = Boolean.parseBoolean(temp);
// output what you read
System.out.println(bools[i]);
i++;
}
You are putting everything at the same location. Increment your iterator variable and it will work.
Your not updating i value. First time your getting properly because your printing values directly from file.

Looping through excel rows keeps given me an ArrayIndex...Exception

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?

Can't Write to File

I need some help please writing the output to a file and I can't get it to work. If I use the System.out.println it works. If I create the file stream and Buffered Writer in the actual method, it creates the file but doesn't write anything to it. I'm assuming it's because my method is recursive and creates a new file every time the method calls it self again. So I created another print method and used the string value key[i] as the string parameter and it does nothing.
Any help is appreciated, thank you.
public void print(String s)throws IOException
{
fstream = new FileWriter("out.txt", true);
out = new BufferedWriter(fstream);
try{
out.write("From print: " + s + " ");
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
public void generate() throws IOException
{
while (k<randomWordNum())
{
if (randomNum() <= sumOfFreq[0])
{
//System.out.println(getKey[0] + " ");
print(getKey[i]);
i++;
k++;
generate();
}
if (randomNum() >= sumOfFreq[i] && randomNum() <= sumOfFreq[i+1])
{
//System.out.println("From generate: " + getKey[i+1] + " ");
print(getKey[i+1]);
i++;
k++;
generate();
}
else
{
i++;
generate();
}
}//while
}//generate
You need to .close the file to make sure things get written
I think that constructor of FileWriter will overwrite the file. So you'll need to use a code line like this:
fstream = new FileWriter("out.txt", true); // true for appending
Also, always close a file before it goes out of scope, otherwise it might never get flushed or closed if you are unlucky...
And one more thing, assuming that is not some sort of debug/troubleshooting code, "never" catch Exception. If you do catch it, be sure to re-throw it asyou got it after logging or whatever you did with it. But, in general, always catch a more specific exception type.

String comparison issue

I'm trying to do something reallllly simple that apparently is extremely difficult in android.
I just want to compare two strings to see if they are equal.
I have a temp variable with the value "Location"
I have debugged this and it does indeed contain Location...
So I tried this at first
if(temp == "Location") { //do something }
But I already know that doesn't work. I then tried all the possible functions for a string such as:
.equals
.contains
.ignoreCaseEquals
etc...
If anyone has any idea what to do please help. This is really getting annoying.
EDIT:
Here is the function where I'm comparing the strings for those of you who want to see.
public String[] getData(){
try {
int tempGroupCount = 0;
URL food_url = new URL (Constants.SERVER_DINING);
BufferedReader my_buffer = new BufferedReader(new InputStreamReader(food_url.openStream()));
temp = my_buffer.readLine();
// prime read
while (temp != null ){
// check to see if readline equals Location
Log.w("HERasdfsafdsafdsafE", temp);
// start a new location
if (temp.equals("Location")
{
groups[tempGroupCount] = temp;
tempGroupCount++;
}
Log.w("HERasdfsafdsafdsafE", temp);
//start for-loop to test to get child info
//for(temp = my_buffer.readLine(); temp != "Location" && temp != null; groupCount++, childrenCount++){
//children[groupCount][childrenCount] = temp;
//}
temp = my_buffer.readLine();
}
my_buffer.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("IO EXCEPTION", "Exception occured in MyExpandableListAdapter:" + e.toString());
}
return groups;
}
equals does work. If temp.equals("Location") returns false, then your temp variable does not refer to a string with the value "Location".
There may be unprintable characters or other oddities about the string - I suggest you look at the length of the string to check. Alternatively, there can be other characters which look like the ASCII characters, but aren't. In the debugger, try examining the array and get at the underlying char array - check the Unicode value of each character.
if(temp.equals("Location"))
{
//your code here
}
does not work
try this
if(temp.contains("Location"))
{
//your code here
}
try like
if(temp.equals("Location")) { //do something }
and
while (!temp.equals("")){
if your variable temp is a String, you can also used the method compareTo(String).
if (temp.compareTo("Location") == 0)
{
//do something
}
I am doing same scenario , its working fine.
String result = responsePrimitiveData.toString();
if(!result.equals("0")){
}
Try doing this:
if (temp.toLowerCase().compareTo("location") == 0)
public String[] getData(){
try {
int tempGroupCount = 0;
URL food_url = new URL (Constants.SERVER_DINING);
BufferedReader my_buffer = new BufferedReader(new InputStreamReader(food_url.openStream()));
temp = my_buffer.readLine();
// prime read
while (temp != null ){
// check to see if readline equals Location
Log.w("HERasdfsafdsafdsafE", temp);
// start a new location
if (temp.toString().equalsIgnoreCase("Location")
{
groups[tempGroupCount] = temp;
tempGroupCount++;
}
Log.w("HERasdfsafdsafdsafE", temp);
//start for-loop to test to get child info
//for(temp = my_buffer.readLine(); temp != "Location" && temp != null; groupCount++, childrenCount++){
//children[groupCount][childrenCount] = temp;
//}
temp = my_buffer.readLine();
}
my_buffer.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("IO EXCEPTION", "Exception occured in MyExpandableListAdapter:" + e.toString());
}
return groups;
}
first try to convert "temp" into string then compare it, apply this may helps you
you may try the following to find out where your problem is.
final String LOCATION = "Location"; // just to make sure we use the very same character sequence
if (temp.equals(LOCATION)
{
/* your code here */
}
else
{
System.out.println("Location : " + Arrays.toString(LOCATION.getBytes(Charset.forName("UTF-8"))));
System.out.println("temp : " + Arrays.toString(temp.getBytes(Charset.forName("UTF-8"))));
}
This should print the byte representation of both Strings to standard out. If equals() returns false, the strings differ. Because of unprintable characters or similar looking characters it's sometimes difficult to find the difference. But the byte representation should show you.
(I'm not an android programmer, so I hope the functions exist on android JVM. And sorry for any typos and missing brackets - if any ;-)

Categories

Resources