the result seems wrong - java

my code will be display me That is not an acceptable input. if I insert negative number. then proceed to prompt the input. But it continue to calculate. this is part of my code contains something wrong. but i did not see.
public static boolean checkOctal()
{
boolean b = true;
if (oct < 0 && oct > 99999999 )
{
b = false;
System.out.println("That is not an acceptable input.");
}
int tmp;
int tmp1 = oct;
while (tmp1 > 0)
{
tmp = tmp1 % 10;
tmp1 = tmp1 / 10;
if (tmp >= 0 && tmp < 8)
{
continue;
} else
{
b = false;
break;
}
}
return b;
}

you should write
if (oct < 0 || oct > 99999999 )
instead of
if (oct < 0 && oct > 99999999 )
|| stands for or, while && for and.

Actually, I doubt that it's displaying anything. Look at the condition:
if (oct < 0 && oct > 99999999 )
How can a number be negative and largely positive at the same time? You want an "or" condition.
Next, look at what you're doing if you did meet the condition:
{
b = false;
System.out.println("That is not an acceptable input.");
}
You're just keeping going - it will return the right result (false) but it's pointless. You know the result already, so why not just return it?
You want:
if (oct < 0 || oct > 99999999 )
{
System.out.println("That is not an acceptable input.");
return false;
}
Or, better yet, perform the validation earlier (before calling the method) - and throw an exception if the input is invalid. Currently you're giving the same result for "invalid input" as for "valid but non-octal input" which doesn't sound like a good idea to me.
Note that the approach of "return as soon as you know the value" is one I'd take for the rest of the method too - I wouldn't bother with a b variable at all. I'd change your loop to something like this:
int value = oct;
while (value > 0)
{
int digit = value % 10;
if (digit >= 8)
{
return false;
}
value = value / 10;
}
return true;
You don't need to worry about digit being negative, as you've already checked that you started off with a non-negative value.
Additionally, it seems odd that this method doesn't have oct as a parameter. That would make it more self-contained.

You should probably check your boolean logic:
if (oct < 0 && oct > 99999999 )
will never be true - no number is less than zero and larger than 999999 at the same time... The symbol || (logical "or") is what you need instead.
Cheers,

Related

multiple conditions else / if statement somehow wrong?

I'm doing a hackernet challenge where n is an int input. The conditions are:
If n is odd, print Weird
If n is even and in the inclusive range of 2 to 5, print Not Weird
If n is even and in the inclusive range of 6 to 20, print Weird
If n is even and greater than 20, print Not Weird.
Im sure the code makes logic and dont think theres syntax. It gives the correct responses and hackernet still says its incorrect so ive come here to see if anyone can see what the problem is
public static void main(String[] args)
{
int N = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
if (N % 2 != 0 || N % 2 == 0 && N >= 6 && N <= 20)
{
System.out.print("weird");
}
else
{
System.out.print("not weird");
}
}
The problem is the logic in your else condition, which would also catch values of N which are less than 2. Try this version:
if (N % 2 != 0)
{
System.out.print("weird");
}
else if (N >= 2 && N <= 5 || N > 20)
{
System.out.print("not weird");
}
else if (N >= 6 && N <= 20)
{
System.out.print("weird");
}
else
{
// NOTE: if the code still fails, remove this else condition
System.out.print("unexpected value of N");
}
Note: To get your code to pass the Hackernet task, you might have to completely remove the else condition. I added it for completeness, but Hackernet might test N=1 to see if nothing gets printed.
Read this condition :
if (N % 2 != 0 || N % 2 == 0 && N >= 6 && N <= 20)
as
if (N % 2 != 0 || (N % 2 == 0 && N >= 6 && N <= 20))
Then see how operator precedence changes the behaviour and yield desired results.
Check the following one
public static void main(String[] args)
{
int N = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
if(N%2!=0) {
System.out.print("weird");
}else if(N>=2 && N<=5) {
System.out.print("not weird");
}else if(N>=6 && N<=20) {
System.out.print("weird");
}else if(N>20) {
System.out.print("not weird");
}
}
For the technical part: start by reading about
precedence of java operators and then make your code easier to read.
Pushing that many conditions into a single if is not helpful. You see it yourself: you think the code is correct, but probably it isn't. And now you look to other people to explain your overly complex code back to you. And of course, all the other answers do all that for you ... but beyond that:
The "real" answer here is: learn how to test your code.
Instead of having a main that somehow asks for a number, and then makes decisions, write a method boolean isWeird() that takes a number and returns true/false according to your requirements.
And then simply test that method with all reasonable cases. And then check if that result is as expected.
Using JUnit, you could write something like
assertThat(isWeird(1), true);
assertThat(isWeird(21), true);
assertThat(isWeird(22), true);
...
Ideally, you write such tests before you implement that method. And then you implement all the conditions, and any check that fails tells you that you got something wrong.
I feel, In the if (N % 2 != 0 || N % 2 == 0 && N >= 6 && N <= 20) condition, you are verifiying the odd and even values at same time using && and || operator. Can you modify the condition into like this if (N % 2 != 0 || (N % 2 == 0 && N >= 6 && N <= 20)) and check? If N is odd weird will be printed or if N is even and it falls under the 6 and 20 inclusive, weird will be printed.
You already have a good few answers here but if you think logically about what you actually need, you can break it down easier.
It looks like the only "Not Weird" print out is 2, 4 and even numbers > 20
So an example could be something like:
if (n % 2 == 0) {
if ((n >= 2 && n <= 5) || (n > 20)) {
return "Not Weird";
}
}
return "Weird";
You can try this
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
if (n % 2 == 1 || (n >= 6 && n <= 20)) {
System.out.println("Weird");
} else {
System.out.println("Not Weird");
}
scanner.close();
}

