I'm trying to make a program that can read whatever the user inputs and checks their input using if..else statement.  import java.util.Scanner;  class Answers{          public void FalseAnim() {             System.out.println("Game Over your answer is wrong. try again!");         }          public void CorrectAnim() {             System.out.println("your answer is correct");         } }  public class quizgame {     public static void main (String[] args) {         Scanner input = new Scanner(System.in);         Answers ans = new Answers();         String strans1;         System.out.println("welcome to the quiz game!");         System.out.println("what is 1+1");         strans1 = input.nextLine();         if (strans1=="two"||strans1=="2") {             ans.CorrectAnim();         }         else {             ans.FalseAnim();         }      } }   every time I run the program and input anything it goes straight into the else statement, even when I input either a "2" or a "two"
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?
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.
92088
public class WrapperTest {      public static void main(String[] args) {          Integer i = 100;         Integer j = 100;          if(i == j)             System.out.println("same");         else             System.out.println("not same");     }     }   The above code gives the output of same when run, however if we change the value of i and j to 1000 the output changes to not same. As I'm preparing for SCJP, need to get the concept behind this clear. Can someone explain this behavior.Thanks.
2156
In Java is there a way to check the condition:  "Does this single character appear at all in string x"  without using a loop?
13663
Assume you have some objects which have several fields they can be compared by:  public class Person {      private String firstName;     private String lastName;     private String age;      /* Constructors */      /* Methods */  }   So in this example, when you ask if:  a.compareTo(b) &gt; 0   you might be asking if a's last name comes before b's, or if a is older than b, etc...  What is the cleanest way to enable multiple comparison between these kinds of objects without adding unnecessary clutter or overhead?   java.lang.Comparable interface allows comparison by one field only Adding numerous compare methods (i.e. compareByFirstName(), compareByAge(), etc...) is cluttered in my opinion.   So what is the best way to go about this?
7905
What is the difference between == and ===?  How exactly does the loosely == comparison work? How exactly does the strict === comparison work?  What would be some useful examples?
40938
After I posted this question, I found a similar post that seemed to answer it: . I'll leave this in place for now, as I am not sure how to mark my own question as a duplicate  In attempting to debug a SOQL query error, I encountered a strange behavior with Database.query and bind variables. Specifically, when I run this code:  String userQuery = 'SELECT Id FROM User'; if (true) {     List&lt;String&gt; firstNames = new List&lt;String&gt;{'James','Joe'};     userQuery += ' WHERE FirstName IN :firstNames'; } Database.query(userQuery);   the Database.query statement executes with no errors, despite the fact that the variable firstNames does not exist in its context. However, when I add an else clause:  String userQuery = 'SELECT Id FROM User'; if (true) {     List&lt;String&gt; firstNames = new List&lt;String&gt;{'James','Joe'};     userQuery += ' WHERE FirstName IN :firstNames'; } else {     List&lt;String&gt; firstNames; } Database.query(userQuery);   I receive a null object reference exception. It seems like Salesforce is checking to see if the variable is only declared once beforehand and, if so, uses its value in the context it was declared. This seems strange to me, so I was wondering if anybody here has any insight into what is going on under the hood.
73868
I need help. I am currently trying to test this code before uploading  public class CoreValuesExt { ApexPages.StandardController sc; public boolean readonly {get; set;} public Core_Values__c cv {get; set;} public integer countEdit = 1; public string buttonValue {get; set;} public integer recordScan;  public CoreValuesExt(ApexPages.StandardController sc) {     this.sc = sc;     cv = new Core_Values__c();     cv.Account__c = sc.getid();      readonly = true;     buttonValue = 'Edit';     recordScan = [SELECT COUNT() FROM Core_Values__c WHERE Account__c = :cv.Account__c];    if (recordScan != 0){    cv = [SELECT id, HSE__c, Professionalism_Integrity__c, Quality_Accuracy__c, Technology_Innovation__c, Timeliness__c, Value_for_money__c FROM Core_Values__c WHERE Account__c = :cv.Account__c];     }  }  public ApexPages.PageReference Save() {     return sc.Save(); }  public void ApplyAction() {     countEdit++;     Integer modolus = Math.mod(countEdit, 2);     String total = cv.HSE__c + cv.Professionalism_Integrity__c + cv.Quality_Accuracy__c + cv.Technology_Innovation__c + cv.Value_for_Money__c + cv.Timeliness__c;     if(modolus == 0)     {         readonly = false;         buttonValue = 'Save';     }     else     {         if(total != 'nullnullnullnullnullnull')            {         if (recordScan == 0){         insert cv;         readonly = true;         buttonValue = 'Edit';         }         else         {         update cv;         readonly = true;         buttonValue = 'Edit';         }         }     }    }   }  With this trigger.  trigger CoreValuesTrigger on Core_Values__c (before insert) {  Core_Values__c cvs = Trigger.new; CoreValuesExt.ApplyAction(cvs);  }   But when I try to save, I get a message saying:      Illegal assignment from List to   CoreValuesExt__Core_Values__c at line 3 column 1   "  How do I go through with this? I need help. Thanks
82893
Is it true that I cannot have OR or AND operators in if statements in APEX?  I have an object that has a picklist Code__c, and I need to execute some code if the code is set to either A or B.  How would I write something like:  if(pc.Code__c = 'A' || pc.Code__c = 'A') { }   Tia.
10915
I'm pretty new to coding and I want to get an opinion on my coding. I am learning Python and I made a really simple heads and tails guessing game.  import random import time import easygui import sys while True:     rand = random.choice(["Heads", "Tails"])     firstguess = raw_input("Guess Heads or Tails: ")     if firstguess == rand:         print "Wow you win"     else:         print "That is wrong you suck so bad lol."     time.sleep(2)     answer = easygui.buttonbox("Play again?", choices=["Yes","No"])     if answer == "Yes":         easygui.msgbox("Ok")     else:         break  easygui.msgbox("Ok, see you later!") sys.exit(0)
81862
Does string immutability work by statement, or by strings within a statement?   For example, I understand that the following code will allocate two strings on the heap.  string s = "hello "; s += "world!";   "hello" will remain on the heap until garbage collected; and s now references "hello world!" on the heap. However, how many strings does the following line allocate on the heap...1 or 2? Also, is there a tool/way to verify the results?  string s = "goodbye " + "cruel world!";
80203
This error should be a simple one but I cant seem to make it work. The problem lies in the fact that this very same code works earlier in the program. I don's see any reason for it to be sending an error on this instance and not the four previous ones. Reference the code below, and feel free to provide any criticism you may have as it should make me better. If it matters, I am using Sharp Develop 2.2.  Here is an example of the code that works:  void calc2Click(object sender, EventArgs e) {     if (!String.IsNullOrEmpty(tb2_fla.Text) &amp; String.IsNullOrEmpty(tb2_e.Text) | String.IsNullOrEmpty(tb2_fla.Text) &amp; String.IsNullOrEmpty(tb2_e.Text) | String.IsNullOrEmpty(tb2_e.Text))     {         MessageBox.Show("Enter either kVA and Voltage or FLA and Voltage", "Invalid Data Entry", MessageBoxButtons.OK);     }                 if (!String.IsNullOrEmpty(tb2_kva.Text) &amp; !String.IsNullOrEmpty(tb2_e.Text))     {              decimal x, y, z;             x = decimal.Parse(tb2_kva.Text);                   y = decimal.Parse(tb2_e.Text);             z = (x * 1000) / (1.732050808m * y); //the m at the end of the decimal allows for the multiplication of decimals                 tb2_fla.Text = z.ToString();             tb2_fla.Text = Math.Round(z,2).ToString();     }         else     {         if (!String.IsNullOrEmpty(tb2_fla.Text) &amp; !String.IsNullOrEmpty(tb2_e.Text))     {              decimal x, y, z;             x = decimal.Parse(tb2_fla.Text);                   y = decimal.Parse(tb2_e.Text);             z = (x * y * 1.732050808m) / 1000; //the m at the end of the decimal allows for the multiplication of decimals               tb2_kva.Text = Math.Round(z,2).ToString();      }   Here is the example of the code that sends the error in the subject line of this post:  void Calc4Click(object sender, EventArgs e) {         if (!String.IsNullOrEmpty(tb4_fla.Text) &amp;&amp; String.IsNullOrEmpty(tb4_e.Text) || String.IsNullOrEmpty(tb4_kw.Text) &amp; String.IsNullOrEmpty(tb4_e.Text) || String.IsNullOrEmpty(tb4_e.Text))         {   //If values are entered improperly, the following message box will appear         MessageBox.Show("Enter either FLA and Voltage or kW and Voltage", "Invalid Data Entry", MessageBoxButtons.OK);         }              if (!String.IsNullOrEmpty(tb4_fla.Text)&amp;&amp; !String.IsNullOrEmpty(tb4_e.Text)&amp;&amp; String.IsNullOrEmpty(tb4_kw.Text))         {//If the user eneters FLA and Voltage calculate for kW              decimal x, y, z;             x = decimal.Parse(tb4_fla.Text);             y = decimal.Parse(tb4_e.Text);             z = (x*y)*(.8 * 1.732050808m);             tb4_kw.Text = Math.Round(z,0).ToString();          }                         if (!String.IsNullOrEmpty(tb4_kw.Text) &amp;&amp; !String.IsNullOrEmpty(tb4_e.Text) &amp;&amp; String.IsNullOrEmpty(tb4_fla.Text))         {;//If the user enters kW and Voltage calculate for FLA             decimal x, y, z;             x = decimal.Parse(tb4_kw.Text);             y = decimal.Parse(tb4_e.Text);             z = (1000 * x)/(y * 1.732050808m)* .8;             tb4_fla.Text = Math.Round(z,0).ToString();         }      }   I appreciate any help that I can get.  Thank you.
97818
I am trying to detect whether the 'a' was entered as the first string argument.
47989
Okay, we know that the following two lines are equivalent -    (0 == i) (i == 0)   Also, the first method was encouraged in the past because that would have allowed the compiler to give an error message if you accidentally used '=' instead of '=='.  My question is - in today's generation of pretty slick IDE's and intelligent compilers, do you still recommend the first method?    In particular, this question popped into my mind when I saw the following code -   if(DialogResult.OK == MessageBox.Show("Message")) ...    In my opinion, I would never recommend the above. Any second opinions?
49713
I'm trying to create an if else statement to verify that the user has entered something. If they have it should run through the commands, and if not i want to echo a help statement.
13369
I have an Object[] array, and I am trying to find the ones that are primitives. I've tried to use Class.isPrimitive(), but it seems I'm doing something wrong:  int i = 3; Object o = i;  System.out.println(o.getClass().getName() + ", " +                    o.getClass().isPrimitive());   prints java.lang.Integer, false.  Is there a right way or some alternative?
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?