What does "if (double)" do in C++ - java

I can't seem to get this figured out, or I already made it work but somewhere in my code is another bug...
My question is, can someone translate this C++ code
if (!fmod(x[i][j], 1) && x[i][j]) {
to the Java equivelent.
The variable x has doubles in it's list.
Thanks alot for your help!

if (x[i][j] % 1 == 0 && x[i][j] != 0 ) {
Java doesn't do automatic coercions to the Boolean type, so you have to make Boolean values with != and ==, etc. This just checks to that the double at x[i][j] is a non-zero whole number. (In C++, anything non-zero is true and zero is false.)

You can just use the % operator instead of fmod:
if ((x[i][j] % 1.0 == 0) && (x[i][j] != 0)) {

Related

Using a for loop and charAt(); to print letters of a string in alternating cases

import java.util.*;
public class BugFixes
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
altCaps("Computer Science");
}
static void altCaps(String hi)
{
String hi2 = hi;
int locate = 0;
for(int i = 0; i < hi2.length();i++)
{
if((Character.isLetter(hi2.charAt(locate))))
{
if(hi2.charAt(locate) % 2 == 0)
{
System.out.print(hi2.toLowerCase().charAt(locate));
locate++;
}
else if(hi2.charAt(locate) % 2 == 1)
{
System.out.print(hi2.toUpperCase().charAt(locate));
locate++;
}
}
else if(hi2.charAt(locate) == ' ')
{
System.out.print(" ");
locate++;
}
}
}
}
This is one of the problems that I have on my current lab. I was able to fix a few other mistakes but I can't seem to find this one.
My question is why it is outputting "COMpUtER SCIEnCE"? I don't understand what is happening here and I've been looking through it for an hour now. My goal is to output "CoMpUtEr ScIeNcE"
I thought the (hi2.charAt(locate) % 2 == 0) and vice versa would alternate between the even and odd locations in the string, but I believe I have made a mistake somewhere. I just can't find it.
Using BlueJ V3.1.7
1 year high school Computer Science Experience and currently enrolled in AP Computer Science
Any Tips?
not really. So hi2.charAt(locate) % 2 == 0 is actually checking if the integer value of the character is odd or even, but you want to actually check if the index is odd or even if I get you right. In other words:
hi2.charAt(2) % 2 == 0
Is check if m is odd or even. However, I think you want to check if 2 (the index) is odd or even. I guess from here it's easy to assume that you need to change:
if(hi2.charAt(locate) % 2 == 0)
//...
else if(hi2.charAt(locate) % 2 == 1)
//...
to
if(locate % 2 == 0)
//...
else if(locate % 2 == 1)
//...
This won't give you exactly the output you want, but it's just a matter of inverting the if conditions or the body as you wish. Also, there's no other cases for the operation % 2, meaning you'd only get either an odd or even index, so you could simplify the code by just doing:
if(locate % 2 == 0)
//...
else
//...
Which reads better. Hope this helps!
I would strongly advise refactoring your code to reduce repetative calls, and make inspection of values possible (rather than comparison of function evaluation).
For example:
char currentCharacter = hi2.charAt(locate);
would replace four instances of the function call, and allow you to inspect what the actual value is (rather than what you expect the value to be). This would likely make your error more evident.
Assuming the following values:
hi2 = "Computer Science";
locate = 0;
then it may be worth stepping through the evaluation.
0. hi2.charAt(locate) % 2 == 0
1. "Computer Science".charAt(0) % 2 == 0
2. 'C' % 2 == 0
3. 67 % 2 == 0
4. 1 == 0
5. false
The fundamental problem is that by never assigning your value to a variable, you never take the time to understand what is in it. By assigning it to the variable, you are able to inspect the value using a debugger.
By inspecting the values, we can see that you probably want the mod of 0, not 'C', therefore you probably wanted
0. locate % 2 == 0
1. 0 % 2 == 0
2. 0 == 0
3. true
Bonus
Refactoring your code to reduce repetition, would also highlight other errors. For example, try the following:
assert "CoMpUtEr sCiEnCe".equals(BugFixes.altcaps("Computer Science"));
assert "CoMpUtEr-sCiEnCe 201".equals(BugFixes.altcaps("Computer-Science 201"));
KISS: removal of needless logic would reduce the chance of things going wrong.
For starters, you don't need to reassign the string, or the locate variable, or check if a character is already a character. Just use the iteration integer, if you need it, and the parameter.
Secondly, you're modding the character, not the position.
Anyways, a simple boolean toggle would be easier to understand than modding.
void altCaps(String hi) {
boolean caps = true;
for (char ch : hi.toCharArray()) {
if (ch == ' ') {
System.out.print(ch);
}
else if (Character.isLetter(ch)) {
if (caps) System.out.print(Character.toUpperCase(ch));
else System.out.print(Character.toLowerCase(ch));
caps = !caps; // switch between upper and lower every character
}

I don't understand the difference

I was reviewing some Java code with this line
if ( list.size() == 1 || list.size() <= 4) {...}
I commented that I do not see how that is any different from just doing
if (list.size() <= 4) {...}
he said it matters and needs to be the first. I don't understand. Perhaps if it were something like
if (list.size() == 1 || list.size() <= someVeryCostlyFunction() ) {...}
and the size was expected to be 1 most of the time you might use both, if someVeryCostlyFunction() always returns some positive number >= 1. Otherwise I can't see the difference. We are supposed to check for efficiency.
The code smells with those two conditions:
if (list.size() == 1 || list.size() <= 4)
Perhaps the author have that in mind:
if there is some number of elements in the list that is 4 or less.
More over the current code allows to satisfy the condition even if the list has zero elements - which is most likely wrong.
Another problem with this condition is use of magic number 4?
What is so important about it and why it is not 5?
It should be self documented and distinguished from other 4's that could appear in the code:
int MAX_HANDLED = 4;
if ( list.size() > 0 && list.size() <= MAX_HANDLED )
:
:
int ALL_TIRES = 4;
if (car.getTires() < ALL_TIRES) {
car.stop();
}
As for the performance, I do not see any significant reason why existing condition should be any faster then yours proposed one (even the second would be faster when list.size > 1). See this question of similar concern.

checking for unwanted input (Error Handling)

I want to check if the input my code needs is correct so I put a lot of if statements checking for the requirements and I can't figure out why it's not working. It is supposed to check if n is less or equal to 91 and / or it is a decimal (I don't want my input to be either). This is so that the user doesn't break the program by typing a decimal or a number higher than 91.
while (Error == 1) {
n = user_input.nextDouble();
if ((n - Math.round(n) <= 0.9) && (n - Math.round(n) >= 0.1)) {
System.out.println("Error: No Decimal points please, try again");
continue;
}
if ((n - Math.round(n) <= 0.9) && (n - Math.round(n) >= 0.1) && (n > 91)) {
System.out.println("Error: No Decimal points please, try again");
System.out.println("Error: Number too high, try again");
continue;
}
if (n > 91) {
System.out.println("Error: Number too high, try again");
continue;
}
if (n == Math.round(n)) {
Error = 0;
}
if (n == 0) {
break;
}
}
For some reason when I type 9.1 or 9.9 it doesn't do anything at all. It's blank...
I did >= which is supposed to check if it is bigger or equal to and <= which is supposed to check if it is less or equal to. Is that wrong?
Well, first of all, you seem to want only inputs that are integers less than or equal to 91.
It seems strange that you would say this, but then explicitly grab doubles with the nextDouble() method of Scanner.
There are better ways of checking for integers... see this question What's the best way to check to see if a String represents an integer in Java?
Either way, I'll assume you intend on sticking with your innovative methodology:
You are correct, that in regular math, 9.1 rounds to 9 and the difference between the two is less than or equal to 0.1. Your cases should work.
But welcome to the world of Java floating point algebra! Doubles don't compare well here.
What do I meant that they don't compare well? Well, the difference between your '9.1' and '9' is actually 0.09999999999999964, not 1.
Java doesn't compensate for this when you use basic comparators, so your comparison fails.
Hope is not lost! There is a better way of comparing doubles than using the regular comparison operators.
Introducing.... Double.compare()!! You can read the javadocs on that method, or you can go here for information on what that method does: some reliable tutorial site
However, what if they input 9.0001? Your test fails, even if the comparison works as you'd expect. You really should rethink your math here. As in, try this instead:
Double.compare((n - Math.round(n)),0.0) != 0)
In case of 9.1 and 9.9, none of the conditions are satisfied. That's why nothing is done. Loop is iterated and wait for next double input.
Here, the main culprit is n - Math.round(n). The calculations are not being accurate. For example, in case of 9.1:
n - Math.round(n) value is equal to 0.09999999999999964. So, the condition n - Math.round(n) >= 0.1 is never satisfied and no if block is reached.

How to check whether an int is within a range of values

In a particular if-else, I have to identify if a given value falls within a range. The condition part looks like this:
else if (a==2 && b.equalsIgnoreCase("line")
&& <<Here I need to search if c falls within a range>> && d)
where a is int, b is string, c is int and d is a boolean. Now if c falls within 1 to 8, the condition is true, else it is false. How can I do that?
I think you need you this condition for c
(c > 1 && c < 8) // 1 and 8 are exclusive
(c => 1 && c <= 8) // 1 and 8 are inclusive
Full sample
else if (a==2 && b.equalsIgnoreCase("line")
&& (c > 1 && c < 8) && d)
If you need to check if the values belongs to a set of values, you need to use a Set and then check if the c belongs to that or not. In your original question, it was mentioned as a range and thus the answer. Anyways, this is how you can check a value in a set.
Integer[] arr = {1,4,9,11,13};
Set<Integer> set = new HashSet<>(Arrays.asList(arr));
...
else if (a==2 && b.equalsIgnoreCase("line")
&& (set.contains(c)) && d)
Surprise surprise, it is c >= low && c <= high
To answer to the update, you'll need to employ a set
Set<Integer> validValues = new HashSet<Integer>();
validValues.add(1);
validValues.add(4);
validValues.add(9);
validValues.add(10);
validValues.add(19);
if (validValues.contains(currentVal)) {
// do stuff
}
To curb java's verbosity you may use Guava's immutable set:
Set<Integer> validValues = ImmutableSet.of(1, 4, 9, 10, 19);
Try like this, range1 and range2 are ranges from which you need to check b.
(c < range1 && c > range2) ? d=true : d=false;
You simply need to add:
c > 1 && c < 8
If you ever feel that your conditionals are getting too complicated I'd suggest creating Boolean methods that simplify them down a little. This is a very moderate case, but for example this range problem could be represented by:
public boolean inRange(int num)
{
return (num > 1 && num < 8);
}
Unfortunately, the only way to do it would be using if else statements (as far as I know). A switch statement does not accept conditional operators, and so would not work for that. As suggested by some others, you could use seperate methods, as the methods, would allow you to check if other values were in range as well. Instead of just for this value, however, you could go for something like
public Boolean inRange(int num, int lowBound, int topBound)
{
return (num > lowBound && num < topBound);
}
and just use it in your code like this
else if (a==2 && b.equalsIgnoreCase("line")
&& inBound(c, 1, 8) && d)
It does not look too messy, and will work (you'll need to decide whether it is inclusive or exclusive bounds though).
The reason for the changed method is that it could be used in other places as well, making it useful for range checking.

Implementing array with min-value ints

I currently have a nxn array of ints. I plan to initialize all the cells within the array with infinity and later change it if a value being compared to the cell is lower than the value inside the cell. Here is the pseudo-code of what I came up with so far, using -1 to represent infinity. What do you think? Is this the most efficient way, any bugs?
if(table[i][j] == -1 || (table[i][j] != -1 && table[i][j] > value)
then table[i][j] = value
I would instead start with Integer.MAX_VALUE. This way, the code could be simpler :
if(table[i][j] > value) {
table[i][j]=value;
}
Notice that, were your array to contain doubles, you could even go as far as using Double.POSITIVE_INFINITY.
If you are sure that the value -1 can be treated as a "reserved" value, you should be fine with such approach.
You could also consider encapsulating the datatype in some PossiblyInfinitInteger which has a boolean of whether or not it is set to infinity. Perhaps an overkill, I don't know.
if(table [i][j] == -1 || table[i][j] > value) then ... does the same. I'm not sure, but the compiler may take care of this.
If -1 is reserved, and the values cannot be less than 0, your approach is correct, just compare table[i][j] < value and not visa versa.
If using -1 as a reserved value is a problem, use Integer.MAX_VALUE:
if(table[i][j] == Integer.MAX_VALUE) then table[i][j] = value;

Categories