Member Avatar for Danme

Hello Everybody,
I am learning Java from a few days.i am getting an error in one of my programs wherein i am trying to print thr sum of "n" numbers..the code is as follows..please help me

import java.math.*;
import java.util.*;
import java.io.*;

             public class Add1{
               public static void main(String args[]) {
               int n;
                System.out.println("eneter n");
        
                Scanner keyboard=new Scanner(System.in);
                      
                 
                       
                      /* n=JOptionPane.showInputDialog("enter a value");*/
                   int sum;           
                   sum=0;
                   int i;
                   for(i=0;i<n;i++)
                      {
                        i=keyboard.nextInt();
                        sum=sum+i;
                     }
                  System.out.println("sum="+ sum);
}
}

i am getting the following error..

C:\Program Files\Java\jdk1.6.0_07\bin>javac Add1.java
Add1.java:18: variable n might not have been initialized
for(i=0;i<n;i++)
^
1 error

please help me...

you need to initialize n

you can do this

int n = 0;

You had some of your code misplaced. I did a few corrections with detailed comments on what is happening in the code. Here it is revised--

import java.math.*;
import java.util.*;
import java.io.*;

public class Add1{
	public static void main(String args[]) {		;
		System.out.println("eneter n"); // prints out message
		Scanner keyboard=new Scanner(System.in); // gets a handle to the standard input stream through the scanner
		int n = keyboard.nextInt(); // obtain int value from keyboard

		/* n=JOptionPane.showInputDialog("enter a value");*/
		int sum; // sum declared to be an int but not defined
		sum=0; // assigning sum the value of zero
		int i; // i declared to be an int but not defined

		// assign i to be zero (happens once), i is less than or equal to n, increment i...
		for(i=0;i<=n;i++){
			sum=sum+i; // sum = sum + i    (1 + 2 + 3 + ... n)
		}
		System.out.println("sum="+ sum); // prints the sum
	}
}
Member Avatar for Danme

thanks a lot for looking it up....i really appreciare it...thanks once again....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.