verification on two Strings

i need help on a verification on a string
I have to write a method that verify if 2 parameters of the method have the same length and if the second one have numbers between 0 and 3.
Let's see what i wrote :
public static boolean coupEstValide( String combinaison, String coup ){
boolean res = true;
if(combinaison.length() == coup.length()){
int i = 0;
while(i < coup.length() && res == true){
char t = coup.charAt(i);
if(t <= 0 && t >= 3)
res = false;
i++;
}
}
return res;
in my opinion, this should work... But if i do this :
coupEstValide("555", "104");
it should tell me false but it it's telling me it's true.
Do you guys see what's wrong ?
Thanks
When you compare Character with an integer actually ASCII value of that character gets compared with that integer. That's why you keep getting true.
So as already suggested in the comments you should compare it either as if(t >= '0' && t <= '3') or use any Utility method of java.lang such as Character.compare(char lhs, char rhs).
Hope this would be helpful.
Enjoy!
A few of problems in your code:
If the lengths are different, you are still returning true!
Strings are composed of characters. Their value is their character code. 0 to 3 are 48 to 51, respectively. Use character constants not integer constants: if (t == '0') will check if t is the character "0".
Your logic for the comparison isn't right anyways. Using your original (incorrect) example with integers, and correcting from <= and >= based on your comments: if (t < 0 && t > 3) will never be true, t cannot simultaneously be less than 0 and greater than 3. I'll leave the correct boolean statement as an exercise to the reader (hint: or).
Alright, i fixed the problem.
So as you said, i should've use
if(t < '0' || t > '3')
And to fix the problem of the time both are not the same size, i added an else.
So the full code is that :
public static boolean coupEstValide( String combinaison, String coup ){
boolean res = true;
if(combinaison.length() == coup.length()){
int i = 0;
while(i < coup.length() && res == true){
char t = coup.charAt(i);
if(t < '0' || t > '3')
res = false;
i++;
}
}
else
res = false;
return res;
}
Thanks for your help guys !
This would never true. A number can not be less and equal to zero and at the same time greater and equal to 3.
if(t <= 0 && t >= 3)
If you want to evaluate whether a character is between 0 and 3 you must use this:
if(t >= '0' && t <= '3')
Now if you want to evaluate if the character is not between 0 and 3 then try this:
if (t <'0' || t> '3')
String coup = "053";
boolean res = true;
int i = 0;
while (i < coup.length() && res == true) {
System.out.println(coup.length());
int t = Integer.parseInt(coup.charAt(i) + "");
System.out.println("T is " + t);
if (t <= 0 || t >= 3) {
res = false;
i++;
}
System.out.println("Value i " + i);
System.out.println("Value of the Res at last" + res);
}
may be this could be helpful try to convert it to the integer
according to your code
String coup = "053";
boolean res = true;
int i = 1;
while (i < coup.length() && res == true) {
System.out.println(coup.length());
//int t = Integer.parseInt(coup.charAt(i) + "");
char t = coup.charAt(i);
System.out.println("T is " + t);
if (t <= 0 || t >= 3) {
res = false;
i++;
}
System.out.println("Value i " + i);
System.out.println("Value of the Res at last" + res);
}

Checking if Element Exists in Boolean Array

I took a programming class, and I'm revisiting old programs that I did not quite get right. This one is a Game Of Life program, and I have a question about code cleanup.
I need to make sure that an array element is in bounds before checking whether its neighbor's boolean value is true or false. I have a statement to check if firstGen[0][0]'s top-left (up one row, left one column) is in bounds. Is there an easier or more elegant way to check if an element is in bounds or to restrict the element checks to the boundaries of a given array without using four && conditionals per if statement?
Note that I have only changed the first if statement thus far, so there may be errors elsewhere. I also excluded the boundary checks for the other neighbors.
public static boolean[][] generation(boolean[][] firstGen)
{
int length = firstGen.length;
boolean[][] newGen = new boolean[length][length];
for (int j = 0; j < firstGen[0].length; j++)
{ for (int i = 1; i < firstGen.length; i++)
{
int count = 0;
if ((i-1 >= 0) && (i-1 < length) && (j-1 >= 0) && (j-1 < length)) //top-left element exists
{ if (newGen[i-1][j-1] == true) count++; } //increment `count` if top-left element is true
if ((newGen[i][j] == false) && (count == 3)) newGen[i][j] = true;
else if ((newGen[i][j] == true) && (count == 1)) newGen[i][j] = false;
else if ((newGen[i][j] == true) && (count > 3)) newGen[i][j] = false;
else break;
}
}
return newGen;
}
If i and j are in bounds, then you know for sure that i - 1 < length and j - 1 < length are both true.
Also:
i - 1 >= 0 can be written i > 0
if (condition == true) can be rewritten if (cond)
So you could replace:
if ((i-1 >= 0) && (i-1 < length) && (j-1 >= 0) && (j-1 < length)) //top-left element exists
{ if (newGen[i-1][j-1] == true) count++; } //increment `count` if top-left element is true
by:
//increment `count` if top-left element is true
if (i > 0 && j > 0 && newGen[i-1][j-1]) count++;
That's the best way I can think of to check if its out of bounds, but an alternative method in general, and one that I think gives programs like the Game of Life more exciting outcomes, is adding periodic boundaries. Basically this means that if you walk off one edge, you end up on the other side (like in pac-man). It sounds complicated, but really all it takes is the % function, which returns the remainder of division between the two numbers given.
So:
27 % 5 = 2;
So for adding periodic boundries you would update x and y positions like this:
x = (x + xStep + horizontalSize) % horizontalSize;
y = (y + yStep + verticalSize) % verticalSize;
Where xStep and yStep are +1 or -1 depending on what direction you want to go. (this works nicely with a for loop) The addition of the size is to make sure you go below zero when you get close to borders.
Then you never have to worry about messy border conditions, everything simply overlaps. No need to check each and every border. I hope this makes sense. Please ask for clarification if not. I've used this more for random walker programs but the idea is the same.

python code not running right, same thing in java does

I was trying to solve Project Euler problem 10 using python, but my program gave a wrong result. Since I am a complete noob to python and I could not find any fault in my (apparently brute-force) logic, I wrote a program in java (almost translated it), and it gave a different result, which turned out to be right.
Here is the python code:
from math import *
limit = 2000000
def isPrime(number):
if number == 2: return 1
elif number % 2 == 0: return 0
elif number == 3: return 1
elif number == 5: return 1
elif number == 7: return 1
else:
rootOfNumber = sqrt(number)
tag = 3
while tag < rootOfNumber:
if number % tag != 0:
tag += 2
else:
break ###
if tag >= rootOfNumber: ###EDIT: it should by only tag > rootOfNumber here
return 1 ### Thats what the problem was.
else:
return 0
sum = 2 # 2 is an even prime, something we are not iterating for
for i in range(3, limit, 2):
if isPrime(i) == 1:
sum += i
print(sum)
print('done...')
The equivalent java code is:
public class Prob10{
static int limit = 2000000;
static long sum = 2L; // 2 is an even prime, something we are not iterating for
public static void main (String[] args) {
for(int i = 3; i < limit; i+=2) {
if( isPrime(i) )
sum += i;
}
System.out.println(sum);
}
private static boolean isPrime (int number) {
if (number == 2) return true;
else if (number == 3 || number == 5 || number == 7) return true;
else {
double rootOfNumber = Math.sqrt(number);
int tag = 3;
while (tag < rootOfNumber) {
if (number % tag != 0)
tag +=2;
else
break;
}
if (tag > rootOfNumber)
return true;
else
return false;
}
}
}
I think I am doing some silly mistake or missing some subtle point.
p.s. I know my isPrime implementation is not too good. I am not printing the outputs because it may spoil the problem for others.
Any comments about (bad) style in the python program are welcome.
Try running with your code for example isPrime(49). You should figure out your problem from there. You have replaced a > with a >= in if (tag > rootOfNumber)
.Also as some coding style, you could just replace the first lines with:
if i in (2, 3, 5, 7): return 1
elif number % 2 == 0: return 0
else:
......
After a quick skim it appears to me that this line in the Python version is superfluous and it might be the cause of the problem:
elif number % 2 == 0: return 0
Why don't you return False for return value of 0? That would make it more simple.

How to check if an integer is in a given range?

Hoping for something more elegant than
if (i>0 && i<100)
You could add spacing ;)
if (i > 0 && i < 100)
For those using commons lang an option is to use Range:
Range<Integer> myRange = Range.between(100, 500);
if (myRange.contains(200)){
// do something
}
Also see: how to construct a apache commons 3.1 Range<Integer> object
I think
if (0 < i && i < 100)
is more elegant. Looks like maths equation.
If you are looking for something special you can try:
Math.max(0, i) == Math.min(i, 100)
at least it uses library.
ValueRange range = java.time.temporal.ValueRange.of(minValue, maxValue);
range.isValidIntValue(x);
it returns true if minValue <= x <= MaxValue - i.e. within the range
it returns false if x < minValue or x > maxValue - i.e.
out of range
Use with if condition as shown below:
int value = 10;
if (ValueRange.of(0, 100).isValidIntValue(value)) {
System.out.println("Value is with in the Range.");
} else {
System.out.println("Value is out of the Range.");
}
The below program checks, if any of the passed integer value in the hasTeen method is within the range of 13 (inclusive) to 19 (inclusive).
import java.time.temporal.ValueRange;
public class TeenNumberChecker {
public static void main(String[] args) {
System.out.println(hasTeen(9, 99, 19));
System.out.println(hasTeen(23, 15, 42));
System.out.println(hasTeen(22, 23, 34));
}
public static boolean hasTeen(int firstNumber, int secondNumber, int thirdNumber) {
ValueRange range = ValueRange.of(13, 19);
System.out.println("*********Int validation Start ***********");
System.out.println(range.isIntValue());
System.out.println(range.isValidIntValue(firstNumber));
System.out.println(range.isValidIntValue(secondNumber));
System.out.println(range.isValidIntValue(thirdNumber));
System.out.println(range.isValidValue(thirdNumber));
System.out.println("**********Int validation End**************");
if (range.isValidIntValue(firstNumber) || range.isValidIntValue(secondNumber) || range.isValidIntValue(thirdNumber)) {
return true;
} else
return false;
}
}
OUTPUT
true as 19 is part of range
true as 15 is part of range
false as all three value passed out of range
I think its already elegant way for comparing range. But, this approach cause you to write extra unit tests to satisfy all && cases.
So, you can use any of the below approach to avoid writing extra unit tests.
Using Java 8 Streams:
if(IntStream.rangeClosed(0,100).boxed().collect(Collectors.toList()).contains(i))
Using Math class:
if(Math.max(0, i) == Math.min(i, 100))
Personally I recommend the second approach because it won't end up creating an Array of the size equal to the range you want to check.
I don't see how that's not elegant, but if you repeat the expression often, then it's a good idea to put it into a method, e.g.
class MathUtil
{
public static boolean betweenExclusive(int x, int min, int max)
{
return x>min && x<max;
}
}
This is particularly true if you mix exclusive and inclusive comparisons. The method name can help avoid typos, such as using < when <= should have been used. The method can also take care of ensuring that min < max etc..
If you're looking for something more original than
if (i > 0 && i < 100)
you can try this
import static java.lang.Integer.compare;
...
if(compare(i, 0) > compare(i, 100))
This guy made a nice Range class.
Its use however will not yield nice code as it's a generic class. You'd have to type something like:
if (new Range<Integer>(0, 100).contains(i))
or (somewhat better if you implement first):
class IntRange extends Range<Integer>
....
if (new IntRange(0,100).contains(i))
Semantically both are IMHO nicer than what Java offers by default, but the memory overhead, performance degradation and more typing overall are hadly worth it. Personally, I like mdma's approach better.
if ( 0 < i && i < 100)
if ( 'a' <= c && c <= 'z' )
Google's Java Library Guava also implements Range:
import com.google.common.collect.Range;
Range<Integer> open = Range.open(1, 5);
System.out.println(open.contains(1)); // false
System.out.println(open.contains(3)); // true
System.out.println(open.contains(5)); // false
Range<Integer> closed = Range.closed(1, 5);
System.out.println(closed.contains(1)); // true
System.out.println(closed.contains(3)); // true
System.out.println(closed.contains(5)); // true
Range<Integer> openClosed = Range.openClosed(1, 5);
System.out.println(openClosed.contains(1)); // false
System.out.println(openClosed.contains(3)); // true
System.out.println(openClosed.contains(5)); // true
That's how you check is an integer is in a range. Greater than the lower bound, less than the upper bound. Trying to be clever with subtraction will likely not do what you want.
Use this code :
if (lowerBound <= val && val < upperBound)
or
if (lowerBound <= val && val <= upperBound)
if(i <= 0 || i >=100)
It will work.
if you are using Spring data you can also use the Range object from Spring.
range = new org.springframework.data.domain.Range(3, 8);
range.contains(5) // will return true.
Just my 2 cts
// Exclusive
public boolean isOrdered(int n1, int n2, int n3) {
return n1 < n2 && n2 < n3 ;
}
call it like to see it is one of 1 to 99
if (isOrdered(0,i,100))
Try:
if (i>0 && i<100) {}
it will work at least ;)
If you are confident that numbers are stored in 2's complement form:
return ((x-low) <= (high-low));
A more general and safer solution would be:
return ((x-high)*(x-low) <= 0);
Range<Long> timeRange = Range.create(model.getFrom(), model.getTo());
if(timeRange.contains(systemtime)){
Toast.makeText(context, "green!!", Toast.LENGTH_SHORT).show();
}
if (i in 0..100) {}
please try this for efficient code ;)
If you just want to test whether the value of i is in the range [0..100), and you want the boolean result, then
i >= 0 && i < 100
is fine and will give you true or false. If you are willing to throw an exception if the value is out of range, you can use the built-in checkIndex method
Objects.checkIndex(i, 100)
which will throw IndexOutOfBoundsException if out of range. Granted, it is not a general solution, and is really only prettier if your context is one in which your range check is being done for checking array bounds, but it has the advantage of not needed any third party libraries, which is nice for small programs.
Try this if strategy. Seems solid.
int num = 5;
//random values; can be changed
int a = 3;
int b = 7;
if (num >= 3 && num <= 7) {
//Your Code Here
}
Wrote this program to check the value of 3 integer parameters against a range.
I have created a separate method to check the range of the each value using if/else-if statements.
I hope this helps someone.
public class TeenNumberChecker {
public static void main(String[] args) {
boolean isTeen = hasTeen();
}
public static boolean hasTeen(int valueOne, int valueTwo, int valueThree) {
if (valueOne > 13 && valueOne < 19) {
return true;
} else if (valueTwo > 13 && valueTwo < 19) {
return true;
} else if (valueThree > 13 && valueThree < 19) {
return true;
}else {
return false;
}
}
}

Categories