HI everyone,
i need to enter all those values and add them up.
but have some trouble storing numbers to a array list.
plz help~~!

[import java.util.*;
public class array
{  public static void main (String []args)
{
Scanner sc= new Scanner (System.in);


int value;



System.out.print("How many values are in the data set?");
value=sc.nextInt();


for (int i=1; i<= value; i++)
{
int num;
System.out.print("Please enter value "+i+":");
num=sc.nextInt();


}



// store numbers to an array



}
}]

Edited 3 Years Ago by happygeek: fixed formatting

Firstly you need to know the size of array before you create one, so I would suggest to chalenge user to insert first number of values he wants to add to gether
Secondly once you get that info create array of that size
Third run for loop to get your values, but don't forget to check if their are numbers NOT characters or strings, if is it number store it in next empty position else request new entry
Finaly add your values together and display it

So what's teh question and where is teh "class Scanner " ?

Scanner is a part of the JDK Since 1.5 (if not 1.4.2).

@OP

Before you start the loop, you need to declare and initiate an array with the variable "value" after your first question.

int arrayname = new int[value];

Then, inside your loop, insert each of the values, as you get them, into your array.

arrayname[i] = num;

And your for loop should go from 0 to < value and not from 1 to <= value.

isn't that what I said in my post ;)

The "firstly" and "thirdly" would have been a little misleading, IMO, since he was already getting the length and he already had a for loop (just wasn't entering the values) and those points made it sound as though he still needed to add a new question for the length and create another for loop, which he didn't.

Like I said, that is all IMO, but that's the way I read it.

;-)

Edit: @OP I missed the totalling part. For that simply add an int declaration before the for loop and then total += num inside the for loop, so that you are totaling and storing the values inside the same for loop.

hi , well u try taking two integers i j to denote the numbers of values and the other for the index number of the array with the help of j , u can fetch the value in that index and add them up .

This article has been dead for over six months. Start a new discussion instead.