+ 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
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..
+ 1
it will not compile
+ 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);
}
}
+ 1
Use ArrayList.
+ 1
Whoops, never tried compiling it. Fixed a few errors. Should run now
0
use an arraylist<Integer> or declere every time a new array with incremented size and put the old values in the new array
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!!!
0
using vector
0
@srilekha How can I use vector? what are they?
0
vector is same as arry list but difference is this vector using some legacy methods
0
@srilekha Thanks for your appreciate!!!
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);
}
}