an issue on "if statement" in Java [duplicate] - java

This question already has answers here:
Is there any reason for Eclipse showing assignment variables in while loops as valid?
(5 answers)
Closed 8 years ago.
Take a look on the following java code.
String Remark="";
boolean Paid, PartiallyPaid, NotPaid;
if(Paid=true) {Remark="Paid";}
if(PartiallyPaid=true) {Remark="Partially Paid";}
if(NotPaid=true) {Remark="Not Paid";}
Here the Boolean values determined by RadioButtons. I want to assign the string "Remark" as mentioned above. But It always giving the last assigning value only(as "Not Paid"). Anyone explain why this is occurring?

use == instead of = for comparison.
== is used to compare two values for equality
= is used for assigning one value to another
String Remark="";
boolean Paid, PartiallyPaid, NotPaid; // initialise values else compile error, pointed out by Peter O.
if(Paid==true) {Remark="Paid";}
if(PartiallyPaid==true) {Remark="Partially Paid";}
if(NotPaid==true) {Remark="Not Paid";}
As pointed out by unholysampler
for boolean values you dont have to explicitly check for equality. Following would do
String Remark="";
boolean Paid, PartiallyPaid, NotPaid; // initialise values else compile error, pointed out by Peter O.
if(Paid) {Remark="Paid";}
if(PartiallyPaid) {Remark="Partially Paid";}
if(NotPaid) {Remark="Not Paid";}

You have to use double equals in the if statement.

Here, if(Paid=true) should be if(Paid==true). Same thing with all other similar cases. = is assignment. You're giving Paid a value of true. == is a test for equivalence of primitive types. It should look like this:
String Remark="";
boolean Paid, PartiallyPaid, NotPaid;
if(Paid) {
Remark="Paid";
} else if(PartiallyPaid) {
Remark="Partially Paid";
} else if(NotPaid) {
Remark="Not Paid";
}
However, your booleans are all currently false. And it seems that simultaneously it can be be all 3 options, which is not a good idea. You should look up if/else statements in Java documentation.

Related

How to mock the function in a loop using Mockito in Java to return different value for each iteration [duplicate]

