For a mini game in where the user tries to guess a name. But when I want to compare two text strings just to check if are the same it seems that doesn't work.       final String miName = "Jhon";     Scanner input = new Scanner(System.in);     System.out.println("Guess my name: ");      while (true) {      String attempt = input.next();      if(attempt == miName) {        System.out.println("Congrats!");        break;      } else {        System.out.println("Try it again!");      }     }   The output:  Guess my name::  Karl Try it again! jhon Try it again! Jhon Try it again!
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?
103564
I have the below If statements using some hard coded strings and I want to make them use as custom labels. I have created custom labels with the same String names as given below. So how can I make these statements to use the Custom Labels I created ?  if(monitoringFrequency == 'daily'){             return dateValue.addDays(1);         }else if(monitoringFrequency == 'weekly'){             return dateValue.addDays(7);         }else if(monitoringFrequency == 'monthly'){             return dateValue.addMonths(1);
24489
#include &lt;stdio.h&gt; #include &lt;conio.h&gt; main() {     char ch,name[20];     int i=0;     clrscr();     printf("Enter a string:");     while((ch=getch())!='\n')     {         name[i]=ch;         i++;     }     name[i] = '\0';     printf("%s",name); }   When I give "abc" as input and if I press enter it's not working. Can anyone let me know why the condition ch=getch() != '\n' is not becoming false when I press enter? I have also observed that ch is taking \r instead of \n. Kindly let me know. Thanks
1138
Is there a way to make the following return true?  string title = "ASTRINGTOTEST"; title.Contains("string");   There doesn't seem to be an overload that allows me to set the case sensitivity.. Currently I UPPERCASE them both, but that's just silly (by which I am referring to the  issues that come with up- and down casing).  UPDATE This question is ancient and since then I have realized I asked for a simple answer for a really vast and difficult topic if you care to investigate it fully. For most cases, in mono-lingual, English code bases  answer will suffice. I'm suspecting because most people coming here fall in this category this is the most popular answer.  answer however brings up the inherent problem that we can't compare text case insensitive until we know both texts are the same culture and we know  what that culture is. This is maybe a less popular answer, but I think it is more correct and that's why I marked it as such.
11000
What is the difference between Parse() and TryParse()?  int number = int.Parse(textBoxNumber.Text);  // The Try-Parse Method int.TryParse(textBoxNumber.Text, out number);   Is there some form of error-checking like a Try-Catch Block?
92333
if ('text'.equals(str))   or   if ('text' == str)   Is there any difference? If yes, then what is it?   Added, after answered.  String q = 'teXt'; system.debug('teXt'.equals(q)); // true system.debug('teXt' == q);      // true system.debug('text'.equals(q)); // false system.debug('text' == q);      // true
40567
I'm working on a project where i find i'm checking for the following in many, many places:  if(item.Rate == 0 || item.Rate == null) { }   more as a curiousity than anything, what's the best way to check for both cases?  I've added a helper method which is:  public static bool nz(object obj) {     var parsedInt = 0;     var parsed = int.TryParse(obj.ToString(), out parsedInt);     return IsNull(obj) || (parsed &amp;&amp; parsedInt == 0); }   Is there a better way?
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?
41503
Is there a difference between single and double quotes in Java?
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.
3154
I have a string User name (sales) and I want to extract the text between the brackets, how would I do this?   I suspect sub-string but I can't work out how to read until the closing bracket, the length of text will vary.
43236
I'm attempting to loop through an array of strings, and do something a little different with one of the values.  The string comparison fails on every element.  arr[0]='red' arr[1]='blue' arr[2]='yellow' arr[3]='green'  ## now loop through the above array for i in "${arr[@]}" do         if [ "$i"="green" ];         then                 echo "i('$i') is equal to green"         else                 echo "i('$i') is not equal to green"         fi  done   I've also tried (with the same result):   if [ "$i"='green' ];   and   if [ $i='green' ];   and   if [ $i="green" ];   Output of each of the above:   i('red') is equal to green i('blue') is equal to green i('yellow') is equal to green i('green') is equal to green   What am I doing wrong with the comparison?
78827
My brother recently started learning C++. He told me a problem he encountered while trying to validate input in a simple program. He had a text menu where the user entered an integer choice, if they entered an invalid choice, they would be asked to enter it again (do while loop). However, if the user entered a string instead of an int, the code would break. I read various questions on stackoverflow and told him to rewrite his code along the lines of:    #include&lt;iostream&gt; using namespace std;  int main() {     int a;     do     {     cout&lt;&lt;"\nEnter a number:"     cin&gt;&gt;a;         if(cin.fail())         {             //Clear the fail state.             cin.clear();             //Ignore the rest of the wrong user input, till the end of the line.             cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(),\                                                     '\n');         }     }while(true);     return 0; }   While this worked ok, I also tried a few other ideas: 1. Using a try catch block. It didn't work. I think this is because an exception is not raised due to bad input. 2. I tried if(! cin){//Do Something} which didn't work either. I haven't yet figured this one out. 3. Thirdly, I tried inputting a fixed length string and then parsing it. I would use atoi(). Is this standards compliant and portable? Should I write my own parsing function? 4. If write a class that uses cin, but dynamically does this kind of error detection, perhaps by determining the type of the input variable at runtime, would it have too much overhead? Is it even possible?  I would like to know what is the best way to do this kind of checking, what are the best practices?  I would like to add that while I am not new to writing C++ code, I am new to writing good standards compliant code. I am trying to unlearn bad practices and learn the right ones. I would be much obliged if answerers give a detailed explanation.  EDIT: I see that litb has answered one of my previous edits. I'll post that code here for reference.  #include&lt;iostream&gt; using namespace std;  int main() {     int a;     bool inputCompletionFlag = true;     do     {     cout&lt;&lt;"\nEnter a number:"     cin&gt;&gt;a;         if(cin.fail())         {             //Clear the fail state.             cin.clear();             //Ignore the rest of the wrong user input, till the end of the line.             cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(),\                                                     '\n');         }         else         {             inputCompletionFlag = false;         }     }while(!inputCompletionFlag);     return 0; }   This code fails on input like "1asdsdf". I didn't know how to fix it but litb has posted a great answer. :)
4153
Is there some easy way to pad Strings in Java?  Seems like something that should be in some StringUtil-like API, but I can't find anything that does this.
41896
I need to compare 2 strings as equal such as these:     Lubeck == Lübeck   In JavaScript.  Why? Well, I have an auto-completion field that's going out to a Java service using Lucene, where place names are stored naturally (as Lübeck), but also indexed as normalized text,   import sun.text.Normalizer; oDoc.setNameLC = Normalizer.normalize(oLocName, Normalizer.DECOMP, 0)     .toLowerCase().replaceAll("[^\\p{ASCII}]","");   This way some-one who doesn't know to type "Mèxico" can type "mexico" and get a match which returns "Mèxico" (among a lot of other possible hits, like "Café Mèxico, Dubai, UAE").  Now the thing is I don't have the ability to change the service to do any highlighting on the server side, therefore I am highlighting on the client JavaScript side with something like:  return result.replace( input.replace(/[aeiou]/g,"."), "&lt;b&gt;$1&lt;/b&gt;");   It's a little more fancy because I am escaping special regex characters in the input. This is fine for simple one word matches at the beginning of a hit, but it really breaks down if you suddenly wish to support multi-word matches like "london cafe":  input = input.strip().toLowerCase(); //fyi prototype's strip is like trim re = new RegEx(input.replace(/[aeiou]/g,".").replace(/\s+/g,"|"),"gi"); return result.replace(re, "&lt;b&gt;$1&lt;/b&gt;");   This doesn't work for say "london ca" (was typing london cafe), because it would mark "Jack London Cabin, Dawson City, Canada" as: "Ja&lt;b&gt;ck&lt;/b&gt; &lt;b&gt;London&lt;/b&gt; &lt;b&gt;ca&lt;/b&gt;bin, Dawson &lt;b&gt;Ci&lt;/b&gt;ty, &lt;b&gt;Ca&lt;b/&gt;nada" [note the "ck" and "Ci" particularly]  Therefore I'm sort of looking for something that's not as crazy as:  input = input.strip().toLowerCase(); input = input.replace(/a/g,"[ÀàÁáÂâÃãÄäÅåÆæĀāĂăĄą]"); input = input.replace(/e/g,"[ÈèÉéÊêËëĒēĔĕĖėĘęĚě]"); // ditto for i, o, u, y, c, n, maybe also d, g, h, j, k, l, r, s, t, w, z  re = new RegEx(input.replace(/\s+/g,"|"),"gi"); return result.replace(re, "&lt;b&gt;$1&lt;/b&gt;");   Is there a compiled table I can refer to mapping a range of characters which are accented versions of an other character to that character, by which I don't mean the plain unicode chart. And if so, could I avoid using weird, possibly slow, RegEx statements?  About the bounty: Before I started a bounty there were two answers, the one pointing me to doing it in Ruby, and  that  wrote which was a completion of the basic form I'd put in my question. Now don't get me wrong, I really appreciate working it out as completely as he did, but I just wished that there might be another way.  It seems so far that everyone who's dropped by to look at the question and answer has decided that MizzardX covers it just fine, or that they have no different approach. I would be interested in a different approach, and if it simply isn't available before the bounty closes, MizzardX will win the bounty (though in a cruel twist, his edits mad it a community wiki answer, so I'm not sure if he'll get the bounty!)
55175
I'm implementing compareTo() method for a simple class such as this (to be able to use Collections.sort() and other goodies offered by the Java platform):  public class Metadata implements Comparable&lt;Metadata&gt; {     private String name;     private String value;  // Imagine basic constructor and accessors here // Irrelevant parts omitted }   I want the natural ordering for these objects to be: 1) sorted by name and 2) sorted by value if name is the same; both comparisons should be case-insensitive. For both fields null values are perfectly acceptable, so compareTo must not break in these cases.   The solution that springs to mind is along the lines of the following (I'm using "guard clauses" here while others might prefer a single return point, but that's beside the point):  // primarily by name, secondarily by value; null-safe; case-insensitive public int compareTo(Metadata other) {     if (this.name == null &amp;&amp; other.name != null){         return -1;     }     else if (this.name != null &amp;&amp; other.name == null){         return 1;     }     else if (this.name != null &amp;&amp; other.name != null) {         int result = this.name.compareToIgnoreCase(other.name);         if (result != 0){             return result;         }     }      if (this.value == null) {         return other.value == null ? 0 : -1;     }     if (other.value == null){         return 1;     }      return this.value.compareToIgnoreCase(other.value); }   This does the job, but I'm not perfectly happy with this code. Admittedly it isn't very complex, but is quite verbose and tedious.  The question is, how would you make this less verbose (while retaining the functionality)? Feel free to refer to Java standard libraries or Apache Commons if they help. Would the only option to make this (a little) simpler be to implement my own "NullSafeStringComparator", and apply it for comparing both fields?  Edits 1-3: Eddie's right; fixed the "both names are null" case above  About the accepted answer  I asked this question back in 2009, on Java 1.6 of course, and at the time  was my preferred accepted answer. I never got round to changing that until now (2017).  There are also —a 2009 Apache Commons Collections one and a 2013 Guava one, both posted by me—that I did prefer at some point in time.  I now made the clean  the accepted answer. That should definitely be preferred if on Java 8, and these days Java 8 should be available to nearly all projects.
102259
I need to search a string in the string array. I dont want to use any for looping in it  string [] arr = {"One","Two","Three"};  string theString = "One"   I need to check whether theString variable is present in arr.