I'm trying to write a code to find a simple path between (0,0) and (n,n) of a matrix and I'm using stacks to keep previously visited x's and y's but I'm getting "java.lang.NullPointerException" at line 28 when I'm trying to push a Pair to the stack. I've tried using .add from vectors but it also didn't help      import java.util.Arrays;     import java.util.Random;     import java.util.Stack;      public class MatrixPathfinder {         static class Pair {             private int x;             private int y;             public Pair(int x, int y) {                 this.x = x;                 this.y = y;             }             public int getX() {                 return x;             }             public int getY() {                 return y;             }         }         public static boolean hasPath(int[][] arr, int[][] visited, Stack&lt;String&gt; path, Stack&lt;Pair&gt; stack, int i, int j) {             int rowLength = arr.length;             int columnLength = arr[0].length;             //if it's the last element, output the path             if(i == rowLength - 1 &amp;&amp; j == columnLength - 1) {                 System.out.println(path);                 return true;             }             stack.push(new Pair(i,j));             //Go right if path available             if(i &gt;= 0 &amp;&amp; i &lt; rowLength &amp;&amp; j + 1 &gt;= 0 &amp;&amp; j + 1 &lt; columnLength &amp;&amp; arr[i][j+1] != 0 &amp;&amp; visited[i][j + 1] != 1) {                 path.push("R");                 visited[i][j + 1] = 1;                 hasPath(arr, visited, path, stack, i, j + 1);             }             //Go down if path available             else if(i + 1 &gt;= 0 &amp;&amp; i + 1 &lt; rowLength &amp;&amp; j &gt;= 0 &amp;&amp; j &lt; columnLength &amp;&amp; arr[i+1][j] != 0 &amp;&amp; visited[i + 1][j] != 1) {                 path.push("D");                 visited[i + 1][j] = 1;                 hasPath(arr, visited, path, stack, i + 1, j);             }             //if non above satisfied, go back previous point to find another direction             else {                 if(stack.size() == 0)                     return false;                 path.pop();                 i = stack.peek().getX();                 j = stack.peek().getY();                 stack.pop();                 hasPath(arr, visited, path, stack, i, j);         }         }         public static void main(String[] args) {             Stack&lt;Pair&gt; stack = null;             Stack&lt;String&gt; path = null;             Random random = new Random();             int[][] visited = new int [5][5];             int[][] arr = new int[5][5];             for (int[] row : visited) {                 Arrays.fill(row, -1);             }             for (int i = 0; i &lt; 5; i++) {                 for (int j = 0; j &lt; 5; j++) {                     arr[i][j] = random.nextInt(2);                 }             }             //making sure the starting and destination points are valid path points             arr[0][0] = 1;             arr[3][3] = 1;             visited[0][0] = 1;             if (hasPath(arr, visited,path, stack,0 ,0))                 System.out.printf("Path found");             else                 System.out.println("Path not found");         }     }
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?
16225
Why does it (apparently) make a difference whether I pass null as an argument directly, or pass an Object that I assigned the value null?  Object testVal = null; test.foo(testVal);    // dispatched to foo(Object) // test.foo(null);    // compilation problem -&gt; "The method foo(String) is ambiguous"     public void foo(String arg) { // More-specific     System.out.println("foo(String)"); }  public void foo(Object arg) { // Generic     System.out.println("foo(Object)"); }   In other words, why is the (commented-out) second call to foo(...) not dispatched to foo(Object)?  Update: I use Java 1.6. I could compile Hemal's code without problems, but mine still doesn't compile. The only difference I see is that Hemal's methods are static while mine are not. But I really don't see why this should make a difference...?  Update 2: Solved. I had another method foo(Runnable) in my class, so the dispatcher couldn't unambiguously select the single most specific method. (See my comment in Hemal's second answer.) Thanks everyone for your help.
24554
I have a lookup relationship.  If I just do the following query it works fine:  Sobject c = [select field__r.fieldchild__c from custom_obj where Id = :someId]; system.debug('c:' + c);   However with the following I get an error:  Sobject c = [select field__r.fieldchild__c from custom_obj where Id = :someId]; String c2 = (String) r.getSobject('field__r').get('fieldchild__c');   Error message:     FATAL_ERROR System.NullPointerException: Attempt to de-reference a   null object
120685
It seems to me that a lot of my debugging time is spent chasing down null-reference exceptions in complex statements. For instance:  For Each game As IHomeGame in _GamesToOpen.GetIterator()   Why, when I get a NullReferenceException, can I get the line number in the stack trace, but not the name of the object that equals null. In other words, why:  Object reference not set to an instance of an object.   instead of  _GamesToOpen is not set to an instance of an object.   or  Anonymous object returned by _GamesToOpen.GetIterator() is null.   or  game was set to null.   Is this strictly a design choice, meant to protect the anonymity of the code or is there a compelling reason in compiler design not to include this information in the debug-time exception?
37844
Is there a good reason why there is no Pair&lt;L,R&gt; in Java? What would be the equivalent of this C++ construct? I would rather avoid reimplementing my own.  It seems that 1.6 is providing something similar (AbstractMap.SimpleEntry&lt;K,V&gt;), but this looks quite convoluted.
89662
Whenever I click the icon on my desktop to get to Minecraft, the launcher loads as usual, like it should. But when I click the "Play" button, the launcher goes away, but then comes back saying this:  [17:15:14] [Client thread/INFO]: Setting user: kassidygallowway [17:15:14] [Client thread/INFO]: (Session ID is token:7b2075512917473abe32b04ffd11b2a4:ce288cc1399b4266a07c19cc48d47531) Exception in thread "Client thread" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1     at com.google.gson.Gson.fromJson(Gson.java:815)     at com.google.gson.Gson.fromJson(Gson.java:768)     at lu.b(SourceFile:151)     at lu.&lt;init&gt;(SourceFile:43)     at net.minecraft.server.MinecraftServer.&lt;init&gt;(SourceFile:155)     at bpp.&lt;init&gt;(SourceFile:41)     at avf.&lt;init&gt;(SourceFile:293)     at net.minecraft.client.main.Main.main(SourceFile:124) Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1     at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:338)     at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:79)     at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60)     at com.google.gson.Gson.fromJson(Gson.java:803)     ... 7 more   I have no idea what this means (I dont know codes or anything like that). It does this over and over again, no matter how many times I press Play.
17717
I wish to print a Stack&lt;Integer&gt; object as nicely as the Eclipse debugger does (i.e. [1,2,3...]) but printing it with out = "output:" + stack doesn't return this nice result.  Just to clarify, I'm talking about Java's built-in collection so I can't override its toString().  How can I get a nice printable version of the stack?
13711
I am trying to install a Java application on my Linux machine (Slackware).   I have received the following error, and I do not understand it.   Could you advise me how to approach the problem? Thank you.  Here is what I get: (I see that some X11 DISPLAY variable needs to be set, but what value should I give it and how?)  ~$ java -jar gate-5.0-beta1-build3048-installer.jar - ERROR -  java.awt.HeadlessException: No X11 DISPLAY variable was set, but this program performed an operation which requires it. java.awt.HeadlessException: No X11 DISPLAY variable was set, but this program performed an operation which requires it. at java.awt.GraphicsEnvironment.checkHeadless(Graphic sEnvironment.java:159) at java.awt.Window.&lt;init&gt;(Window.java:407) at java.awt.Frame.&lt;init&gt;(Frame.java:402) at net.sourceforge.mlf.metouia.borders.MetouiaDotsBuf fer.&lt;init&gt;(MetouiaDotsBuffer.java:105) at net.sourceforge.mlf.metouia.borders.MetouiaDots.&lt;i nit&gt;(MetouiaDots.java:66) at net.sourceforge.mlf.metouia.borders.MetouiaToolBar Border.&lt;init&gt;(MetouiaToolBarBorder.java:49) at net.sourceforge.mlf.metouia.MetouiaLookAndFeel.ini tComponentDefaults(MetouiaLookAndFeel.java:241) at javax.swing.plaf.basic.BasicLookAndFeel.getDefault s(BasicLookAndFeel.java:130) at javax.swing.plaf.metal.MetalLookAndFeel.getDefault s(MetalLookAndFeel.java:1591) at javax.swing.UIManager.setLookAndFeel(UIManager.jav a:537) at javax.swing.UIManager.setLookAndFeel(UIManager.jav a:581) at com.izforge.izpack.installer.GUIInstaller.loadLook AndFeel(GUIInstaller.java:373) at com.izforge.izpack.installer.GUIInstaller.&lt;init&gt;(G UIInstaller.java:116) at sun.reflect.NativeConstructorAccessorImpl.newInsta nce0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInsta nce(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newI nstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Construc tor.java:513) at java.lang.Class.newInstance0(Class.java:355) at java.lang.Class.newInstance(Class.java:30 at com.izforge.izpack.installer.Installer.main(Instal ler.java:62)
89434
I am calling, through reflection, a method which may cause an exception. How can I pass the exception to my caller without the wrapper reflection puts around it? I am rethrowing the InnerException, but this destroys the stack trace. Example code:  public void test1() {     // Throw an exception for testing purposes     throw new ArgumentException("test1"); }  void test2() {     try     {         MethodInfo mi = typeof(Program).GetMethod("test1");         mi.Invoke(this, null);     }     catch (TargetInvocationException tiex)     {         // Throw the new exception         throw tiex.InnerException;     } }
27323
I can't figure out how to use an array or matrix in the way that I would normally use a list. I want to create an empty array (or matrix) and then add one column (or row) to it at a time.  At the moment the only way I can find to do this is like:  mat = None for col in columns:     if mat is None:         mat = col     else:         mat = hstack((mat, col))   Whereas if it were a list, I'd do something like this:  list = [] for item in data:     list.append(item)   Is there a way to use that kind of notation for  arrays or matrices?
56415
I have four foreach loops that iterate through the collections and based on a condition do something.   Here is the code that I am writing now:  boolean breakFlag = false; String valueFromObj2 = null; String valueFromObj4 = null; for(Object1 object1: objects){   for(Object2 object2: object1){     // I get some value from object2     valueFromObj2 = object2.getSomeValue();     for(Object3 object3 : object2){       for(Object4 object4: object3){        // Finally I get some value from Object4.        valueFromObj4 = object4.getSomeValue();        // Compare with valueFromObj2 to decide either to break all the foreach loop        breakFlag = compareTwoVariable(valueFromObj2, valueFromObj4 );        if(breakFlag){break;}       } // fourth loop ends here       if(breakFlag){break;}     } // third loop ends here     if(breakFlag){break;}   } // second loop ends here   if(breakFlag){break;} } // first loop ends here   The main object (objects in the code) comes from a third-party provider SDK, so I cannot change anything on that portion. I want to ask the Stack&nbsp;Overflow community if there is a better approach to break all the four foreach loops. Or if there is any other way to refactor this code to make it more readable and maintainable.
46114
First of all, I swear this is not homework, it's a question I was asked in an interview. I think I made a mess of it (though I did realise the solution requires recursion). Here is the question:  Implement the count() method which returns the number of nodes in a tree. If a node doesn't have either a left or right child, the relevant getXXChild() method will return null  class Tree {    Tree getRightChild() {     // Assume this is already implemented   }    Tree getLeftChild() {     // Assume this is already implemented   }    int count() {     // Implement me   } }   My reason for asking the question is simply curious to see the correct solution, and thereby measure how bad mine was.  Cheers, Tony
16473
Consider the class below that represents a Broker:  public class Broker {     public string Name = string.Empty;     public int Weight = 0;      public Broker(string n, int w)     {         this.Name = n;         this.Weight = w;     } }   I'd like to randomly select a Broker from an array, taking into account their weights.  What do you think of the code below?  class Program     {         private static Random _rnd = new Random();          public static Broker GetBroker(List&lt;Broker&gt; brokers, int totalWeight)         {             // totalWeight is the sum of all brokers' weight              int randomNumber = _rnd.Next(0, totalWeight);              Broker selectedBroker = null;             foreach (Broker broker in brokers)             {                 if (randomNumber &lt;= broker.Weight)                 {                     selectedBroker = broker;                     break;                 }                  randomNumber = randomNumber - broker.Weight;             }              return selectedBroker;         }           static void Main(string[] args)         {             List&lt;Broker&gt; brokers = new List&lt;Broker&gt;();             brokers.Add(new Broker("A", 10));             brokers.Add(new Broker("B", 20));             brokers.Add(new Broker("C", 20));             brokers.Add(new Broker("D", 10));              // total the weigth             int totalWeight = 0;             foreach (Broker broker in brokers)             {                 totalWeight += broker.Weight;             }              while (true)             {                 Dictionary&lt;string, int&gt; result = new Dictionary&lt;string, int&gt;();                  Broker selectedBroker = null;                  for (int i = 0; i &lt; 1000; i++)                 {                     selectedBroker = GetBroker(brokers, totalWeight);                     if (selectedBroker != null)                     {                         if (result.ContainsKey(selectedBroker.Name))                         {                             result[selectedBroker.Name] = result[selectedBroker.Name] + 1;                         }                         else                         {                             result.Add(selectedBroker.Name, 1);                         }                     }                 }                   Console.WriteLine("A\t\t" + result["A"]);                 Console.WriteLine("B\t\t" + result["B"]);                 Console.WriteLine("C\t\t" + result["C"]);                 Console.WriteLine("D\t\t" + result["D"]);                  result.Clear();                 Console.WriteLine();                 Console.ReadLine();             }         }     }   I'm not so confident. When I run this, Broker A always gets more hits than Broker D, and they have the same weight.  Is there a more accurate algorithm?  Thanks!
34074
Why this code isn't working? In my mind the next() method should move the cursor for the next item of the list...  List&lt;string&gt; listX = new List&lt;String&gt; {'A','B','C'}; while(listX.iterator().hasNext())     system.debug(listX.iterator().next());   When I try to run it I receive a error message of exceed a governor limit of CPU time. It's happend because the next() method doesn't move the cursor for the next list item. Every time returns "A".
7172
What would be the best way to look in a string[] to see if it contains a element. This was my first shot at it. But perhaps there is something that I am overlooking. The array size will be no larger than 200 elements.  bool isStringInArray(string[] strArray, string key) {     for (int i = 0; i &lt;= strArray.Length - 1; i++)         if (strArray[i] == key)             return true;     return false; }
14769
I need to concatenate two String arrays in Java.  void f(String[] first, String[] second) {     String[] both = ??? }   What is the easiest way to do this?
122018
I am trying to add a list into an another nested list before adding values of a list to nested list it is getting the correct value but after adding i am getting (already output) in debug log when i checked.    public List&lt;String&gt; fieldName {get;set;}  public List&lt;List&lt;String&gt;&gt; fileValuesXML; // To get the field values of xml  for(Dom.XMLNode child : SalesforceObjecet.getChildElements()) {                        objecetName = child.getText();             system.debug('Object Name in XML field  ' + objecetName );              for(Dom.XMLNode subchild : child.getChildElements())              {                 system.debug('Sub child ' + subchild.getText() );                 for(Dom.XMLNode subchildfield : subchild.getChildElements())                 {                     system.debug('Sub child Field ' + subchildfield );                     fName  = subchildfield.getText();                     fieldName.add(fName);                     //fileValuesXML.add(fieldName);                     //system.debug('Filed Name in XML field  ' + fieldName);                 }                  system.debug('Filed Name before affing to filevalueXML  ' + fieldName);                                     fileValuesXML.add(fieldName);                 fieldName.clear();                 system.debug('Filed Name after affing to filevalueXML  ' + fileValuesXML);             }    }    I am getting values in debug log as:     Filed Name before affing to filevalueXML  (AccountSource, field3)   Filed Name after affing to filevalueXML  ((), (already output),   (already output))