Whenever you assign a new value to a variable, the new value replaces the old value in it. In other words, there can be only one value in a variable. In case of an array, you can have multiple values assigned to array variables (identified by their indexes) but keep in mind that the array name itself can refer to only a single value.
Another thing you should keep in mind is the problems associated with Scanner::next
, Scanner::nextInt
etc. when you are inputting value in a loop. Check this to learn more about it.
Considering the points mentioned above, a better way to handle such a requirement would be as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean valid;
int t = 0, n = 0;
do {
valid = true;
System.out.print("Enter the number of integers you want to process: ");
try {
t = Integer.parseInt(s.nextLine());
if (t < 0) {
System.out.println(
"Error: This is a wrong input. The number should be a positive integer. Try again.");
valid = false;
}
} catch (NumberFormatException e) {
System.out.println("Error: This is a wrong input. The number should be a positive integer. Try again.");
valid = false;
}
} while (!valid);
System.out.println("Thank you. Now enter " + t + " intgers as prompted.");
int evensum = 0;
for (int i = 1; i <= t; i++) {
do {
valid = true;
System.out.print("Enter an integer: ");
try {
n = Integer.parseInt(s.nextLine());
if (n % 2 == 0) {
evensum = evensum + n;
}
} catch (NumberFormatException e) {
System.out.println("Error: This is a wrong input. Try again.");
valid = false;
}
} while (!valid);
}
// Display the result of adding all even inputs
System.out.print("The sum of even integers input by you is " + evensum);
}
}
A sample run:
Enter the number of integers you want to process: 3
Thank you. Now enter 3 intgers as prompted.
Enter an integer: 10
Enter an integer: 5
Enter an integer: 8
The sum of even integers input by you is 18
Another sample run:
Enter the number of integers you want to process: a
Error: This is a wrong input. The number should be a positive integer. Try again.
Enter the number of integers you want to process: 10.5
Error: This is a wrong input. The number should be a positive integer. Try again.
Enter the number of integers you want to process: -20
Error: This is a wrong input. The number should be a positive integer. Try again.
Enter the number of integers you want to process: 3
Thank you. Now enter 3 intgers as prompted.
Enter an integer: 10
Enter an integer: xyz
Error: This is a wrong input. Try again.
Enter an integer: 1.5
Error: This is a wrong input. Try again.
Enter an integer: 5
Enter an integer: 8
The sum of even integers input by you is 18
Feel free to comment in case of any issue/doubt.