I am making a java calculator to find out the density and viscosity of aqueous sucrose solutions (chemistry stuff) and decided to go farther with it. I used Micheal Flanagan's Java library for Sucrose which is the:  import flanagan.physprop.Sucrose;   in the code. I wanted a way to continue entering equations without having to continue pressing run over and over so I created  public static void restart() {     System.out.println("would you like to calculate another solution?(y/n)");     String yn = new String(input.nextLine());     String y = "y";     String n = "n";     System.out.println(yn);     if (yn == y){         tf = true;     }     else {         if (yn == n) {             tf = false;         }         else {         System.out.println("ERROR: Please print 'y' or 'n'");         restart();         }     }     if (tf == true) {         calc();     }     if (tf == false) {         fin();     } }   I am using a scanner called 'import' which is defined in an earlier line.  static Scanner input = new Scanner(System.in);   So, anyway, what is happening is the code is not restarting, but instead triggering the error. I have tried fixing it by defining the readout as a string and making variables for "y" and "n". I am thinking that "yn" is not registering properly as a string, and cannot think of anything else.  flanagan.jar can be found .
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?
117335
I'm trying to check if an input is an integer and I've gone over it a hundred times but don't see the error in this. Alas it does not work, it triggers the if statement for all inputs (numbers/letters)  read scale if ! [[ "$scale" =~ "^[0-9]+$" ]]         then             echo "Sorry integers only" fi   I've played around with the quotes but either missed it or it did nothing. What do I do wrong? Is there an easier way to test if an input is just an INTEGER?
80420
In the case of languages with a C-like syntax, we declare the main() method to return an int or float value (or void).  Is it possible to declare a non-void return type from main() in Java?  If not, then why not?  Does this mean that a Java program doesn't return any value to the OS?
69342
I'm using this code to let the user enter in names while the program stores them in an array until they enter an empty string (they must press enter after each name):  people = [] info = 'a' # must fill variable with something, otherwise loop won't execute  while not info.empty?     info = gets.chomp     people += [Person.new(info)] if not info.empty? end   This code would look much nicer in a do ... while loop:  people = []  do     info = gets.chomp     people += [Person.new(info)] if not info.empty? while not info.empty?   In this code I don't have to assign info to some random string.  Unfortunately this type of loop doesn't seem to exist in Ruby. Can anybody suggest a better way of doing this?
5691
Is there a better way of getting this result? This function fails if num has more digits than digits, and I feel like it should be in the library somewhere (like Integer.toString(x,"%3d") or something)  static String intToString(int num, int digits) {     StringBuffer s = new StringBuffer(digits);     int zeroes = digits - (int) (Math.log(num) / Math.log(10)) - 1;      for (int i = 0; i &lt; zeroes; i++) {         s.append(0);     }     return s.append(num).toString(); }
27140
This is a problem I've ran into several times, and I imagine that others have ran across it too.    Basically, I have a complicated equation, and I want the user to type in the values needed to calculate the results.  (For what it's worth, there are good default values for the variables in the equation.)  I've constructed a GUI that shows the user the names of the variables/fields that need to be provided, along with a control (like a numeric up/down, slider, etc.) to enter the values of the field.  Below that, I have an area that shows the output of the equation.  So my question is this.  Should my results area automatically change the calculated results whenever the user makes any changes to any of the input fields, or should they push a "Calculate" button to generate the results?  One other thing that probably applies is that the user is not trying to "get the right answer" out of the results.  They shouldn't be using the output to then go back and modify the input to get a better answer.  Are there any benefits to requiring the button press?  Is the extra click to see the results worth those benefits?
74793
I have written a method which I will call in a Trigger.While trying to save this code as Apex class, I am getting the error " Error: Compile Error: Loop variable must be of type SObject at line 7 column 13"   My code goes as below ,appreciate any help, thanks  public class LeadBefore {     public static void UpdateChapterEmailAddress (){          set&lt;Id&gt; JDRFLocationId = new set&lt;Id&gt;();         List&lt;Lead&gt; vLstLead = new List&lt;Lead&gt;();           for(Lead vLead:trigger.new)         {             if(vLead.JDRF_Location__c != null)             {                 JDRFLocationId.add(vLead.JDRF_Location__c);                 vLstLead.add(vLead);             }         }         Map&lt;Id, JDRF_Location__c&gt; vMapIdJDRFLocat = new Map&lt;Id, JDRF_Location__c&gt;([Select Id, Name, General_Email_Address__c from JDRF_Location__c where Id In: JDRFLocationId]);         for(Lead vLead: vLstLead)         {             if(vMapIdJDRFLocat.containsKey(vLead.JDRF_Location__c))             {                 vLead.Chapter_Email_Address__c = vMapIdJDRFLocat.get(vLead.JDRF_Location__c).General_Email_Address__c;             }         }     } }
26673
Switch statement fallthrough is one of my personal major reasons for loving switch vs. if/else if constructs. An example is in order here:  static string NumberToWords(int number) {     string[] numbers = new string[]          { "", "one", "two", "three", "four", "five",            "six", "seven", "eight", "nine" };     string[] tens = new string[]          { "", "", "twenty", "thirty", "forty", "fifty",            "sixty", "seventy", "eighty", "ninety" };     string[] teens = new string[]         { "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",           "sixteen", "seventeen", "eighteen", "nineteen" };      string ans = "";     switch (number.ToString().Length)     {         case 3:             ans += string.Format("{0} hundred and ", numbers[number / 100]);         case 2:             int t = (number / 10) % 10;             if (t == 1)             {                 ans += teens[number % 10];                 break;             }             else if (t &gt; 1)                 ans += string.Format("{0}-", tens[t]);         case 1:             int o = number % 10;             ans += numbers[o];              break;         default:             throw new ArgumentException("number");     }     return ans; }   The smart people are cringing because the string[]s should be declared outside the function: well, they are, this is just an example.  The compiler fails with the following error:   Control cannot fall through from one case label ('case 3:') to another Control cannot fall through from one case label ('case 2:') to another   Why? And is there any way to get this sort of behaviour without having three ifs?
87449
I have a python app and java app. The python app generates input for the java app and invokes it on the command line.  I'm sure there must be a more elegant solution to this; just like using JNI to invoke C code from Java.  Any pointers? (FYI I'm v. new to Python)    Clarification (at the cost of a long question: apologies) The py app (which I don't own) takes user input in the form of a number of configuration files. It then interprits these and farms work off to a number of (hidden) tools via a plugin mechanism. I'm looking to add support for the functionality provided by the legacy Java app.  So it doesn't make sense to call the python app from the java app and I can't run the py app in a jython environment (on the JVM).  Since there is no obvious mechanism for this I think the simple CL invocation is the best solution.
3732
For example:  javac Foo.java Note: Foo.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.
24951
I wrote a function in C that converts a string to an integer and returns the integer. When I call the function I also want it to let me know if the string is not a valid number. In the past I returned -1 when this error occurred, because I didn't need to convert strings to negative numbers. But now I want it to convert strings to negative numbers, so what is the best way to report the error?  In case I wasn't clear about this: I don't want this function to report the error to the user, I want it to report the error to the code that called the function. ("Report" might be the wrong word to use...)  Here's the code:  s32 intval(const char *string) {     bool negative = false;     u32 current_char = 0;      if (string[0] == '-') {         negative = true;         current_char = 1;     }      s32 num = 0;     while (string[current_char]) {         if (string[current_char] &lt; '0' || string[current_char] &gt; '9') {             // Return an error here.. but how?         }          num *= 10;         num += string[current_char] - '0';         current_char++;     }      if (negative) {         num = -num;     }      return num; }
59699
Here is the code.  \documentclass{article} \begin{document} \directlua{tex.sprint(tostring(math.sin(math.pi)))} \\ \directlua{tex.sprint(tostring(math.tan(math.pi/2)))} \end{document}   I am expecting the answers as 0 and error . The code above gives some very small and big number. Can I get the expected answers by some modifications in code?
62033
I have a question about comparing a string with the empty string in Java. Is there a difference, if I compare a string with the empty string with == or equals? For example:  String s1 = "hi";  if (s1 == "")   or   if (s1.equals(""))    I know that one should compare strings (and objects in general) with equals, and not ==, but I am wondering whether it matters for the empty string.
5289
I have a rather big number of source files that I need parse and extract all string literals and put them in a file as play old java constant. For exemple:  Label l = new Label("Cat");   Would become:  Label l = new Label(Constants.CAT);   And in Constants.java I would have:  public final static String CAT = "Cat";   I do not want the strings to be externalized in a property text file. One reason is for consistency and code readability. The other is that our client code uses GWT, which does not support Java property text file mechanism.  I could write some sort of parser (using ant replace task maybe)? But I wondered if an IDE already does this sort of thing automatically.
36484
I'm trying to implement a KeyListener for my JFrame. On the constructor, I'm using this code:  System.out.println("test"); addKeyListener(new KeyListener() {     public void keyPressed(KeyEvent e) { System.out.println( "tester"); }      public void keyReleased(KeyEvent e) { System.out.println("2test2"); }      public void keyTyped(KeyEvent e) { System.out.println("3test3"); } });   When I run it, the test message comes up in my console. However, when I press a key, I don't get any of the other messages, as if the KeyListener was not even there.  I was thinking that it could be because the focus is not on the JFrame and so they KeyListener doesn't receive any events.  But, I'm pretty sure it is.  Is there something that I am missing?
119341
I'm pretty new to programming and made a few programs so far. I recently made a Calculator program and I hope you guys could tell me what I could do to improve. int firstNumber; string sign; int secondNumber; int answer;  Console.WriteLine(&quot;Input Number:&quot;); firstNumber = Convert.ToInt32(Console.ReadLine()); Console.Clear();  Console.WriteLine(&quot;Input Sign:&quot;); sign = Console.ReadLine(); Console.Clear();  Console.WriteLine(&quot;Input Second Number:&quot;); secondNumber = Convert.ToInt32(Console.ReadLine()); Console.Clear();  switch (sign) {     case &quot;+&quot;:         answer = firstNumber + secondNumber;         Console.WriteLine(answer);         Console.ReadKey();     break;     case &quot;-&quot;:         answer = firstNumber - secondNumber;         Console.WriteLine(answer);         Console.ReadKey();     break;     case &quot;*&quot;:         answer = firstNumber * secondNumber;         Console.WriteLine(answer);         Console.ReadKey();     break;     case &quot;/&quot;:         answer = firstNumber / secondNumber;         Console.WriteLine(answer);         Console.ReadKey();     break;     default:         Console.WriteLine(&quot;Invalid Input&quot;);     break; }
1992
While working in a Java app, I recently needed to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be in advance. The best I could come up with off the top of my head was something like this:  public String appendWithDelimiter( String original, String addition, String delimiter ) {     if ( original.equals( "" ) ) {         return addition;     } else {         return original + delimiter + addition;     } }  String parameterString = ""; if ( condition ) parameterString = appendWithDelimiter( parameterString, "elementName", "," ); if ( anotherCondition ) parameterString = appendWithDelimiter( parameterString, "anotherElementName", "," );   I realize this isn't particularly efficient, since there are strings being created all over the place, but I was going for clarity more than optimization.  In Ruby, I can do something like this instead, which feels much more elegant:  parameterArray = []; parameterArray &lt;&lt; "elementName" if condition; parameterArray &lt;&lt; "anotherElementName" if anotherCondition; parameterString = parameterArray.join(",");   But since Java lacks a join command, I couldn't figure out anything equivalent.  So, what's the best way to do this in Java?