Java code asks the user to enter the number of grades he want to enter then it enter a function or method to put them into array then enter another method to find average. the code compile without error but when i run and i put the number of grades but the function grades crash, I am used to code in c++ so i may be missing some basics of java. Your understanding will be appreciated. I hope when fixing it , to tell me what is my mistake. package lab10ex8;  import java.util.Scanner;  public class Lab10ex8 {                public static double[] grades ( int n, double a [] ) {         Scanner S = new Scanner(System.in);         double grade=0;         for(int i=0; i&lt;n ; i++)         {             grade = S.nextDouble();             a[i] = grade;                      }         return a;     }          public static double average( double a[] ) {         double average=0;         double c;         double sum=0;         Scanner S = new Scanner(System.in);                  for(int i=0; i&lt; a.length ; i++){                          c= a[i];             sum = sum+c;         }         average = sum/a.length;         return average;     }      public static void main(String[] args) {         int n;         System.out.println( &quot;Enter the number of Grades : &quot; );         Scanner S = new Scanner(System.in);              n=S.nextInt();         double a[] = null;         grades(n,a);         average(a);                       }      }
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?
116296
Anytime I have to handle dates/times in java it makes me sad   I'm trying to parse a string and turn it into a date object to insert in a preparepared statement. I've been trying to get this working but am having no luck. I also get the helpful error message when I go to compile the class.  "Exception in thread "main" java.lang.Error: Unresolved compilation problem:  The method setDate(int, Date) in the type PreparedStatement is not applicable for the arguments (int, Date)"  Eh WTF?  Here is the offending code.  for(int i = 0; i &lt; flights.size(); i++){      String[] details = flight[i].toString().split(":");      DateFormat formatter ;      formatter = new SimpleDateFormat("ddMMyyyy");     Date date = formatter.parse(details[1]);       PreparedStatement pstmt = conn.prepareStatement(insertsql);     pstmt.setString(1, details[0]);     pstmt.setDate(2, date);     pstmt.setString(3, details[2] + "00");     pstmt.setString(4, details[3]);     pstmt.setString(5, details[4]);     pstmt.setString(6, details[5]);     pstmt.setString(7, details[6]);     pstmt.setString(8, details[7]);     pstmt.setString(9, details[8]);     pstmt.executeUpdate();  }
29851
I have an error that seems common on the web,  Though i cant find a definite answer that applies to my case:  I have the following Apex code:  public with sharing class templicenseemail {      private ApexPages.standardController standardController;       public Trainee__c trainee { get; set; }     public templicenseemail(ApexPages.StandardController controller) {         this.standardController = standardController;     }      public PageReference doSomething()     {         trainee  = [SELECT Email__c,First_Name__c,Institution__c,Last_Name__c FROM Trainee__c                  WHERE Id = :ApexPages.currentPage().getParameters().get('id')];                  String whatIs = trainee.Volume_Serial_Number__c;                 integer strlen = whatIs.length();                  ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, trainee.Email__c  ));         return null;      }     }   And the following test case:  @isTest(seealldata=false)      private class Send_noti_emailsTestClass5 {          static testMethod void validateSend_noti_emails5() {              templicenseemail  MyTestcase = new templicenseemail();              // code here in the Middle              MyTestcase.doSomething();          }     }   I'm getting the following error:  Error: Compile Error: Constructor not defined: [templicenseemail].&lt;Constructor&gt;(SOBJECT:Lead) at line:      templicenseemail  MyTestcase = new templicenseemail();   Does anyone know why?
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.
76434
I have just started the MIT Introduction to Algorithms course through the material posted online. Along with the course I have also decided to learn/enhance my Ruby skills by coding the algorithms in it.   I am on the first algorithm given, which is Insertion sort, and I have the following code typed up but I am getting this error when I run it:     insertionsort.rb:5:in `>': comparison of Fixnum with nil failed (ArgumentError)   def  insertionsort(num) for j in 2..num.length     key = num[j]     i = j - 1     while i &gt; 0 and num[i] &gt; key         num[i+1] = num[i]         i = i - 1     end     num[i+1] = key end  puts num end  numbers = [23,34,46,87,12,1,66]  insertionsort(numbers)   I'm sure it is a fairly basic problem but I just can't grasp what it is at the moment. Any  help or tips would be very much appreciated.
1992
While working in a Java app, I recently needed to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be in advance. The best I could come up with off the top of my head was something like this:  public String appendWithDelimiter( String original, String addition, String delimiter ) {     if ( original.equals( "" ) ) {         return addition;     } else {         return original + delimiter + addition;     } }  String parameterString = ""; if ( condition ) parameterString = appendWithDelimiter( parameterString, "elementName", "," ); if ( anotherCondition ) parameterString = appendWithDelimiter( parameterString, "anotherElementName", "," );   I realize this isn't particularly efficient, since there are strings being created all over the place, but I was going for clarity more than optimization.  In Ruby, I can do something like this instead, which feels much more elegant:  parameterArray = []; parameterArray &lt;&lt; "elementName" if condition; parameterArray &lt;&lt; "anotherElementName" if anotherCondition; parameterString = parameterArray.join(",");   But since Java lacks a join command, I couldn't figure out anything equivalent.  So, what's the best way to do this in Java?
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.
9051
Check out the below program.   try {     for (String data : Files.readAllLines(Paths.get("D:/sample.txt"))){         String[] de = data.split(";");         System.out.println("Length = " + de.length);     } } catch (IOException e) {     e.printStackTrace(); }   Sample.txt:   1;2;3;4 A;B;; a;b;c;   Output:   Length = 4 Length = 2 Length = 3   Why second and third output is giving 2 and 3 instead of 4. In sample.txt file, condition  for 2nd and 3rd line is should give newline(\n or enter) immediately after giving delimiter for the third field. Can anyone help me how to get length as 4 for 2nd and 3rd line without changing the condition of the sample.txt file and how to print the values of de[2] (throws  ArrayIndexOutOfBoundsException)?
7075
I have a function which parses one string into two strings.  In C# I would declare it like this:  void ParseQuery(string toParse, out string search, out string sort) {     ... }   and I'd call it like this:  string searchOutput, sortOutput; ParseQuery(userInput, out searchOutput, out sortOutput);   The current project has to be done in C++/CLI.  I've tried  using System::Runtime::InteropServices;  ...  void ParseQuery(String ^ toParse, [Out] String^ search, [Out] String^ sort) {     ... }   but if I call it like this:  String ^ searchOutput, ^ sortOutput; ParseQuery(userInput, [Out] searchOutput, [Out] sortOutput);   I get a compiler error, and if I call it like this:  String ^ searchOutput, ^ sortOutput; ParseQuery(userInput, searchOutput, sortOutput);   then I get an error at runtime.  How should I declare and call my function?
9476
Imagine you have a large array of floating point numbers, of all kinds of sizes. What is the most correct way to calculate the sum, with the least error? For example, when the array looks like this:  [1.0, 1e-10, 1e-10, ... 1e-10.0]   and you add up from left to right with a simple loop, like  sum = 0 numbers.each do |val|     sum += val end   whenever you add up the smaller numbers might fall below the precision threshold so the error gets bigger and bigger. As far as I know the best way is to sort the array and start adding up numbers from lowest to highest, but I am wondering if there is an even better way (faster, more precise)?  EDIT: Thanks for the answer, I now have a working code that perfectly sums up double values in Java. It is a straight port from the Python post of the winning answer. The solution passes all of my unit tests. (A longer but optimized version of this is available here )  /**  * Adds up numbers in an array with perfect precision, and in O(n).  *   * @see http://code.activestate.com/recipes/393090/  */ public class Summarizer {      /**      * Perfectly sums up numbers, without rounding errors (if at all possible).      *       * @param values      *            The values to sum up.      * @return The sum.      */     public static double msum(double... values) {         List&lt;Double&gt; partials = new ArrayList&lt;Double&gt;();         for (double x : values) {             int i = 0;             for (double y : partials) {                 if (Math.abs(x) &lt; Math.abs(y)) {                     double tmp = x;                     x = y;                     y = tmp;                 }                 double hi = x + y;                 double lo = y - (hi - x);                 if (lo != 0.0) {                     partials.set(i, lo);                     ++i;                 }                 x = hi;             }             if (i &lt; partials.size()) {                 partials.set(i, x);                 partials.subList(i + 1, partials.size()).clear();             } else {                 partials.add(x);             }         }         return sum(partials);     }      /**      * Sums up the rest of the partial numbers which cannot be summed up without      * loss of precision.      */     public static double sum(Collection&lt;Double&gt; values) {         double s = 0.0;         for (Double d : values) {             s += d;         }         return s;     } }
89923
Question:  Is exception handling in Java actually slow?  Conventional wisdom, as well as a lot of Google results, says that exceptional logic shouldn't be used for normal program flow in Java.  Two reasons are usually given,   it is really slow - even an order of magnitude slower than regular code (the reasons given vary),     and    it is messy because people expect only errors to be handled in exceptional code.     This question is about #1.  As an example,  describes Java exception handling as "very slow" and relates the slowness to the creation of the exception message string - "this string is then used in creating the exception object that is thrown. This is not fast."  The article  says that "the reason for this is due to the object creation aspect of exception handling, which thereby makes throwing exceptions inherently slow".  Another reason out there is that the stack trace generation is what slows it down.  My testing (using Java 1.6.0_07, Java HotSpot 10.0, on 32 bit Linux), indicates that exception handling is no slower than regular code.  I tried running a method in a loop that executes some code.  At the end of the method, I use a boolean to indicate whether to return or throw.  This way the actual processing is the same. I tried running the methods in different orders and averaging my test times, thinking it may have been the JVM warming up.  In all my tests, the throw was at least as fast as the return, if not faster (up to 3.1% faster).  I am completely open to the possibility that my tests were wrong, but I haven't seen anything out there in the way of the code sample, test comparisons, or results in the last year or two that show exception handling in Java to actually be slow.  What leads me down this path was an API I needed to use that threw exceptions as part of normal control logic.  I wanted to correct them in their usage, but now I may not be able to.  Will I instead have to praise them on their forward thinking?  In the paper , the authors suggest that the presence of exception handlers alone, even if no exceptions are thrown, is enough to prevent the JIT compiler from optimizing the code properly, thus slowing it down.  I haven't tested this theory yet.
13332
I am trying to use a  as input and then creating a query with it - so I need a .    I was surprised to find that it couldn't do the conversion implicitly or explicitly - but I don't even know how I would do this, as the Java API is still fairly new to me.
1982
The following code is generating a stack overflow error for me  int main(int argc, char* argv[]) {     int sieve[2000000];     return 0; }   How do I get around this? I am using Turbo C++ but would like to keep my code in C  EDIT:  Thanks for the advice.  The code above was only for example, I actually declare the array in a function and not in sub main.  Also, I needed the array to be initialized to zeros, so when I googled malloc, I discovered that calloc was perfect for my purposes.  Malloc/calloc also has the advantage over allocating on the stack of allowing me to declare the size using a variable.
118553
In C++ I can't use a method if I declare it after the calling method.    Does this order matter in other languages like Java or C#?
74245
In the  book on pg 130, they mention that an Array's length is fixed when you initialize it and that multidimensional arrays are not supported. I just tried using the .add function on an array and it worked so I'm sure what they are talking about, but I couldn't make an array of arrays (which could have just been because I didn't have the right syntax). Ignoring syntax errors, there seems to be some sort of difference and thus maybe an (even if just slight) advantage to using one over the other?
81621
If I write the following class:  public class Example {        int j;       int k;        public Example(int j, int k) {            j = j;            k = k;       }        public static void main(String[] args) {            Example exm = new Example(1,2);            System.out.println(exm.j);            System.out.println(exm.k);       }  }   The program compiles, but when I run the program, the main method will print out two 0s. I know that in order to say that I want to initialize the instance variables in the constructor I have to write:  this.j = j; this.k = k;   But if I don't write it, then which variable is evaluated (or considered) in the constructor (on the left and on the write hand side of the expressions)? Is is the argument or the instance variable? Does it make a difference?  Are there other cases where the use of this is obligatory?
91651
I know that it isn't a new question (I read already some others questions) but:   the question was asked many months ago; my problem, perhaps, is a little different!   Well, as I wrote in the previous message I'm blind and when I try to insert a question I have many problems with correctly indenting my code! I try the shortcut ctrl+K but it add the first 4 spaces and nothing else! If I try to indent this code, for example:  String buf; if(buf!=null) buf="buf isn't null"; else buf="buf is null";   If I selected all rows and press ctrl+K all rows are shifted to right by 4 spaces and the check returns an error because the rows 3 and 5 aren't indentent correctly and now there is the problem... if I select lines 3 and 5 and press ctrl+K again, the editor deletes the 4 spaces!  My question is: why don't you implement an HTML tag (something like &lt;bad code&gt;) that skips the control and, the negative thing, add a "bad reputation" to the author? I don't ask a workaround, but I can't lose 3 hours (yesterday I lost this time) for a question that already I can't post because the code is blocked! Another suggestion: could we be to able ask a moderator to add that bad reputation if he/she see the author never indent his/her code or remove the "bad reputation" if he/she see the author try to indent the code but it isn't indent perfectly! What do you think about it?  P.S.: This post is caused by the frustration that I have because from yesterday to today I can't insert a question on stack overflow because my code isn't indented correctly... If you should see how many times I try to fix it tou could understand my frustration!  P.S.2: can you implement the tag title on your toolbar icon? It could help me to use it.  @Hammar: ok, I write here what I think should be the correct code:     String buf;     if(buf!=null)         buf="buf is not null";     else         buf="buf is null"; ...  There are some errors to this code?  Ok, now I understand that the error wasn't where I thought (or better it COULD be in another place) so my new suggestion is: why don't you create a function that insert a tag for delimited where is the error? I not that you already change the post (for example deleting the initial phrase: "Hello all,") but i don't know how you do the check so I don't know if it is possible!  Ok, now I inset the question that caused this post and my frustration, the question is this:    and I resolve the check adding 4 space around all "suspected" code and adding some empty line... Tell me if it is better change the title for only the last suggestion or is better keep all things for, in the future, understand why and what I asked...