0

I'm making a program in java that will use a string array say:

String[] category = new String[46];

Then I will check if the array in a for loop if it already has a value,

for(int checking = 21; checking <= 45 ;checking++) {
    if(category[checking]=INSERT_HERE) {
        textArea += category[checking] + "\n";
    }
}

What do I put in INSERT_HERE? Note: textArea is a named JTextArea.

3
  • A string variable without a value assigned is null, so check if it is not that. if(category[checking] != null). Commented Feb 26, 2014 at 11:14
  • you can use if(category[checking]!=null) Commented Feb 26, 2014 at 11:14
  • category[checking]=INSERT_HERE is wrong.. '=' means assign. '==' means compare.. Commented Feb 26, 2014 at 11:14

5 Answers 5

1

If you are making a check if the value is not null, then use

if(category[checking]!=null)

And if you are making a check for some particular value, then

if(category[checking].equals(PARTICULAR_VALUE))

PS: '=' is for assignment, you should use '==' for comparison.

Sign up to request clarification or add additional context in comments.

Comments

0

u have to checkout if it is not null use like this:

 if(category[checking] != null) // will check all filled values only

Comments

0

When you define your array as

String[] category=new String[46];

you allocate 46 reference slots in memory for your array. These slots are initially null, so when you need to do a comparison like the one you asked, you need to check against null.

...
if(category[checking] != null)
...

Comments

0

You could try something like that in your code:

for(int checking=21;checking<=45;checking++) {
    if(category[checking] != null) {
        textArea+=category[checking] +"\n";
    }
}

Or like that:

for(int checking=21;checking<=45;checking++) {
    if(category[checking] != "") {
        textArea+=category[checking] +"\n";
    }
}

2 Comments

In your second example, comparing a String to another String with a != would not work, .equals(String) should be used to compare Strings.
OK! Thanks for checking)
0
for(int checking=21;checking<=45;checking++) {
    if(category[checking] != null || category[checking] != "") {
       textArea += category[checking] +"\n";
    }
}

2 Comments

if(category[checking] != null || category[checking].trim() != "") { textArea += category[checking].trim() +"\n"; } //the trim() is safer
Shouldn't the || be &&? or better still category[checking] != null && !category[checking].isEmpty()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.