+ 1

How to write in an array without size!

I wanna have a program which read's an unknown numbers of data from user and then sum them up!!! Thanks

3rd Aug 2016, 1:07 PM
Ali Ashkani nia
12 Respostas
+ 2
/* in java .... or you can set some random appropriate general size of that array */ No no no..! do not set random general size for an array you are ASKING for problems later.. a list is a MUCH better idea..
3rd Aug 2016, 5:10 PM
Keith Brandenburg
Keith Brandenburg - avatar
+ 1
it will not compile
3rd Aug 2016, 1:33 PM
Ian Kahwai
Ian Kahwai - avatar
+ 1
Use a list. import java.util.*; class Program{ public static void main(String[] args){ Scanner input = new Scanner(System.in); List<Double> dArray = new ArrayList<Double>(); double sum = 0; boolean takeInput = true; while(takeInput){ if(input.hasNextDouble()){ dArray.add(input.nextDouble()); }else{ takeInput = false; } } for(double d : dArray){ sum += d; } System.out.println(sum); } }
3rd Aug 2016, 2:11 PM
James
James - avatar
+ 1
Use ArrayList.
3rd Aug 2016, 3:33 PM
WPimpong
WPimpong - avatar
+ 1
Whoops, never tried compiling it. Fixed a few errors. Should run now
3rd Aug 2016, 7:20 PM
James
James - avatar
0
use an arraylist<Integer> or declere every time a new array with incremented size and put the old values in the new array
3rd Aug 2016, 2:01 PM
Vincenzo Martusciello
Vincenzo Martusciello - avatar
0
@James Thanks for your help brother! but there is a problem! it won't quit from the loop!!! I tried what exactly U wrote (even name of variables!!! ) but it has errors!!! (scanner. java:864)(*******:1485)(********:2413) Thanks a bundle for your appreciate!!!
3rd Aug 2016, 5:23 PM
Ali Ashkani nia
0
using vector
8th Aug 2016, 1:24 PM
srilekha
0
@srilekha How can I use vector? what are they?
8th Aug 2016, 2:08 PM
Ali Ashkani nia
0
vector is same as arry list but difference is this vector using some legacy methods
8th Aug 2016, 2:24 PM
srilekha
0
@srilekha Thanks for your appreciate!!!
8th Aug 2016, 2:25 PM
Ali Ashkani nia
0
Hi everybody!!! I have written code for it and miraculously it works (: Thanks import java.util.*; public class Program { public static void main(String[] args) { ArrayList<Integer> ali = new ArrayList<Integer>(); int sum=0; Scanner g=new Scanner(System.in); while (g.hasNextInt()) { ali.add(g.nextInt()); } System.out.print(ali); for (int i = 0; i < ali.size(); i++) { sum+=ali.get(i); } System.out.print(sum); } }
9th Aug 2016, 6:03 PM
Ali Ashkani nia