Error when check an empty element in array [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
why cannot I check if a place in array is empty ?
I got this wrong message:
The operator == is undefined for the argument type(s) int, null"
on the marked line
private static int findNr(int[] trans)
{
int emptyPlace=0;
for (int i=0; i<trans.Length -1;i++)
{
--> if( trans[i] = null) <--
return emptyPlace = trans[i];
}
return emptyPlace;
}

You can not compare primitive data type for null. int is primitive data type.

You have to do
if( trans[i] == null)
instead of
if( trans[i] = null)
^-----------Mistake
Anyway in which language you have written the code?

You try to assign null to the array element at position i
To check if the element is null you have to do:
if(trans[i] == null)
{
...
}
but this expression doesn't make any sense since an int can never be null (unless its a nullable int (int?)) so the condition will always be false

Primitive cannot be checked with the null. So for particular primitive types use their default value to check.
i.e for int default value is 0 and for
double default value is 0.0 etc.
So check as:
if(intr[i]==0){
//some logic
}

if( trans[i] = null)
In the above line your are using assignment operator = in place of comparison operator ==. If condition expects the final value after computation to be of the type boolean. Hence you get the error.
Also your trans[i] is an primitive int value which cannot be compared to a null. (Only objects can be null in java)
The assignment operator = will only work in case of boolean variables, something like this:
boolean flag = false;
if(flag=true) {
// this condition will be true
}

First, you mispelled the == comparison. Should be:
if (trans[i] == null)
Second, the above doesn't works. Primitive values can never be null, when you declare any int variable, it's 0 by default.
Thats why:
int[] v = new int[3];
for (int i = 0; i < v.length; i++)
System.out.println(v[i]);
Outputs this:
0
0
0
You should either work with Integer objects array or review your logic.

1- You have forgot '=' ---> if (trans[i] == null)
2- You can't compare primitive value (int) with null

Related

Single equal in different situation [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have this code...
class Test {
public static void main(String[] args) {
Boolean mySuperBoolean = Boolean.FALSE;
System.out.print("a");
if (mySuperBoolean = Boolean.TRUE) {
System.out.print("b");
}
System.out.print("c");
}
}
I am new to Java, but I knew single equal (=) is used to assign. And double equals (==) is used to check if object is referred to the same location in memory. However, in this case I do not understand how the 'b' is being printed with a single equals, but I understand changing it to a double equals sign will not print it out
if (mySuperBoolean = Boolean.TRUE) will assign Boolean.TRUE to your mySuperBoolean variable and the condition will evaluate to true, hence whatever is inside your if it will always execute
The result of the assignment operator = will be the assigned value. So if (mySuperBoolean = Boolean.TRUE) will always evaluate to true.
Assignment is an expression which resolves to whatever was assigned, in this case(mySuperBoolean = Boolean.TRUE) is an expression which resolves to Boolean.TRUE.
This is really only useful in a few specific situations. One such case is the following idiom:
String line;
while ((line = readLine()) != null) {
//...
}
Or even
i = j = k = 0; // equal to: i = (j = (k = 0))
It's a controversial feature because it allows probable bugs such as yours to compile successfully. To mitigate this, some people will invert the operands (a "yoda condition"):
if (Boolean.TRUE == mySuperBoolean)
This works because if I forget the second equals then the compiler will throw an error because Boolean.TRUE is final and cannot be assigned to.
In essence, what happens here boils down to:
if (Boolean.TRUE) {
System.out.print("b");
}
That assignment puts TRUE into the variable, the variable is boolean, and checked for its current value, end of story.

Java int 'through' int operator? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to figure out how to do something like:
int test = 1;
int test1 = 10;
if (value = test (though) test1) {
}
I've looked at oracles java operators but could not figure out how to do it.
The construct should check if value is between test and test1.
Can anybody tell me how to do this in Java?
if (value >= test && value <= test1)
{
//doSomething
}
Java does not support chained inequalities, ie test <= value <= test1, so instead you can just use two boolean expressions, connected via the boolean and operator, to get a logically equivalent conditional.
You should try something like with logical and operator
if (value > test && value < test1) {
// do something
}
or add >= to add equals comparison too.
It looks like you are looking for range operator that is common in a lot of programming languages, Java not being one of them, but the condition that you are trying to impose on the range will always be the same. You don't need to check every value in the range, merely the endpoints since it is contiguous:
if( value > test && value < test1 ) {
// do something
}
There is no through op in Java. You can do it with a simple if :
if (value >= test && value <= test1) {
// your code
}
This post begged to be clarified.
If you are checking that value is between test1 and test2 then you need:
if(value >= test && value <= test1){
// do stuff
}
Note that you should remove the = signs if value should be strictly between test and test1.
However, if you are checking that value is one of multiple tests from test0 "through" test10 for instance, then pack those tests in a set and check if value is among them:
import java.util.*;
Set tests = new HashSet();
tests.add(test);
tests.add(test1); // similarly for as many as you need
if(tests.contains(value)){
// do stuff
}

Java: NullPointerException with substrings [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm having a problem in one of my methods. Please keep in mind that I am learning Java in college so I might not be up to speed on simple things. Below is a method that is made to add expressions. The problems I'm running into is found where x = x.substring.(1, x.length() - 1); I'm getting an exception that reads:
Exception in thread "main" java.lang.NullPointerException
I have no idea what that means and/or how to fix it. If you could point me in the right direction, that'd be great.
Thanks.
public static int adder(String x){
int total = 0;
x = x.substring(1, x.length() - 1);
sopln(x);
String[] nums = x.split("\\+");
for(int i = 0; i < nums.length; ++i){
if(nums[i].charAt(0) == ' ' || nums[i].charAt(nums[i].length()-1) == ' '){
sopln("ERROR: Excess whitespace identified.");
nums[i] = nums[i].trim();
}
nums[i] = nums[i].replaceAll(" ", "");
if(nums[i].charAt(0) == '-')
total -= Integer.parseInt(nums[i]);
else
total += Integer.parseInt(nums[i]);
}
return total;
}
It probably means that your String x is null and not actually set to an Object of a String.
How are you calling the method?
Does it happen when you call it with a hard coded string like
int num = adder("string checking in");
if not, then somewhere upstream in your code, that String variable you are passing into the adder method is null.
you are passing a null value when you call adder(the_string), where the_string is null
The problems I'm running into is found where x=x.substring.(1,x.length() - 1);
This means that at some point you are calling adder with an argument that is null. That's the only way you can get an NPE at that point.
Find out where and why the argument is null, and then fix it.
(It could be an explicit null, but it is more likely to be coming from an uninitialized field, or from some method that returns a null to indicate something; e.g. BufferedReader.readLine() returns null when the reader reached the EOF position.)

Evaluation of && boolean operator

If i have the following if statement
if ( (row != -1) && (array[row][col] != 10) ) {
....
}
Where row is an int value and array is an int[][] object.
My question is, if this will throw an exception if row = -1 as the array won't have a -1 field, so out of bounds exception? Or will it stop at the first part of the if, the (row!=-1) and because that is false, it will ignore the rest?
Or to be sure it doesn't throw exception, i should separate the above if statement into two?
(Pls, don't tell me to check this out for my self :) I'm asking here 'cause i wanna ask a followup question as well ...)
It will stop safely before throwing an exception
The && is a short-circuiting boolean operator, which means that it will stop execution of the expression as soon as one part returns false (since this means that the entire expression must be false).
Note that it also guaranteed to evaluate the parts of the expression in order, so it is safe to use in situations such as these.
It will not throw an exception. However, if row is < -1 (-2 for example), then you're going to run into problems.
It will stop at the first part of the if. Java uses short circuite evaluation.
No, It wont. the compiler will not check the second expression if the first expression is false... That is why && is called "short circuit" operator...
Called a short-circuit evaluation via the && and if the row check fails, there is no point in continuing evaluation.
Most programming languages short-circuit the test when the first expression returns false for an AND test and true for an OR test. In your case, the AND test will be short-circuited and no exception will occur.
Many programming languages have short-circuit evaluation for logical operators.
In a statement such as A and B, the language will evaluate A first. If A is false, then the entire expression is false; it doesn't matter whether B is true or false.
In your case, when row is equal to -1, row != -1 will be false, and the short-circui the array expression won't be evaluated.
Also, your second question about the behavior of the array index is entirely language-dependent. In C, array[n] means *(array + n). In python, array[-1] gives you the last item in the array. In C++, you might have an array with an overloaded [] operator that accepts negative indexes as well. In Java, you'll get an ArrayIndexOutOfBoundsException.
Also, you might need something like the following (or just use a try/catch).
boolean isItSafe(int[][] a, int x, int y) {
boolean isSafe = true;
if (a == null || a.length == 0 || x >= a.length || x < 0 || y < 0 || y >= a[0].length ) {
isSafe = false;
}
return isSafe;
}

How to write correct expression to result to Boolean? (Cannot cast from boolean to Boolean)

I am experiencing difficulties with an expression that should result in showing or hiding a band in an iReport.
These are variables that I have:
Integer mainGroupInt = Integer.valueOf(5);
Integer subGroupInt = Integer.valueOf(5);
Boolean showDetailGroup = Boolean.valueOf(false);
The result must be a Boolean, so I tried the following:
mainGroupInt.intValue() != 0 && subGroupInt.intValue() != 0)) || (mainGroupInt.intValue() != 0 && showDetailGroup)
This is thus not working, I get the following error:
The expression of type boolean is boxed into Boolean
I'm overthinking this one but I cannot solve it.
Thanks for your help.
Are you looking for...
showDetailGroup = Boolean.valueOf( (mainGroupInt.intValue() != 0 && subGroupInt.intValue() != 0) ||
(mainGroupInt.intValue() != 0 && showDetailGroup.booleanValue()) )
If not, I don't understand your question. The above code returns a Boolean representing the value of the boolean expression. See Java Boolean.valueOf() and Boolean.booleanValue() docs.
Boolean ( with capital B ) cannot be used in the boolean expressions without unboxing it.
If you want to silence the warning, convert Boolean to primitive type by calling booleanValue function (this is what's happening behind the scene with unboxing):
mainGroupInt.intValue() != 0 && showDetailGroup.booleanValue( )
Boolean and Integer are wrapper classes for the primitives boolean and int. You should change your variables to boolean and int and wrap them up later if you must pass them by reference to a function.

Categories

Resources