I am new to Java. I wrote this program and when I run it, it always gives me that the answer is 0.0   Can you tell me what I did wrong?  import java.util.Scanner; public class Learnclass {     public static void main(String[] args) {         Double fnum, snum;         Double ans = 0.0;         String opr;         Scanner getIn = new Scanner(System.in);           System.out.print("Enter your first number: ");         fnum = getIn.nextDouble();         System.out.print("Enter your second number: ");         snum = getIn.nextDouble();         System.out.print("Enter the operation: ");         opr = getIn.next();       if(opr == "add") {         ans = fnum + snum;    }       System.out.print("Answer is " + ans); }  }
93
I've been using the == operator in my program to compare all my strings so far. However, I ran into a bug, changed one of them into .equals() instead, and it fixed the bug.  Is == bad? When should it and should it not be used? What's the difference?
2140
What I would like is a method to convert a double to a string which rounds using the half-up method - i.e. if the decimal to be rounded is 5, it always rounds up to the next number. This is the standard method of rounding most people expect in most situations.  I also would like only significant digits to be displayed - i.e. there should not be any trailing zeroes.  I know one method of doing this is to use the String.format method:  String.format("%.5g%n", 0.912385);   returns:  0.91239   which is great, however it always displays numbers with 5 decimal places even if they are not significant:   String.format("%.5g%n", 0.912300);   returns:  0.91230   Another method is to use the DecimalFormatter:  DecimalFormat df = new DecimalFormat("#.#####"); df.format(0.912385);   returns:  0.91238   However as you can see this uses half-even rounding. That is it will round down if the previous digit is even. What I'd like is this:  0.912385 -&gt; 0.91239 0.912300 -&gt; 0.9123   What is the best way to achieve this in Java?
113604
I was messing around with my TI-84 Plus Silver Edition calculator and discovered that it will actually give me values when taking the factorial of any number $n/2$ where $n$ is any integer greater than $-2$. Why does this happen? I thought factorials were only defined for positive integers and $0$, so what is my calculator doing to get the answer $3.32335097$ when I enter $2.5!$? Is there actually a definition of $2.5!$ or is my calculator just being weird? How is the factorial function implemented?  I understand the binary implications of $2.5$, so that could possibly have something to do with it. I get a domain error when trying to take the factorial of $-1, 2.3, e$, and any number that is not of the form $n/2$ where $n$ is any integer greater than $-2$.
13332
I am trying to use a  as input and then creating a query with it - so I need a .    I was surprised to find that it couldn't do the conversion implicitly or explicitly - but I don't even know how I would do this, as the Java API is still fairly new to me.
31758
The documentation for the  function states that you pass it a number, and the positions past the decimal to round. Thus it should do this:  n = 5.59 round(n, 1) # 5.6   But, in actuality, good old floating point weirdness creeps in and you get:  5.5999999999999996   For the purposes of UI, I need to display 5.6. I poked around the Internet and found some  that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. .  Short of creating my own round library, is there any way around this?
82915
For example, the standard division symbol '/' rounds to zero:  &gt;&gt;&gt; 4 / 100 0   However, I want it to return 0.04. What do I use?
57685
I still can't wrap my head around this one and have to consult references every time I want to be safe:   Is it "0.4 point" or "0.4 points"?   Is it "1.0 point" or "1.0 points"?   I know that I can work around that by using four tenths of a point or one point instead, but sometimes writing 0.4 point/points or 1.0 point/points is called for, especially in technical documents.  I gathered that this mostly goes by the style guide I choose to (or have to) use, and it's quite possible that there is no universally accepted convention for this. Then again, in light of potential benefits for learners here, I think it's worth asking, and I hope that we can lay out some rules of thumb, something that can be used as a general guideline, especially on writing tests and exams.  Addendum: another case that's worth mentioning in answers, for completeness, is "0.0 point" or "0.0 points"? In my humble opinion, it's safe to assume that most learners on our site know what to use when the quantity falls out of the range between -1.0 and 1.0.
25130
Of course most languages have library functions for this, but suppose I want to do it myself.  Suppose that the float is given like in a C or Java program (except for the 'f' or 'd' suffix), for example "4.2e1", ".42e2" or simply "42". In general, we have the "integer part" before the decimal point, the "fractional part" after the decimal point, and the "exponent". All three are integers.  It is easy to find and process the individual digits, but how do you compose them into a value of type float or double without losing precision?  I'm thinking of multiplying the integer part with 10^n, where n is the number of digits in the fractional part, and then adding the fractional part to the integer part and subtracting n from the exponent. This effectively turns 4.2e1 into 42e0, for example. Then I could use the pow function to compute 10^exponent and multiply the result with the new integer part. The question is, does this method guarantee maximum precision throughout?  Any thoughts on this?
99038
Which libraries for Java are there that have a fast implementation for floating point or fixed point operations with a precision of several thousands of digits? How performant are they?  A requirement for me is that it implements a multiplication algorithm that is better than the naive multiplication algorithm that takes 4 times as much time for a 2 times larger number of digits (compare ).
9792
Yesterday I had a two-hour technical phone interview (which I passed, woohoo!), but I completely muffed up the following question regarding dynamic binding in Java.  And it's doubly puzzling because I used to teach this concept to undergraduates when I was a TA a few years ago, so the prospect that I gave them misinformation is a little disturbing...  Here's the problem I was given:  /* What is the output of the following program? */  public class Test {    public boolean equals( Test other ) {     System.out.println( "Inside of Test.equals" );     return false;   }    public static void main( String [] args ) {     Object t1 = new Test();     Object t2 = new Test();     Test t3 = new Test();     Object o1 = new Object();      int count = 0;     System.out.println( count++ );// prints 0     t1.equals( t2 ) ;     System.out.println( count++ );// prints 1     t1.equals( t3 );     System.out.println( count++ );// prints 2     t3.equals( o1 );     System.out.println( count++ );// prints 3     t3.equals(t3);     System.out.println( count++ );// prints 4     t3.equals(t2);   } }   I asserted that the output should have been two separate print statements from within the overridden equals() method: at t1.equals(t3) and t3.equals(t3).  The latter case is obvious enough, and with the former case, even though t1 has a reference of type Object, it is instantiated as type Test, so dynamic binding should call the overridden form of the method.  Apparently not.  My interviewer encouraged me to run the program myself, and lo and behold, there was only a single output from the overridden method: at the line t3.equals(t3).  My question then is, why?  As I mentioned already, even though t1 is a reference of type Object (so static binding would invoke Object's equals() method), dynamic binding should take care of invoking the most specific version of the method based on the instantiated type of the reference.  What am I missing?
33306
Hey! I was looking at this code at   I noticed that in some situations they used hex numbers, like in line 134:  for (j = 1; val &amp;&amp; j &lt;= 0x80; j &lt;&lt;= 1, q++)   Now why would they use the 0x80? I am not that good with hex but I found an online hex to decimal and it gave me 128 for 0x80.  Also before line 134, on line 114 they have this:  small_n = (n &amp; 0xffff0000) == 0;   The hex to decimal gave me 4294901760 for that hex number. So here in this line they are making a bit AND and comparing the result to 0??  Why not just use the number? Can anyone please explain and please do give examples of other situations.  Also I have seen large lines of code where it's just hex numbers and never really understood why :(
32263
Can you please tell me how much is (-2) % 5? According to my Python interpreter is 3, but do you have a wise explanation for this?  I've read that in some languages the result can be machine-dependent, but I'm not sure though.
26183
Seems like the subtraction is triggering some kind of issue and the resulting value is wrong.  double tempCommission = targetPremium.doubleValue()*rate.doubleValue()/100d;   78.75 = 787.5 * 10.0/100d  double netToCompany = targetPremium.doubleValue() - tempCommission;   708.75 = 787.5 - 78.75  double dCommission = request.getPremium().doubleValue() - netToCompany;   877.8499999999999 = 1586.6 - 708.75  The resulting expected value would be 877.85.  What should be done to ensure the correct calculation?
41641
What is the most efficient way of testing an input string whether it contains a numeric value (or conversely Not A Number)? I guess I can use Double.Parse or a regex (see below) but I was wondering if there is some built in way to do this, such as javascript's NaN() or IsNumeric() (was that VB, I can't remember?).  public static bool IsNumeric(this string value) {     return Regex.IsMatch(value, "^\\d+$"); }
57062
Today I needed a simple algorithm for checking if a number is a power of 2.  The algorithm needs to be:   Simple Correct for any ulong value.   I came up with this simple algorithm:  private bool IsPowerOfTwo(ulong number) {     if (number == 0)         return false;      for (ulong power = 1; power &gt; 0; power = power &lt;&lt; 1)     {         // This for loop used shifting for powers of 2, meaning         // that the value will become 0 after the last shift         // (from binary 1000...0000 to 0000...0000) then, the 'for'         // loop will break out.          if (power == number)             return true;         if (power &gt; number)             return false;     }     return false; }   But then I thought, how about checking if log2 x is an exactly round number? But when I checked for 2^63+1, Math.Log returned exactly 63 because of rounding. So I checked if 2 to the power 63 is equal to the original number - and it is, because the calculation is done in doubles and not in exact numbers:  private bool IsPowerOfTwo_2(ulong number) {     double log = Math.Log(number, 2);     double pow = Math.Pow(2, Math.Round(log));     return pow == number; }   This returned true for the given wrong value: 9223372036854775809.  Is there a better algorithm?
61612
I'm looking for a  way to convert numbers to string format, dropping any redundant '.0'   The input data is a mix of floats and strings. Desired output:  0   --> '0'  0.0 --> '0'  0.1 --> '0.1'  1.0 --> '1'  I've come up with the following generator expression, but I wonder if there's a faster way:  (str(i).rstrip('.0') if i else '0' for i in lst)   The truth check is there to prevent 0 from becoming an empty string.  EDIT: The more or less acceptable solution I have for now is this:  ('%d'%i if i == int(i) else '%s'%i for i in lst)   It just seems strange that there is no elegant way to handle this (fairly straightforward) case in python.
87341
An array is defined to be maxmin equal if it contains at least two different elements and the number of times the maximum value occur is the same as the number of times the minimum value occur. So {11, 4, 9, 11, 8, 5 , 4, 10} is maxmin equal, because the max value 11 and min value 4 both appear two times in the array.   if the input array is {} , isMaxMinEqual should return false (array must have at least two different elements) status = false; if the input array is {2}, isMaxMinEqual should return false (array must have at least two different elements). if the input array is {1,1,1,1,1,1}, isMaxMinEqual should return false (array must have at least two different elements).  if the input array is {2,4,6,8,11}, isMaxMinEqual should return true (Both max value(11) and min value 2 appear exactly one time). if the input array is {-2,-4,-6,-8,-11}, isMaxMinEqual should return true(Both max value(-2) and min value -11 appear exaclty one time).   I wrote the class MaxMin which satisfied the above condition.  public class MaxMin {  public static void main(String args[]) {     System.out.println("The result is: " + isMaxMinEqual(new int[]{2, 2})); }  public static boolean isMaxMinEqual(int[] a) {     boolean status = false;     int count = 0;     if (a.length &lt; 2) {         status = false;         return status;     }     for (int i = 1; i &lt; a.length; i++) {         if (a[i - 1] != a[i]) {             count++;         }     }      int max = a[0];     int min = a[0];     for (int i = 0; i &lt; a.length; i++) {         if (a[i] &gt; max) {             max = a[i];         } else if (a[i] &lt; min) {             min = a[i];         }     }      int maxCount = 0;     for (int j = 0; j &lt; a.length; j++) {         if (a[j] == max) {             maxCount++;         }     }      int minCount = 0;     for (int j = 0; j &lt; a.length; j++) {         if (a[j] == min) {             minCount++;         }     }     System.out.println(count);     System.out.println("max is: " + max);     System.out.println("min is: " + min);     System.out.println("Max Count is: " + maxCount);     System.out.println("Min Count is: " + minCount);      if (maxCount == minCount &amp;&amp; count &gt;= 1) {         status = true;     }      return status; } }