I have this code:  int[][] stuGrades = {{97, 64, 75, 100, 21}}; //extract from data file  String[][] HWdata; // original data file for (int g = 0; g &lt; stuGrades.length; g++) {     for (int p = 0; p &lt; stuGrades[0].length; p++) {         int tempScores = stuGrades[g][p];         if (tempScores &lt;= 100 &amp;&amp; tempScores &gt; 98.1) {             stuGpa[g][p] = 4.0;         }         else if (tempScores &lt;= 98 &amp;&amp; tempScores &gt; 96.1) {             stuGpa[g][p] = 3.9;         }     } }   My goal is to convert the grades array {97, 64, 75, 100, 21} to a new GPA array, which will convert the score to 4.0, 3.9 or something else. I got this error:     Exception in thread "main" java.lang.NullPointerException at homework7.main.    How can I resolve this issue?
129
What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them?  What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
102402
I'm wanting to parse a string into a nullable int in C#.  ie. I want to get back either the int value of the string or null if it can't be parsed.  I was kind of hoping that this would work  int? val = stringVal as int?;   But that won't work, so the way I'm doing it now is I've written this extension method  public static int? ParseNullableInt(this string value) {     if (value == null || value.Trim() == string.Empty)     {         return null;     }     else     {         try         {             return int.Parse(value);         }         catch         {             return null;         }     } }      Is there a better way of doing this?  EDIT:  Thanks for the TryParse suggestions, I did know about that, but it worked out about the same.  I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int?
26439
Is there any performance difference between the for loops on a primitive array?   Assume:  double[] doubleArray = new double[300000];   for (double var: doubleArray)     someComplexCalculation(var);   or :  for ( int i = 0, y = doubleArray.length; i &lt; y; i++)    someComplexCalculation(doubleArray[i]);   Test result  I actually profiled it:  Total timeused for modern loop= 13269ms Total timeused for old loop   = 15370ms   So the modern loop actually runs faster, at least on my Mac OSX JVM 1.5.
90240
I have the below code:  public class CallOutForGet {      HttpRequest request=new Httprequest(); http http=new http(); request.setEndPoint('https://th-apex-http-callout.herokuapp.com/animals'); request.setmethod('GET');  HttpResponse response=http.send(request);  if(response.getStatusCode()==200){      Map&lt;String,Object&gt; results= (Map&lt;String,Object&gt;)JSON.deserializeUntyped(response.getBody());      List&lt;object&gt; animals=(List&lt;object&gt;)results.get('animals');     System.debug('Received Animals************');     for(object anim:animals){         System.debug(anim);     } }  }   This error at line -  request.setEndPoint('https://th-apex-http-callout.herokuapp.com/animals');  says expecting right parenthesis.
110820
I'm currently making a callout to a 3rd party vendor and I'm getting a huge response. What is currently messing me up is this section:   "MessageSeq":13,"Description":"config file: config-qa1.txt\"","MessageTS":"2014-02-17T14:46:58","MessageLevel":4,"IsSystemMessage":false   As you can see here, the portion at the end of the Description value is ended with backslash double quote. If I attempt to parse this via the JSONParser I get an exception. Does anyone have an recommendations on how to resolve this?  Exception Message:  System.JSONException: Unexpected character ('"' (code 34)): was expecting comma to separate OBJECT entries at [line:1, column:3699]  Updated with sample Code   public class ResponseWrapper{     // fields from JSON to auto map     public Integer messageSeq;     public String Description;     public String messageTS;     public Integer messageLevel;     public Boolean isSystemMessage;     // parsing fields     private ResponseWrapper theResponse;     private JSONParser parser;      public void parse(String jsonString){         parser = JSON.createParser(jsonString);         parseJSON();     }      private void parseJSON(){            while (parser.nextToken() != null) {             if (parser.getCurrentToken() == JSONToken.START_OBJECT) {                 theResponse = (ResponseWrapper)parser.readValueAs(ResponseWrapper.class);                            }         }     } }  String responseString = '{"MessageSeq":13,"Description":"config file: config-qa1.txt\"","MessageTS":"2014-02-17T14:46:58","MessageLevel":4,"IsSystemMessage":false}'; system.debug('\n\nBEFORE\n' + responseString); ****Place code in here to test such as ReplaceALL*** ResponseWrapper parser = new ResponseWrapper(); parser.parse(responseString);
116653
I have this:  If String.IsNullOrEmpty(editTransactionRow.pay_id.ToString()) = False Then     stTransactionPaymentID = editTransactionRow.pay_id 'Check for null value End If   Now, when editTransactionRow.pay_id is Null Visual Basic throws an exception. Is there something wrong with this code?
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
67149
I'm trying to create an array of arrays that will be using repeated data, something like below:  int[] list1 = new int[4] { 1, 2, 3, 4 }; int[] list2 = new int[4] { 5, 6, 7, 8 }; int[] list3 = new int[4] { 1, 3, 2, 1 }; int[] list4 = new int[4] { 5, 4, 3, 2 };  int[,] lists = new int[4, 4] {  list1 ,  list2 ,  list3 ,  list4  };   I can't get it to work and so I'm wondering if I'm approaching this wrong.   What I'm attempting to do is create some sort of method to create a long list of the values so I can process them in a specific order, repeatedly. Something like,  int[,] lists = new int[90,4] { list1, list1, list3, list1, list2, (and so on)};  for (int i = 0; i &lt; 90; ++i) {    doStuff(lists[i]); }   and have the arrays passed to doStuff() in order. Am I going about this entirely wrong, or am I missing something for creating the array of arrays?
81401
I have an array of doubles and I want the index of the highest value. These are the solutions that I've come up with so far but I think that there must be a more elegant solution. Ideas?  double[] score = new double[] { 12.2, 13.3, 5, 17.2, 2.2, 4.5 }; int topScoreIndex = score.Select((item, indx) =&gt; new {Item = item, Index = indx}).OrderByDescending(x =&gt; x.Item).Select(x =&gt; x.Index).First();  topScoreIndex = score.Select((item, indx) =&gt; new {Item = item, Index = indx}).OrderBy(x =&gt; x.Item).Select(x =&gt; x.Index).Last();  double maxVal = score.Max(); topScoreIndex = score.Select((item, indx) =&gt; new {Item = item, Index = indx}).Where(x =&gt; x.Item == maxVal).Select(x =&gt; x.Index).Single();
40009
I have the following code that shows either a bug or a misunderstanding on my part.  I sent the same list, but modified over an ObjectOutputStream.  Once as [0] and other as [1].  But when I read it, I get [0] twice.  I think this is caused by the fact that I am sending over the same object and ObjectOutputStream must be caching them somehow.  Is this work as it should, or should I file a bug?   import java.io.*; import java.net.*; import java.util.*;  public class OOS {      public static void main(String[] args) throws Exception {         Thread t1 = new Thread(new Runnable() {             public void run() {                 try {                     ServerSocket ss = new ServerSocket(12344);                     Socket s= ss.accept();                      ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());                     List same = new ArrayList();                     same.add(0);                     oos.writeObject(same);                     same.clear();                     same.add(1);                     oos.writeObject(same);                  } catch(Exception e) {                     e.printStackTrace();                 }             }         });         t1.start();          Socket s = new Socket("localhost", 12344);         ObjectInputStream ois = new ObjectInputStream(s.getInputStream());          // outputs [0] as expected         System.out.println(ois.readObject());          // outputs [0], but expected [1]         System.out.println(ois.readObject());         System.exit(0);     } }
24747
I've got a large array of primitive types (double). How do I sort the elements in descending order?  Unfortunately the Java API doesn't support sorting of primitive types with a Comparator.  The first approach that probably comes to mind is to convert it to a list of objects (boxing):  double[] array = new double[1048576];     Arrays.stream(array).boxed().sorted(Collections.reverseOrder())…   However, boxing each primitive in the array is too slow and causes a lot of GC pressure!  Another approach would be to sort and then reverse:  double[] array = new double[1048576]; ... Arrays.sort(array); // reverse the array for (int i = 0; i &lt; array.length / 2; i++) {      // swap the elements      double temp = array[i];      array[i] = array[array.length - (i + 1)];      array[array.length - (i + 1)] = temp; }   This approach is also slow - particularly if the array is already sorted quite well.  What's a better alternative?
103112
When and why would somebody do the following:  doSomething( (MyClass) null );   Have you ever done this? Could you please share your experience?
95092
Why does list.index throw an exception, instead of using an arbitrary value (for example, -1)? What's the idea behind this?  To me it looks cleaner to deal with special values, rather than exceptions.  EDIT: I didn't realize -1 is a potentially valid value. Nevertheless, why not something else? How about a value of None?
22625
MyClass[] array; List&lt;MyClass&gt; list;   What are the scenarios when one is preferable over the other? And why?
107003
I'm working on a sparse matrix class that needs to use an array of LinkedList to store the values of a matrix. Each element of the array (i.e. each LinkedList) represents a row of the matrix. And, each element in the LinkedList array represents a column and the stored value.  In my class, I have a declaration of the array as:  private LinkedList&lt;IntegerNode&gt;[] myMatrix;   And, in my constructor for the SparseMatrix, I try to define:  myMatrix = new LinkedList&lt;IntegerNode&gt;[numRows];   The error I end up getting is     Cannot create a generic array of LinkedList&lt;IntegerNode&gt;.   So, I have two issues with this:   What am I doing wrong, and Why is the type acceptable in the declaration for the array if it can't be created?   IntegerNode is a class that I have created. And, all of my class files are packaged together.
24043
I'm trying to work with  in Java.   I want to implement arithmetic functions.  For this, I will first require a way to normalize the functions.  I know I can't add 1/6 and 1/2 until I have a common denominator. I will have to add 1/6 and 3/6.  A naive approach would have me add 2/12 and 6/12 and then reduce.  How can I achieve a common denominator with the least performance penalty?  What algorithm is best for this?    Version 8 (thanks to ):     Improvements include:         the equals() method is now consistent with the compareTo() method      final class Fraction extends Number {     private int numerator;     private int denominator;      public Fraction(int numerator, int denominator) {         if(denominator == 0) {             throw new IllegalArgumentException("denominator is zero");         }         if(denominator &lt; 0) {             numerator *= -1;             denominator *= -1;         }         this.numerator = numerator;         this.denominator = denominator;     }      public Fraction(int numerator) {         this.numerator = numerator;         this.denominator = 1;     }      public int getNumerator() {         return this.numerator;     }      public int getDenominator() {         return this.denominator;     }      public byte byteValue() {         return (byte) this.doubleValue();     }      public double doubleValue() {         return ((double) numerator)/((double) denominator);     }      public float floatValue() {         return (float) this.doubleValue();     }      public int intValue() {         return (int) this.doubleValue();     }      public long longValue() {         return (long) this.doubleValue();     }      public short shortValue() {         return (short) this.doubleValue();     }      public boolean equals(Fraction frac) {         return this.compareTo(frac) == 0;     }      public int compareTo(Fraction frac) {         long t = this.getNumerator() * frac.getDenominator();         long f = frac.getNumerator() * this.getDenominator();         int result = 0;         if(t&gt;f) {             result = 1;         }         else if(f&gt;t) {             result = -1;         }         return result;     } }     I have removed all previous versions.  My thanks to:
71247
List&lt;String&gt; nameList = new List&lt;String&gt;(); DropDownList ddl = new DropDownList();   List is populated here, then sorted:  nameList.Sort();   Now I need to drop it into the dropdownlist, which is where I'm having issues (using foreach):  foreach (string name in nameList){     ddl.Items.Add(new ListItem(nameList[name].ToString())); }   No workie - any suggestions? It's giving me compile errors:  Error - The best overloaded method match for 'System.Collections.Generic.List&lt;string&gt;.this[int]' has some invalid arguments   Error - Argument '1': cannot convert from 'string' to 'int'