//first
if(num % 2 == 0 ) {
isEven = true;
}
//second
isEven = (num %2 == 0);
What is the best thing to do, and is first case a case of code smell?
They don't do the same thing - if num is odd, the first leaves isEven with its previous value, the second sets it to false.
I would:
Try to initialize the variable at the point of declaration, and not change it afterwards.
Use the second form in preference to the first in general.
When the body of an if block is just setting a variable, and the value can be expressed as some simple modification of the condition of the if block, and you always want to set some value, I would just use the simple assignment.
The same goes for return statements - I would rather have:
return (num % 2 == 0); // Or (num & 1 == 0)
than
if (num % 2 == 0) {
return true;
} else {
return false;
}
Without knowing anything about the surrounding context, these two version actually differ in their semantics.
The first version will only change the value of isEven if num is an even number. The latter version will always update the value of isEven. So I would definitely prefer the latter, as it ensures isEven holds a useful semantic value.
Related
Another class is going to pass in random numbers into this method(x,y,z). I want to know the boolean that does returns true from my last if() statement, so I can do operations on it. I have explained my logic in the comments.
I am still really new to this, so my logic may be wrong.
public static String FindDate(int x, int y, int z) {
boolean istrue1 =(x >= 1 && x <= 31);
boolean istrue2 =(y >= 1 && y <= 31);
boolean istrue3 =(z >= 1 && z <= 31);
if(istrue1 ^ istrue2){
if(istrue1^istrue3){
if(istrue2^istrue3){//now knowing that no values are the same, i can find the true value.
if(istrue1||istrue2||istrue3){
// I want to store/use/print/know which bool(istrue) that evaluated to true, so I would know if it is
//x,y,z that went through the algorithm successfully.
}
} else{return "Ambiguous";}
}else{return "Ambiguous";}
}else{return "Ambiguous";}
return "true"; //I would actually end up returning the value that went through the algorithm
}
You can store boolean values just like any other type in Java. I'm not sure exactly what your last comment means by "the value that went through", but if you want to keep track of the result of a particular test, you don't necessarily need to write something like
if (a == b) {
return true;
} else {
return false;
}
In that case,
return a == b;
is equivalent. If the expression is more complicated parens are a good idea.
return ((a == b) || c);
And instead of returning, you could always store the result and do something with it later.
bool test = ((a == b) || c);
action(test);
You can your following: But your condition is incorrect 3 variable for two value (true, false) all can't be different. So your logic always return "Ambiguous"
if(istrue1 ^ istrue2){
if(istrue1^istrue3){
if(istrue2^istrue3){
//now knowing that no values are the same, i can find the true value.
if(istrue1||istrue2||istrue3){
// I want to store/use/print/know the bool that evaluated to true, so I would know if it is
//x,y,z that went through the algorithm successfully.
return "true";
}
}
return "Ambiguous";
Instead of:
if(istrue1||istrue2||istrue3)
Its is easiest to just break it down into 3 differnt if statement.
if(istrue1)
if(istrue2)
if(istrue3)
No easy trick that i was hoping for. sad day.
Also the statements i did with the xor(^) operators turns out to be bad logic.
it would be easiest to this:
if(a&&b || a&&c || b&&c)
That would return ambiguous if any combo are both true.
However thats not the original question, but I thought i might as well mention it.
I have four methods that check whether or not a given grid location is next to an occupied location (value of 1). The grid is assumed to wrap around, ie, if in a 50x50 grid[0][1] is the given location and grid[49][1] is occupied, the method should return true/ My checkNorth and checkEast method are working fine, but I get an ArrayIndexOutofBoundsException: -1 error for either the south or west methods every time I run the program. I checked my math and I think it should work - am I using the modulo incorrectly, or am I missing something else?
EDIT: Clarified the wrapping criterion, word use correction.
boolean checkWest(int indexA, int indexB)
{
if (indexA-1 > 0)
{
if (grid[indexA-1][indexB] == 1)
{
return true;
}
}
if (indexA-1 < 0)
{
if (grid[(indexA-1)%width][indexB] == 1)
{return true;}
else return false;
}
return false;
}
I see a couple problems. First, Java arrays are zero-indexed, which means that the first element is at index 0. So it's okay to check grid[indexA-1][indexB] when indexA-1 is equal to 0. Second, you're not properly handling when indexA equals 0. Here is my implementation. I also simplified the logic a bit.
boolean checkWest(int indexA, int indexB)
{
if (indexA > 0)
return grid[indexA - 1][indexB] == 1;
else
return grid[width + indexA - 2][indexB] == 1;
}
EDIT: I'm pretty sure I butchered the math with the second return statement. It should be right now...
Note: Not a duplicate of How do I compare strings in java as I am taking about going through some checks to determine if something is inheriting something something else
Is their a better and more efficient way to do this:
As you can see I am inputting 2 strings then checking them of on a list, as if current = three then it returns true for checking for one, two and three
NOTE: these values(one,two,three) are just placeholders for the example in my use their is no relation between them except that they have a different priority.
public boolean checker(String current, String check) {
if (check.equals("one")) {
if (current.equals("one") || current.equals("two")
|| current.equals("three")) {
return true;
}
}
if (check.equals("two")) {
if (current.equals("two") || current.equals("three")) {
return true;
}
}
if (check.equals("three")) {
if (current.equals("three")) {
return true;
}
}
return false;
}
Here are a few pointers
As Frisch mentioned in comments, use .equals rather than == for String comparison.
Use switch/case
switch (check) {
case "one":
if (current.equals("one")) return true;
case "two":
if (current.equals("two")) return true;
case "three":
if (current.equals("three")) return true;
}
Apart from that, there doesn't seem to be much to do.
Two things.
Don't check strings using equality. Use the .equals() method. You can call it off the string literal. So something like this. Calling it off the string literal is safe even with nulls, which is generally a good thing.
if ("one".equals(check))
You can take advantage of Java's short circuit operators && and ||
if ("one".equals(check)) {
if ("one".equals(current) || "two".equals(current) || "three".equals(current)) {
return true;
}
}
Can become
if ("one".equals(check) && ("one".equals(current) || "two".equals(current) || "three".equals(current))) {
return true;
}
Which will be evaluated from left to right. Since the "one".equals(check) is on the far most left, and is &&'ed with the rest of the statement, Java will bail out of the condition checking if "one".equals(check) is not true, and will not evaluate the rest of the statement.
Since you're just returning true or false, you can also take this a step further and reduce all of your if statements into a single one using De Morgan's laws (http://en.wikipedia.org/wiki/De_Morgan's_laws). Generally you state your boolean if statement in the way that is most natural to you, and then you start simplifying it by applying transformations that keep the logical if statement the same.
A good example of this is, stolen from the below link.
In the context of the main method's program body, suppose the following data is defined:
int score, min = 0, max = 20;
boolean bad, good;
Further suppose that a value is assigned to score, perhaps from a keyboard entry, and I would like to test, with a Boolean expression whether the score is a valid number or not. A good score is in the closed range [0 .. 20], which includes 0 and 20.
good = (score >= min && score <= max);
I would like to get the score from the keyboard in a do while loop, so that I can validate the entry. The logic in my control structure is to demand another entry for the score while the entry is bad. I have a definition of a good entry, and I will use definitions of operators and De Morgan's Law to help me write an expression that represents a bad entry.
good = (score >= min && score <= max); // original definition of good from the logic of my task
good = !(score < min) && !(score > max); // by definition, >= means ! < , <= means ! >
good = !(score < min || score > max); // by De Morgan's' Law
bad = !good ; // bad is not good
bad = !!(score < min || score > max); // substituting for good
bad = score < min || score > max; // double negation is dropped
http://fcmail.aisd.net/~JABEL/1DeMorgansLaw.htm
I would like to update you some thing.
1. We can apply switch cases only on primitive data types but not on objects. As string is object we can't use strings in case/switch statement.
I would like to suggest you to enums/maps in this case.
Please find the below sample programm how i implemented using maps.
public static void main(String[] args) {
Map<String,Integer> map = new HashMap<String, Integer>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
String current = "one";
String check = "one";
if(map.get(check)<=map.get(current)){
System.out.println("Our condition is success");
}
}
Instead of multiple comparison this is better.
---Santhosh
I have a recursive function like this:
public static int h(int n) {
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
} else {
//variable value is a fixed one.
i = value % 2;
return h(n - h(i) - 1) + h(n - 2);
}
}
Suppose the value of variable value is even at this time.Then if I call the function with h(12) I want to know how the function works?
In this case what I want to happen is evaluate
h(12)=h[12-h(0)-1]+h(10)
=h(11)+h(10)
={h(11-h(0)-1)+h(9)}+{h(10-h(0)-1)+h(8)}
={h(10)+h(9)}+{h(9)+h(8)}
Here when evaluating h(11)+h(10) does the function first finish h(11) and get a value for that before starting with h(n-2) which is this case h(10).
If it first finish h(11) then finally it has to reach n==0 or n==1 case.Then by the time it reaches wouldn't h(n-2) be h(-2) or h(-1).
How can I store the initial function call value of 12 and when it reaches h(n-2) to call as h(10) and then make that part to evaluate as h(8),h(6)..
Each function call stores its own copy of arguments. So, call to h(11) won't change n in the first call (h(12)).
Expressions in Java are evaluated from left to right. This means that the call h(11) would finish before h(10) is called from h(12). However, in this case this is not important, since the result would be the same either way.
I'm trying to make a method that will tell me weather or not it is true or false that a number is prime. here's the code:
class prime
{
public static boolean prime (int a, int b)
{
if (a == 0)
{
return false;
}
else if (a%(b-1) == 0)
{
return false;
}
else if (b>1)
{
prime (a, b-1) ;
}
else
{
return true;
}
}
public static void main (String[] arg)
{
System.out.println (prime (45, 45)) ;
}
}
when i try to compile this i get this error message:
prime.java:23: missing return statement
}
^
1 error
I could be misinterpreting what the error message is saying but it seems to me that there isn't a missing return statement since i have a return statement for every possible set of conditions. if a is 0 then it returns false, if it isn't then it checks to see if a is dividable by b if it is then it returns if not then if b is greater than 1 it starts over again. if b isn't greater than 1 it also returns.
Also it seems a bit messy to have to
make this method take two ints that
are the same int.
What is wrong with my syntax/ why am i getting the error message? Is there a way to make it so that the method that i use in main only has to take one int (perhaps another method splits that int into two clones that are then passed to public static boolean primeproper?
or is there a more effective way of
going about this that i'm missing
entirely?
In your prime function, there are four possible code paths, one of which doesn't return anything. That is what the error message is complaining about. You need to replace:
prime (a, b-1) ;
with:
return prime (a, b-1) ;
in the else if (b>1) case.
Having said that, this is actually not a good way to calculate if a number is prime. The problem is that every recursive call allocates a stack frame and you'll get into serious stack overflow problems if you're trying to work out whether 99,999,999 is a prime number?
Recursion is a very nice tool for a certain subset of problems but you need to be aware of the stack depth. As to more efficient solutions, the are many tests you can carry out to determine a number is not prime, then only check the others with a brute force test.
One thing you should be aware of is to check divisibility against smaller numbers first since this will reduce your search scope quicker. And don't use divide where multiply will do, multiplication is typically faster (though not always).
And some possibly sneaky tricks along the lines of:
every number other than 2 that ends in 2, 4, 6, 8 or 0 is non-prime.
every number other than 5 that ends in 5 is non-prime.
Those two rules alone will reduce your search space by 60%. Assuming you get your test number as a string, it's a simple matter to test the last digit of that string even before converting to an integral type.
There are some more complex rules for divisibility checks. If you take a multiple of 9 and sum all the digits to get a new number, then do it again to that number, then keep going until you have a single digit, you'll find that it's always 9.
That will give you another 10% reduction in search space albeit with a more time-expensive check. Keep in mind that these checks are only advantageous for really large numbers. The advantages are not so great for, say, 32-bit integers since a pre-calculated bitmap would be much more efficient there (see below).
For a simplistic start, I would use the following iterative solution:
public static boolean prime (int num) {
int t = 2;
while (t * t <= num) {
if ((num % t) == 0) {
return false;
}
t++;
}
return true;
}
If you want real speed in your code, don't calculate it each time at all. Calculate it once to create a bit array (one of the sieve methods will do it) of all primes across the range you're interested in, then simply check your values against that bit array.
If you don't even want the cost of calculating the array every time your program starts, do it once and save the bit array to a disk file, loading it as your program starts.
I actually have a list of the first 100 million primes in a file and it's easier and faster for me to use grep to find if a number is prime, than to run some code to calculate it :-)
As to why your algorithm (fixed with a return statement) insists that 7 is not prime, it will insist that every number is non-prime (haven't checked with negative numbers, I'm pretty sure they would cause some serious problems - your first check should probably be if (a < 1) ...).
Let's examine what happens when you call prime(3,3).
First time through, it hits the third condition so calls prime(3,2).
Then it hits the second condition since 3 % (2-1) == 0 is true (N % 1 is always 0).
So it returns false. This could probably be fixed by changing the third condition to else if (b>2) although I haven't tested that thoroughly since I don't think a recursive solution is a good idea anyway.
The following complete code snippet will do what you need although I appreciate your curiosity in wanting to know what you did wrong. That's the mark of someone who's actually going to end up a good code cutter.
public class prime
{
public static boolean isPrime (int num) {
int t = 2;
while (t * t <= num) {
if ((num % t) == 0) {
return false;
}
t++;
}
return true;
}
public static void main (String[] arg)
{
System.out.println (isPrime (7)) ;
}
}
You seem to be under the impression that because the recursion will eventually find a base-case which will hit a return statement, then that return will bubble up through all of the recursive calls. That's not true. Each recursive call must pass out the result like this:
return prime(a, b - 1);
If b is larger than 1, your function won't return anything.
May it be return prime (a, b-1) ; ?
To improve efficiency, think more about your conditions. Do you really need test every factor from 2 to N? Is there a different stopping point that will help tests of prime numbers complete more quickly?
To make a better API, consider making the recursive method private, with a public entry point that helps bootstrap the process. For example:
public static boolean prime(int n) {
return recurse(n, n);
}
private static boolean recurse(int a, int b) {
...
}
Making a method private means that it can't be called from another class. It's effectively invisible to users of the class. The intent here is to hide the "ugly" extra parameter by providing a public helper method.
Think about the factors of some composite numbers. 10 factors to 5×2. 12 factors to 6×2. 14 factors to 7×2. Now think about 25. 25 factors to 5×5. What about 9? Do you see a pattern? By the way, if this isn't homework, please let me know. Being this didactic is hard on me.
In answer to why 7 isn't working, pretend you're the computer and work through your logic. Here's what you wrote.
class prime
{
public static boolean prime (int a, int b)
{
if (a == 0)
{
return false;
}
else if (a%(b-1) == 0)
{
return false;
}
else if (b>1)
{
// Have to add the return statement
// here as others have pointed out!
return prime(a, b-1);
}
else
{
return true;
}
}
public static void main (String[] arg)
{
System.out.println (prime (45, 45)) ;
}
}
So let's start with 7.
if(7 == 0) // not true, don't enter this block
else if(7 % 6 == 0) // not true
else if(7 > 1) // true, call prime(7, 6)
if(7 == 0) // not true, don't enter this block
else if(7 % 5 == 0) // not true
else if(6 > 1) // true, call prime(7, 5)
if(7 == 0) // not true, don't enter this block
else if(7 % 4 == 0) // not true
else if(5 > 1) // true, call prime(7, 4)
... keep going down to calling prime(7, 2)
if(7 == 0) // not true, don't enter this block
else if(7 % 1 == 0) true, return false
When you get down to calling prime(n, 2), it will always return false because you have a logic error.
Your recursive method must return a value so it can unroll.
public static boolean prime (int a, int b)
{
if (a == 0)
{
return false;
}
else if (a%(b-1) == 0)
{
return false;
}
else if (b>1)
{
return prime (a, b-1) ;
}
else
{
return true;
}
}
I might write it a different way, but that is the reason that you are not able to compile the code.
I think the original question was answered already - you need to insert return in the body of else if (b>1) - I just wanted to point out that your code still will crash when given 1 as the value for b, throwing an ArithmeticException since a%(b-1) will be evaluated to a%0, causing a division by zero.
You can avoid this by making the first if-statement if (a == 0 || b == 1) {}
This won't improve the way the program finds primes, it just makes sure there is one less way to crash it.
Similar to #paxdiblo's answer, but slightly more efficient.
public static boolean isPrime(int num) {
if (num <= 1 || (num & 1) == 0) return false;
for (int t = 3; t * t <= num; t += 2)
if (num % t == 0)
return false;
return true;
}
Once it is determined that the number is not even, all the even numbers can be skipped. This will halve the numbers which need to be checked.