Else If statement with 2 variables [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a task to write a simple Java program:
I have two integers a and b. If a>10 and b<10 then it should print out "balanced" and if not then print out "unbalanced"
I know how to make this with 1 variable, but i don't have clue how to make it with 2.
Here is something I have tried:
public static void main(String args[]) {
int a = 1;
int b = 15;
if (a > 10 && b <= 10)
{
System.out.println("balanced");
}
else
{
System.out.println("unbalanced);
}
}

Your code not even compile since there is syntax error. You can make your mistake correct as follows.
int a = 1;
int b = 15;
if (a > 10 & b <= 10) { // why <= by reading your question it should <
System.out.println("balanced");
} else {
System.out.println("unbalanced");
}
Now out put is unbalanced.
Now let's review your code. you have use &(non short circuit) and here. That's not good since always non short circuit operands evaluate both side of the expression.
So you should use && (short circuit)
int a = 1;
int b = 15;
if (a > 10 && b <= 10) {
System.out.println("balanced");
} else {
System.out.println("unbalanced");
}
What's wrong with non short circuit?
Consider following logic.
if(name!=null&name.getFirstName()=="same"){ // Now both side evaluate
}
what happen name==null?, name.getFirstName() will give you NullPointerException. If you use && short circuit you are same from this NPE
if(name!=null&&name.getFirstName()=="same"){ // if first case false not
evaluate second
}

Use && instead of & so that it does a logical and not a bitwise one.
You will find it clearer to read if you put brackets around (a > 10) && (b <= 10) as well.

Related

Needing help understanding logic in "Head First Java" [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have recently started programming in Java for the first time (just as a hobby), and at the moment Im working with a book "Head First Java" that is very good, but I'm really struggling with understanding the exercises.
Like this for example:
class Output {
void go() {
int y = 7;
for(int x = 1; x < 8; x++) {
y++; // is y now 8?
if(x >4) {
System.out.println(++y + " "); // does this make y = 9?
}
if(y > 14) {
System.out.println(" x = " + x);
break; // how does the break key word affect the rest of the loop?
}
}
}
public static void main(String[] args) {
Output o = new Output();
o.go();
}
}
Can someone please explain to me what goes on in this code?
Variable y must be 15, because you increased it's value many times with the for loop.
++y increases it's value by 1. i++ and ++i are very similar but not exactly the same. Both increment the number, but ++i increments the number before the current expression is evaluted, whereas i++ increments the number after the expression is evaluated.
break simply exists from the loop.

Shorter version of calculation [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have two methods, that I believe can be made better way, but can't find this way.
First:
public int calcPow(long num) {
int count = 0;
while(num/2!=0) {
num = num/2;
count++;
}
return count;
}
The second is:
private long findParentNumber(long value) {
for(int bitNum = 0; bitNum < Long.SIZE; bitNum++) {
if((value & (1L << bitNum)) != 0) {
return value ^ (1L << bitNum);
}
}
throw new RuntimeException("No parent number found");
}
I believe, there are ways to do the same without loops. Can you help?
Cheers!
For the second one, you're unsetting the lowest set bit. There's a relatively well known bithack to do that, though only relatively because it seems that bithacks in general are not well known.
Anyway, it's
return x & (x - 1);
The logic here is that in x - 1, there's a borrow running through the lowest zeroes until it hits the lowest 1-bit, which it unsets. The lowest zeroes are left set, they are then removed by ANDing it with the original number.
You can write the first one in terms of numberOfLeadingZeros, which would be more obviously correct than floating point hacks which always make you think about how accurate they might be (and in any case they're slow, you might be better off with the loop).
Edit: for completeness, that would be 63 - numberOfLeadingZeros(x), it differs from your definition at x = 0 but that's a bad input anyway.
Try this for the first one.
public int calcPow(long num) {
if (num == 0) return 0;
if (num < 0) num = -num;
return Long.numberOfTrailingZeros(Long.highestOneBit(num));
}
Or this suggested by harold
public int calcPow(long num) {
return num == 0 ? 0
: 63 - Long.numberOfLeadingZeros(Math.abs(num));
}
For the first one, you can use the Math.log method that already exists:
public static int log2(long number) {
return (int) Math.floor(Math.log(number) / Math.log(2));
}
or this faster function suggested by saka1029:
public static int log2(long number) {
return number == 0? 0: Long.numberOfTrailingZeros(Long.highestOneBit((number < 0)? number * -1: number));
}
As you can see I also changed the method to static, since I see no point in having to use an Object to get a log when no object is involved. And secondly I changed the names into something more fitting.
For the second one you can use the bit-wise check operator &:
public static long removeSmallBit(long value) {
return value & (value - 1);
}
Essentially you are removing the smallest bit from the variable, and return that number after you change that bit to 0. And as you can see again I made the method static and changed the name. 2nd answered inspired by this answer submitted by harold

Java for loop confusion, something I am missing (am a beginner) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a for loop in java like below,
for (int x = cell.getGridX() - 1; x >= 0 && compareCells(cell, getCell(x, cell.getGridY())); --x, ++matches[0]);
I need to add more validation to the condition so I changed it to,
for (int x = cell.getGridX() - 1; x >= 0; --x) {
if (compareCells(cell, getCell(x, cell.getGridY()))) {
++matches[0];
}
}
But now it doesn't behave as expected, I cannot figure out why, thanks.
In your original for loop, the --x and ++matches[0] were executed only when x >= 0 AND compareCells(cell, getCell(x, cell.getGridY())) resulted as true.
In your new for loop, --x is executed every time x >= 0, and ++matches[0] is only executed when the compareCells() function returns true. To match the original functionality, it'd look more like the following:
for (int x = cell.getGridX() - 1; x >= 0; ;) {
if (compareCells(cell, getCell(x, cell.getGridY()))) {
--x;
++matches[0];
continue;
}
break;
}

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.)

Categories

Resources