Sum up numbers with Arraylist in Java
A small application which sum up numbers from the Scanner input.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class SumUp {
public static List<Integer> inputNumbers(){
List<Integer> numbers = new ArrayList<Integer>();
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String[] numberlist = input.split(" ");
sc.close();
for(var n = 0; n < numberlist.length; n++){
Integer value;
try {
value = Integer.valueOf(numberlist[n]);
numbers.add(value);
} catch ( NumberFormatException e){
// continue
}
}
return numbers;
}
private static void sumup(List<Integer> numbers){
int sum = 0;
for(var n = 0; n < numbers.size(); n++){
sum += numbers.get(n);
}
System.out.println(sum);
}
public static void main(String[] args){
List<Integer> n = SumUp.inputNumbers();
SumUp.sumup(n);
}
}
0
0
0.000
While I'm more interested in programming with Python, I understand that the size of conventional arrays in Java can't be modified, so ArrayLists are the way to go.
That being said, congrats on creating the project, that inspires me to post my own. Good luck!
Python is also a good programming language with a huge community and library support.
Yes, and ArrayLists also support generics and static arrays not. This is an advantage to use the Lists.
!LUV
@jesalmofficial, @ozelot47(1/10) sent you LUV. | discord | community | HiveWiki | NFT | <>< daily
! help
(no space) to get help on Hive. Info