This question already has answers here:
How to tell a Mockito mock object to return something different the next time it is called?
(5 answers)
Closed 2 years ago.
I am new to using Mockito. In my logic I need to mock a function that is inside the loop and for every iteration, it should return different value.
Example :
for(value : values )
{
int i = getValue(value);
i=i+1;
}
if(i=somevalue)
{
some code
}
else
{
Some other code
}
So if I mock getValue() method to return a particular value. Everytime, it is returning the same value and only one part of if else is covered.
Can you please suggest me a way such that everytime in the loop getValue() is returned different value.
Thank you !
Since you have an input in getValue() you can use that.
when(mockFoo.getValue(value1).thenReturn(1);
when(mockFoo.getValue(value2).thenReturn(2);
when(mockFoo.getValue(value2).thenReturn(3);
But if you just don't care you can return different values in a sequence.
when(mockFoo.getValue(any()))
.thenReturn(0)
.thenReturn(1)
.thenReturn(-1); //any subsequent call will return -1
// Or a bit shorter with varargs:
when(mockFoo.getValue())
.thenReturn(0, 1, -1); //any subsequent call will return -1
Also please note, that if(i=somevalue) will always be true, you might want to use if (i == somevalue).

Efficient null check for a compound object in Java [duplicate]

This question already has answers here:
is there a Java equivalent to null coalescing operator (??) in C#? [duplicate]
(5 answers)
Null check chain vs catching NullPointerException
(19 answers)
Closed 6 years ago.
A program creates a JDialog panel with multiple tabs. One of the tabs has several tables. A JTable has adjustable column width. This tab is generated under different conditions. Sometimes from the state tab is null, sometimes tab exists, but the table is null. Sometimes user haven't resized the column yet.
I am looking for a method to save the columnWidth value if user resized the column. Checking for null seems bulky in this situation:
jpanel.tab.table.width
the best method I can find is:
if( jpanel!=null &&
jpanel.jtab!=null &&
jpanel.jtab.jtable!=null && ...
Is there a better way to do this null check?
I saw this question:
is there a Java equivalent to null coalescing operator (??) in C#?
It doesn't list a solution and is quite old (Java 6-7 time). I was hoping this feature was added in later releases.
There's no way to do exactly what you want.
However, you can just throw everything into a try statement:
try {
myItem = bundle.category.subcategory.item;
}
catch(NullpointerException ignored) {}
Note that this looks very hacked, and it's rather poor coding practice. Your current solution is probably the best approach in terms of clarity.
Edit: I tried posting another Anwser but the button is greyed out, so I'll put it here:
Feels like repeating same code many times, when you should use a for loop
You can indeed use a for loop, but that will invovle Reflection and much boilerplate code. Imagine something like this:
static boolean checkDeepNull(Object root, String... attributes) throws NoSuchFieldException, IllegalAccessException {
Object currentAttribute = root;
for(int attr = 0; currentAttribute != null && attr < attributes.length; attr++){
Field nextField = currentAttribute.getClass().getField(attributes[attr]);
Object nextAttribute = nextField.get(current);
if(nextAttribute == null) return false;
currentAttribute = nextAttribute;
}
return true;
}
How to use it: if(checkDeepNull(bundle, "category", "subcategory", "item"))
You could have an interface which determines nullability:
public interface Nullability {
public boolean hasNulls();
}
And then simply have the parent call any children like so:
public boolean hasNulls() {
return this.bundle == null || bundle.hasNulls();
}
//in bundle
public boolean hasNulls() {
return this.category == null || category.hasNulls();
}
Regardless, if you have to nullcheck everything, you're going to be doing a lot of boilerplate code if you don't provide a means of iteration. That's what you should really focus on.
On a personal level, I disagree heavily with exposing fields like that. It's a very easy way to lead to more headaches and errors in design.
The short answer is no.
Can you redesign bundle so that it is always fully constructed? I.e., if bundle != null, then category, subcategory and item always exist? This could also help with concurrency issues. Basically, if nulls give you problems, where possible, don't allow these fields to be null.
Another option is the Null Object Pattern. Basically, you have a "default" implementation of Bundle which always return getCategory() that always returns a value for getSubcategory(), but ultimately the call to getItem() returns null or something to indicate "nothing". This is a great pattern but requires some work.
I hesitate to suggest it, but it is rare for any of the items to be null, at some point it may be faster and clearer to just catch the NPE, but this style should really be avoided. And it is a definite code smell that your design is poor. Avoid it if at all possible.
try {
return foo.bar.bap.zaz.blah.blah;
}
catch (NullPointerException ignored) {
return null;
}

Searching through a collection of an array list pair [duplicate]

This question already has answers here:
How to compare two java objects [duplicate]
(5 answers)
Closed 9 years ago.
I am trying to search through a collection of an ArrayList if pairs. What I want to be able to do, is to go through the collection and find the first value in a pair and return the second value of that pair. The problem I am having is that the check I have to find the first value doesn't seem to be working, so every time I search, I end up returning null. I know that the problem exists with my if statement, but I cannot seem to sort out what it is I am doing wrong. Since this is a homework assignment, I can't show all the code to my pair class, or my pair list class, but I can show you the method I have for searching the first value:
public S findFirst(F firstValue) {
Iterator<Pair> myIter = this.iterator();
S tmp2 = null;
while (myIter.hasNext()) {
Pair tmp1 = myIter.next();
if (tmp1.getFirst() == firstCall) {
tmp2 = (S) tmp1.getSecond();
}
}
return tmp2;
}
If I throw in an else statement that just calls what I am attempting to do in my if check, like this:
else{
tmp2 = (S) tmp1.getSecond();
}
then whenever I test for the first value, I get the second value, so I know I am at least on the correct path, but I am assuming that I am doing something wrong with what I am checking for in my if statement. Does anyone know how I can correctly do this, (and please bear in mind that this is homework, so a guide to how to figure this out is far more valuable to me than just some random answer, I want to learn, not just be given an answer) Thanks in advance!
Don't use == to compare objects. Override and use equals().
I think
if (tmp1.getFirst() == firstCall)
should probably say
if (tmp1.getFirst().equals(firstValue))
The important difference is that == checks whether two expressions refer to the exact same object. You're more interested in knowing whether your two expressions actually refer to objects that are equal.
Try this:
if (tmp1.getFirst().equals(firstValue))
instead of
if (tmp1.getFirst() == firstCall)
Also you can override your own equals method.
You should never use == to compare objects.
Check How to compare two java objects
What Matt says, (don't use == ) but I think a bigger problem is that you don't return the 'first' encounter.... your if statement should look like:
public S findFirst(F firstValue) {
Iterator<Pair> myIter = this.iterator();
while (myIter.hasNext()) {
Pair tmp1 = myIter.next();
if (firstValue.equals(tmp1.getFirst())) {
return (S) tmp1.getSecond();
}
}
return null;
}

Trying to learn methods/boolean. Need an assist [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
Trying to figure out what's wrong with my code here - I want user input to be checked with the concentrations array and if they enter any of the array to print out a positive display message... However, I get an output of "Yes, that is a valid concentration" every time, regardless of input.
import javax.swing.JOptionPane;
public class BASIT_Concentration_Check
{
public static void main(String[] args)
{
String[] concentrations = {"DTP","HCIT","INFS","NTEL","WDM"};
String studentconcentration = getStudentConcentration();
boolean concentrationvalid = isConcentrationValid(studentconcentration, concentrations);
displayMessage(concentrationvalid);
}
public static String getStudentConcentration()
{
String studentconcentration = JOptionPane.showInputDialog(null,"What is your B.S. AIT Concentration?");
return studentconcentration;
}
public static boolean isConcentrationValid(String studentconcentration, String [] concentrations)
{
boolean concentrationvalid=false;
for (int i=0;i<concentrations.length;i++)
{
if (concentrations[i]==studentconcentration)
{
concentrationvalid = true;
}
}
return concentrationvalid;
}
public static void displayMessage(boolean concentrationvalid)
{
if (concentrationvalid==true)
{
JOptionPane.showMessageDialog(null, "Yes, that is a valid concentration");
}
else
{
JOptionPane.showMessageDialog(null,"I'm sorry, that is not a valid concentration");
}
}
}
if (concentrations[i]==studentconcentration)
That is not how you compare strings in Java!
Instead use if (concentrations[i].equals(studentconcentration))
Basically, == only compares references (or values for primitive types), for a more detailed description of why it is this way, see this question
You have a comparison error. In Java, using == operator fails with strings since strings are not primitive types, they are objects. So you have to use the equals method of the String class, like this.
if (concentrations[i].equals(studentconcentration))
This should work. Also you can add a break; statement if the validation is true to save some cpu processing. One more thing, there is no need to add == true in the if comparison of booleans, you can just use
if (concentrationvalid)
The above statement is the same as with your statement but is more readable.
Hope this helps.
You would need to use .equals() to compare strings in Java. It will return a boolean value of true or false which would activate the if statement if true or skip it if false.
You can also use .equalsIgnoreCase() if you want the comparison to ignore whether the letters are upper/lower case.
Ex:
if (concentrations[i].equals(studentconcentration))
or
if (concentrations[i].equalsIgnoreCase(studentconcentration))
Hope that helps!

Error while using ternary operator

I'm writing my Code with Eclipse Juno and I'm using a hash table to set my dataImportObject depending on the entries in it.
Could anyone please tell me whats wrong about this:
ht is my hashTable with <String, Integer> pairs in it
(ht.containsKey("DEVICE_ADDRESS")) ?
dataImportObject.setDevice_Address(dataitems[ht.get("DEVICE_ADDRESS")]) :
dataImportObject.setDevice_Address("");
Could anyone please tell me whats wrong about this
Two things:
The conditional operator can't be used as a statement on its own, only as an expression
I assume these set methods have void return types, so they can't appear as operands in the conditional operator
Three options:
Use an if statement:
if (ht.containsKey("DEVICE_ADDRESS")) {
dataImportObject.setDevice_Address(dataitems[ht.get("DEVICE_ADDRESS")]));
} else {
dataImportObject.setDevice_Address("");
}
Use the conditional operator inside the setDevice_Address call, or even clearer, beforehand:
String address = ht.containsKey("DEVICE_ADDRESS")
? dataitems[ht.get("DEVICE_ADDRESS")] : "";
dataImportObject.setDevice_Address(address);
If you know that your hashtable won't have any null values, you can avoid the double lookup:
Integer index = ht.get("DEVICE_ADDRESS");
String address = index == null ? "" : dataitems[index];
dataImportObject.setDevice_Address(address);
You can't set the return type of ternary condition to void.
Use if else for that.
Possible duplicate

Categories