If you just want to keep numbers, why did you create a ArrayList
of String
?
If you create a list of String
, to add you will have to convert the String
's in numbers, and if any is not (for example, if the user type xyz
), What will you do? Ignore it, make a mistake? Wouldn’t it be better to already treat it in the input, and so ensure that the list only has numbers?
Use the right kind for what you want - in case it could be a Integer
, if it is only integers, for example:
Scanner scanner = new Scanner(System.in);
List<Integer> numeros = new ArrayList<>();
for (int i = 1; i < 4; i++) {
System.out.println("Digite o " + i + "º valor: ");
numeros.add(scanner.nextInt()); // ler o dado como um número inteiro
}
int soma = 0;
for (Integer n : numeros) {
soma += n.intValue();
}
System.out.println("A soma é " + soma);
Probably someone will suggest using streams to add:
int soma = numeros.stream().mapToInt(Integer::intValue).sum();
// ou
int soma = numeros.stream().reduce(0, Integer::sum);
But I already say that for this case is an exaggeration (not to mention that streams are slower than a loop simple).
The above code does not handle errors if you type something that is not a number. An alternative is to read the data as String
and try to convert to number:
for (int i = 1; i < 4; i++) {
while (true) {
try {
System.out.println("Digite o " + i + "º valor: ");
numeros.add(Integer.parseInt(scanner.nextLine()));
break;
} catch (NumberFormatException e) {
System.out.println("Você não digitou um número inteiro");
}
}
}
Reading with nextLine
avoids some pitfalls if the user type only ENTER, for example, among other problems that may occur while using nextInt
and the input is not the expected amount (see here for more details).
Another detail is that you used ArrayList
, which despite the name, is not an array (not the array itself as defined by the language), rather a list (one of the many classes that make up the Collections Framework).
The advantage of the list is that its size is flexible, and you can add elements without worrying, because internally it allocates more space if necessary. Already arrays have fixed size, and as in your case you are using a fixed size, the code could use arrays as well:
Scanner scanner = new Scanner(System.in);
int numeros[] = new int[3];
for (int i = 0; i < numeros.length; i++) {
while (true) {
try {
System.out.println("Digite o " + (i + 1) + "º valor: ");
numeros[i] = Integer.parseInt(scanner.nextLine());
break;
} catch (NumberFormatException e) {
System.out.println("Você não digitou um número inteiro");
}
}
}
int soma = 0;
for (int n : numeros) {
soma += n;
}
System.out.println("A soma é " + soma);
Finally, if you want to have numbers with decimals, just change int
for double
and Integer.parseInt
for Double.parseDouble
:
Scanner scanner = new Scanner(System.in);
double numeros[] = new double[3];
for (int i = 0; i < numeros.length; i++) {
while (true) {
try {
System.out.println("Digite o " + (i + 1) + "º valor: ");
numeros[i] = Double.parseDouble(scanner.nextLine());
break;
} catch (NumberFormatException e) {
System.out.println("Você não digitou um número válido");
}
}
}
double soma = 0;
for (double n : numeros) {
soma += n;
}
System.out.println("A soma é " + soma);
Remembering that the numbers should be typed taking into account the decimal separator of the locale JVM standard (ie may be 2.5
or 2,5
depending on configuration, although I can change that).
Remembering that you can also make the sum in it loop who reads the numbers, how did the other answer. In the above codes I am assuming that there is already a list (no matter where it came from) and you want to add its elements (because if it is only to read the numbers and display the sum, and nothing else, it is better to do everything in the same loop).
you can use String.Join(" ," valueList); - has a post with a similar doubt https://stackoverflow.com/questions/42433540/string-join-list-and-items/42433722
– tarsomatos
I used the method but they are concatenating as a string, I cannot sum the values. (1+2+3=6 and not 1,2,3)
– En.Fabiano