I am trying to check for integers, &quot;&quot; and &quot; &quot; when a user inputs a string. Every thing is working as expected but when I pass an empty field it validates and prints invalid input. Apart from that it also prints the println statement from the catch. Below is my code and actual output. package com.assessment;  import java.util.Scanner;  public class MaxCharString {      public static void main(String[] args) {         int i, j, count = 0, maxcount = 0;         System.out.println(&quot;Enter a string to find the maximum character.&quot;);         Scanner input = new Scanner(System.in);         String character = input.nextLine().toLowerCase();         try {             if (character == &quot;&quot;) {                 System.out.println(&quot;Invalid Input&quot;);             }             int inputCharacter = Integer.parseInt(character);             System.out.println(inputCharacter + &quot; is not a valid Input. Please try again.&quot;);         } catch (NumberFormatException e) {             char result = 0;             char ch[] = character.toCharArray();             for (i = 0; i &lt; ch.length; i++) {                 count = 0;                 for (j = 0; j &lt; ch.length; j++) {                     if (ch[i] == ch[j]) {                         count++;                     }                     if (maxcount &lt; count) {                         maxcount = count;                         result = ch[i];                     }                 }             }             System.out.println(&quot;Maximum count of occuring character in the string is: &quot; + result);             input.close();         }     } }  Output: Invalid Input Maximum count of occuring character in the string is:    Could anyone please help me out with this problem. Thank you.
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?
57093
I think there's a lot for me to learn about data types. Why this happens  double result = ((3/8)*100).ToString();   it gives zero .. should be 37,5 ... :(
46072
JSON(I am working with): JSONLinter confirms this is a valid JSON.  {     "errors": [         {             "params": {                 "password": "size must be between 4 and 30",                 "loginId": "must match \"^[a-zA-Z0-9_]*$\""             }         }     ] }   Attempt 1(Using JSONParser:  String str = '{ "errors": [ { "params": { "password": "size must be between 4 and 30", "loginId": "must match \"^[a-zA-Z0-9_]*$\"" } } ] }'; JSONParser parser = JSON.createParser(str); while(parser.nextToken() != null){     parser.nextToken(); }   Fails:      ▸    ERROR: System.JSONException: Unexpected character ('^' (code   94)): was  ▸    expecting comma to separate OBJECT entries at input   location [1,99]  ▸    ERROR: Class.System.JSONParser.nextToken: line   94, column 1  ▸    AnonymousBlock: line 3, column 1  ▸   AnonymousBlock: line 3, column 1   Attempt 2(JSON2Apex option):  public class JSON2Apex {      public class Errors {             public Params params;     }      public List&lt;Errors&gt; errors;      public class Params {             public String password;             public String loginId;     }  }  String str = '{ "errors": [ { "params": { "password": "size must be between 4 and 30", "loginId": "must match \"^[a-zA-Z0-9_]*$\"" } } ] }'; JSON2Apex obj = (JSON2Apex)JSON.deserialize(str, JSON2Apex.class);   Fails:     ▸    ERROR: System.JSONException: Unexpected character ('^' (code   94)): was  ▸    expecting comma to separate OBJECT entries at [line:1,   column:99]  ▸    ERROR: Class.System.JSON.deserialize: line 15, column   1  ▸    AnonymousBlock: line 2, column 1  ▸    AnonymousBlock: line 2,   column 1   Attempt 3(deserializeUntyped):  String str = '{ "errors": [ { "params": { "password": "size must be between 4 and 30", "loginId": "must match \"^[a-zA-Z0-9_]*$\"" } } ] }'; Map&lt;String,Object&gt; jsonObj = (Map&lt;String,Object&gt;)JSON.deserializeUntyped(str);   Fails:     ▸    ERROR: System.JSONException: Unexpected character ('^' (code   94)): was  ▸    expecting comma to separate OBJECT entries at [line:1,   column:99]  ▸    ERROR: Class.System.JSON.deserializeUntyped: line 11,   column 1  ▸    AnonymousBlock: line 2, column 1  ▸    AnonymousBlock:   line 2, column 1   Attempt 4(replace the problem causing double quote in JSON):  String str = '{ "errors": [ { "params": { "password": "size must be between 4 and 30", "loginId": "must match \"^[a-zA-Z0-9_]*$\"" } } ] }'; Map&lt;String,Object&gt; jsonObj = (Map&lt;String,Object&gt;)JSON.deserializeUntyped(str.replaceAll('\"', '\\"'));   Still fails:     ▸    ERROR: System.JSONException: Unexpected character ('^' (code   94)): was  ▸    expecting comma to separate OBJECT entries at [line:1,   column:99]  ▸    ERROR: Class.System.JSON.deserializeUntyped: line 11,   column 1  ▸    AnonymousBlock: line 2, column 1  ▸    AnonymousBlock:   line 2, column 1   I have looked into the below similar questions but still don't see any solution:
104592
I am running some script which passing the string argument and I want to do if else statement shown as below:  if [ $1 != '' ] &amp;&amp; [ $2 != '' ] then      do something.....   but it shown Error too many argument. Why?
113159
I'm not sure why I'm getting this error, but shouldn't this code compile, since I'm already checking to see if queue is getting initialized?   public static void Main(String[] args) {     Byte maxSize;     Queue queue;      if(args.Length != 0)     {         if(Byte.TryParse(args[0], out maxSize))             queue = new Queue(){MaxSize = maxSize};         else             Environment.Exit(0);     }     else     {         Environment.Exit(0);     }      for(Byte j = 0; j &lt; queue.MaxSize; j++)         queue.Insert(j);     for(Byte j = 0; j &lt; queue.MaxSize; j++)         Console.WriteLine(queue.Remove()); }   So if queue is not initialized, then the for loops aren't reachable right? Since the program already terminates with Environment.Exit(0)?  Hope ya'll can give me some pointers :)  Thanks.
107801
I posted the code below to the Sun developers forum since I thought it was erroring (the true error was before this code was even hit).  One of the responses I got said it would not work and to throw it away.  But it is actually working.  It might not be the best code (I am new to Java) but is there something inherently "wrong" with it?   =============  CODE:   private static void ImportFromCsvToAccessTable(String mdbFilePath, String accessTableName  , String csvDirPath , String csvFileName ) throws ClassNotFoundException, SQLException {      Connection msConn = getDestinationConnection(mdbFilePath);     try{          String strSQL = "SELECT * INTO " + accessTableName + " FROM [Text;HDR=YES;DATABASE=" + csvDirPath + ";].[" + csvFileName + "]";         PreparedStatement selectPrepSt = msConn.prepareStatement(strSQL );         boolean result = selectPrepSt.execute();                 System.out.println( "result = " + result );      } catch(Exception e) {         System.out.println(e);     } finally {         msConn.close();     } }
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?
35663
My controller code is as follows -          for(String resStr : responseArray){             if(resStr.indexOf('r_error_str') != -1){                 responseString += resStr.substring(resStr.indexOf('=') + 1);                  responseString += '\n';             }         }   but when i display this 'responseString ' String using 'apex:outputLabel or apex:outputText or as Exception message '\n' is not converting in new line. Whole String is coming in one line.  Can anyone explain why is this happining
105631
Please consider the below scenario:   I have an Application__c object. I have a trigger on that (for simplicity, coded directly in trigger) which does one thing if the record name is Error then throws exception.     trigger ApplicationTrigger on Application__c (before insert, after update){          if(trigger.new[0].Name == 'Error'){             Application__c application;             System.debug(application.Name);         } }    Now I am running below code:     Now notice the catch statement is not executing, means system was not able to catch the exception. It came as the Fatal Error.   This is kind of a big issue where if there is null pointer or any other exception in trigger and exception handling code will not be able to do anything. Not even logging since it never reaches to catch block.   Let me know if you guys ever faced such situation and if yes what you did to make sure that it is properly caught.
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.
10611
I've been having a debate (mostly with myself) over the best approach to deal with invalid input in text fields -- validation versus prevention.    Taking a  numeric text field as an example, is it better to prevent the entry of non-numeric characters (allowing for special cases like sign, decimal pt., etc.) or allow the entry of whatever and then indicate an error message (typically when focus is left) if the result is invalid?    The first approach is "don't allow the user to do something you know is wrong" but has the disadvantage that it may not be at all obvious what is going on if a keyboard key is typed and nothing happens.  It also breaks the expectation that, if you type something in a text field, you expect to see what you typed.    In the past, I've generally leaned towards the prevention approach but in general but feel perhaps, at the field input-level, the validation approach provides a better user experience.  Is anyone aware of a best practice here?
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+$"); }
81943
How does one parse an integer to string(char* || char[]) in C? Is there an equivalent to the Integer.parseInt(String) method from Java in C?
76187
How can I test whether a command's output is an empty string while not   interfering with buffering?  Example:  command | ??? if [ $? = 0 ] &amp;&amp; [ -n "$output_from_command"]; then    ...   I want the output from the code above to be the same as when running command.
119736
I have a try...except block in my code and When an exception is throw. I really just want to continue with the code because in that case, everything is still able to run just fine. The problem is if you leave the except: block empty or with a #do nothing, it gives you a syntax error. I can't use continue because its not in a loop. Is there a keyword i can use that tells the code to just keep going?
119860
A weird bug was occurring in production which I was asked to look into. The issue was tracked down to a couple of variables being declared within a For loop and not being initialized on each iteration. An assumption had been made that due to the scope of their declaration they would be &quot;reset&quot; on each iteration. Could someone explain why they would not be)? (My first question, really looking forward to the responses.) The example below is obviously not the code in question but reflects the scenario:  Please excuse the code example, it looks fine in the editor preview?? for (int i =0; i&lt; 10; i++) {     decimal? testDecimal;     string testString;      switch( i % 2  )     {         case 0:         testDecimal = i / ( decimal ).32;         testString = i.ToString();             break;         default:             testDecimal = null;             testString = null;             break;     }      Console.WriteLine( &quot;Loop {0}: testDecimal={1} - testString={2}&quot;, i, testDecimal , testString ); }   EDIT: Sorry, had to rush out for child care issue. The issue was that the prod code had was that the switch statement was huge and in some &quot;case&quot;'s a check on a class' property was being made, like if (myObject.Prop != null) then testString = myObject.Stringval... At the end of the switch, (outside) a check on testString == null was being made but it was holding the value from the last iteration,hence not being null as the coder assumed with the variable being declared within the loop. Sorry if my question and example was a bit off, I got the phone call about the day care as I was banging it together. I should have mentioned I compared IL from both variables in and out the loop. So, is the common opinion that &quot;obviously the variables would not be reinitialized on each loop&quot;? A little more info, the variables WHERE being initialized on each iteration until someone got over enthusiastic with ReSharper pointing out &quot;the value is never used&quot; and removed them.  EDIT: Folks, I thank you all. As my first post I see how much clearer I should be in the future. The cause of our unexpected variable assignment can me placed on an inexperienced developer doing everything ReSharper told him and not running any unit tests after he ran a &quot;Code Cleanup&quot; on an entire solution. Looking at the history of this module in VSS I see variables Where declared outside of the loop and where initialized on each iteration. The person in question wanted his ReSharper to show &quot;all green&quot; so &quot;moved his variables closer to assignment&quot; then &quot;Removed redundant assignment&quot;! I don't think he will be doing it again...now to spend the weekend running all the unit tests he missed! How to do mark a question as answered?
10097
Does Java have a built-in way to escape arbitrary text so that it can be included in a regular expression? For example, if my users enter "$5", I'd like to match that exactly rather than a "5" after the end of input.