So I'm basically finished with a program, and at the end of it I'm printing Strings from an array to a file. The array may contain null values, so I'm checking for null before I print, but I keep ending up with 1 null at the very end of the file...
Here's the code I'm using to check for null
for(int i=0;i<array2.length;i++)
{
if(array2[i] != null)
out.println(array2[i]);
}
I know that the array contains multiple instances of null, but only 1 is being printed. I tried using the debugger and when array2[i] == null, it still entered the conditional statement...
So I added a println statement to help me see what's going on. It now looks like this:
for(int i=0;i<array2.length;i++)
{
if(array2[i] != null)
{
System.out.println("Adding " + array2[i]);
out.println(array2[i]);
}
Just after printing all the String values to the console, it prints "Adding null" so I know it's happening here in this if statement. Why is this happening???
The debugger is not always clear as to whether it has entered an if condition or not. I don't believe this code is entering the if condition which it might appear it is and your null is probably coming from another line of code.
You could write the code as
for(ElementType e: array2.length)
if(e != null)
out.println("[" + e+ ']'); // extra text for debugging.
// I suspect your `null` will still be on a line of its own
Arent you also missing a set of brakets for the if statement??
for(int i=0;i<array2.length;i++)
{
if(array2[i] != null)
{
out.println(array2[i]);
}
}
Related
I have a program that gets an input from the console. It checks what the input is then using 'if's it decides what to do. One section test to see what the first four letters of the string are, to see if it needs to deal with it, but not all of the strings are always 4 or more letters long. This means that if you type in something that is less than 4 letters long, it encounters an error, and quits. I can't put that section at the end, because at the end there is an else, which if the command is unknown, is called and something happens. Is there a way I can stop the error from occurring?
My code is:
if(input.equals("help")){
int commandsSize = commands.size();
for(int i = 0; i < commandsSize; i++) {
String value = commands.get(i);
System.out.println(value);
} else if((input.substring(0, 4)).equals("open")) {
...
}
You can check the size of the string the user inputs,
if (input.length() != 4) {
System.out.println("You must enter valid input");
// Probably do something here.
}
if(input.equals("help")){
int commandsSize = commands.size();
for(int i = 0; i < commandsSize; i++) {
String value = commands.get(i);
System.out.println(value);
}
} else if((input.substring(0, 3)).equals("open")) {
...
}
Your code is erroring out on the substring method because if the string is less than 4 characters, the method is going outside the bounds of the string (or the char array that makes up the string). You will also want to check that you string is not null before calling methods on the string object.
To have the same flow as you currently have, but to protect your code against the substring error and not being null, you can do this:
if(input != null && input.equals("help")){
//some code
} else if((input != null && input.length() >= 4) && (input.substring(0, 4)).equals("open")) {
//some code
}
I have a script which visits links from a text file. I am trying to delete the string if value returned is null
Example:
1. some link (returned value 'hi')
2. some link (returned null value) //DELETE STRING FROM FILE BECAUSE NULL VALUE RETURNED
3. some link (returned value 'hello')
Some code:
while ((input = in.readLine()) != null) {
System.out.println(input);
if ((input = in.readLine())=="0"){
System.out.println("1 String deleted from file because null value returned ");
}
I'm aware that I'm checking for String "0" instead of an integer 0 because the server stores it as a string i suppose.
I think, rather than trying to remove to the file mid-read (and I don't even really know how you'd do that, and if you could it'd be a horrible idea) you might have an easier time of this by just reading the entire file in and storing each value in an index of an ArrayList<string>:
ArrayList<string> lines = new ArrayList<string>();
while ((input = in.readLine()) != null) {
lines.add(input);
}
Then write the file again after you've finished reading it, skipping any index of lines that's equal to "0":
for (String line : lines)
{
// skip "0"
if (line.equals("0")) {
continue;
}
// write to file if not
writer.write(line);
writer.newLine();
}
Note that == compares reference equality in Java, and .equals compares value equality, so for almost all cases you want to use .equals.
Granted, if as your comment states above, you have another file constantly writing to this one, you're better off looking for an entirely new idea. For that matter, if you've got a script writing these, why not change the script so that it just doesn't write lines for null values in the first place? Unless you have literally no way at all of changing the script, spinning another one up to constantly rewrite parts of its work (on the same constantly-accessed file!) is going to be a. ineffective and b. extremely problematic.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have a Huffman Tree, and a character, and I want to return what that character's encoding within the Huffman Tree should be.
I've implemented it using the breadth-first traversal method, and each time I'm checking the left and right tree, I'm checking if the tree's data is equal to character I'm looking for. Each time I go right or left, though, I add 0 or 1 to the encoding so far. Eventually, when I find the character equal to the tree's data, I return that tree's encoding value.
Code:
public static String findCharEncoding(BinaryTree<CharProfile> bTree, char character) {
Queue<BinaryTree<CharProfile>> treeQueue = new LinkedList<BinaryTree<CharProfile>>();
// Create a TreeWithEncoding object from the given arguments and add it to the queue
treeQueue.add(bTree);
while (!treeQueue.isEmpty()) {
BinaryTree<CharProfile> t = treeQueue.remove();
-> if (t.getLeft().getData().getCharacter() == character) {
return t.getLeft().getData().getEncoding();
}
if (t.getLeft() != null) {
t.getLeft().getData().setEncoding(t.getLeft().getData().getEncoding() + "0");
treeQueue.add(t.getLeft());
}
if (t.getRight().getData().getCharacter() == character) {
return t.getRight().getData().getEncoding();
}
if (t.getRight() != null) {
t.getRight().getData().setEncoding(t.getRight().getData().getEncoding() + "1");
treeQueue.add(t.getRight());
}
}
// If it gets to here, the while loop was unsuccessful in finding the encoding
System.out.println("Unable to find.");
return "-1";
}
Which I've implemented as follows:
for (int i = 0; i < charOccurrences.size(); i++) {
char character = charOccurrences.get(i).getCharacter();
charOccurrences.get(i).setEncoding(findCharEncoding(huffmanTree, character));
System.out.println(charOccurrences.get(i).getEncoding());
}
CharProfile is a custom class that holds the character value, the probability of the character and the encoding.
It keeps returning a NullPointerExceptionError at the line if (t.getLeft().getData().getCharacter() == character) {, which I've indicated with an arrow. I've tried and tried, but I can't seem to figure out why.
Either t is null or t.getLeft() returns null or t.getLeft().getData() returns null.
As we only see the code you show is, it's your job to debug that.
You could insert this a line above the error:
if (t == null) {
System.out.println("t = null");
} else if (t.getLeft() == null) {
System.out.println("t.getLeft() returns null");
} else if (t.getLeft().getData() == null) {
System.out.println("t.getLeft().getData() returns null");
}
As pointed out in a comment, you're checking for whether t.getLeft() returns null at one point but not at others. Also, personally, I just hate code that keeps calling the same get methods over and over. I'd probably take this section:
if (t.getLeft().getData().getCharacter() == character) {
return t.getLeft().getData().getEncoding();
}
if (t.getLeft() != null) {
t.getLeft().getData().setEncoding(t.getLeft().getData().getEncoding() + "0");
treeQueue.add(t.getLeft());
}
and rewrite it as:
left = t.getLeft();
if ( left != null ) {
data = t.getData();
encoding = data.getEncoding();
if ( data.getCharacter() == character ) {
return encoding;
else {
data.setEncoding( encoding + "0" );
treeQueue.add( left )
}
}
(I've left out type declarations for the variables I've added, since I'm not sure of the right type names.)
This should avoid the NullPointerException if t.getLeft() is what's returning null; otherwise you should at least see more clearly which reference is null when the exception happens since you won't have multiple dereferences in one line. The section for the right side can be rewritten the same way (and in fact it looks like you could make one method that you simply pass the left and right values to, since you do the same thing for both).
I just started programming in java and i am creating a simple waiting list.
it al seems to work well but i decided to include a if else construction to check the textfield not beeing empty. the problem is that it seems to be ignored because i don't get a error or something.. and i googled alot for the if else example and i can't solve the problem somehow.. what am i doing wrong? below you can find the relevant code. Thanks in advance.
public void actionPerformed(ActionEvent e) {
// check if veld1 is filled in.
if ( veld1 == null || veld1.equals( "" ) ) {
// give error
System.out.println("U heeft niets ingevuld in veld1");
}
else {
veld4.setText( veld3.getText() );
veld3.setText( veld2.getText() );
veld2.setText( veld1.getText() );
textveld1.append( veld4.getText() + "\n" );
veld1.setText("");
}
}
It seems veld1 is not a string, but some Swing control.
You probably want to do
if(veld1.getText() == null || veld1.getText().equals( "" )
It is difficult to grant without seeing the rest of it, but veld1.equals("") looks suspicious. You are comparing veld1 to the empty String, but veld1 looks like a component. Maybe you meant veld1.getText().equals("") (and, similarly, veld1.getText() == null)
If the veld1 holds a JTextField, you probably want to change the statement to veld1 == null || veld1.getText() == null || veld1.getText().equals( "" ), as in your current code you check if the field itself exists, not its content.
veld1.equals("") is not the same as veld1.getText().equals(""), the first one is comparing the veld1 object to an empty string, and will always be false.
Ive made this:
if( tal[i+1] ){
if( tal[i] == tal[i+1]){
match=true;
}
}
But it doesnt seem to work.
I want to check whether the field next to the current (i) exists, in the array tal[].
How can i fix this?
If by "exists" you mean "is not out of bounds", then you have to check the length:
if (i+1 < tal.length) {
// i+1 is a valid index in tal here
}
You can check the length of an array with the length field, like:
if (tal.length > i + 1) {
// there is an elemnt at i + 1
}
As you did not mention anything about your comparison line (the line containing ==) I think it is not part of the question.
Although I guess you should put it into a for loop like:
for (int i=0; < tal.length - 1; i++) {
// you can safely do something here involving tal[i] and tal[i + 1]
}
well, all his code does is check if the next element of the boolean array is the same as the current element after first checking if the next element is true.
My guess is he thinks it does something else, but without him telling us what that something is it's rather hard to make recommendations for changes.