- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxSumArrayList.java
More file actions
Latest commit
39 lines (32 loc) · 1.31 KB
/
Copy pathMaxSumArrayList.java
File metadata and controls
39 lines (32 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
importjava.util.ArrayList;
importjava.util.Scanner;
publicclassHighestAdjacentSum {
publicstaticvoidmain(String[] args) {
Scannerscanner = newScanner(System.in);
ArrayList<Integer> numbers = newArrayList<>();
// Taking input from the user
System.out.println("Enter numbers (enter any non-integer value to stop):");
while (scanner.hasNextInt()) {
intnum = scanner.nextInt();
numbers.add(num);
}
// Finding the sum of two adjacent numbers with the highest value
intmaxSum = Integer.MIN_VALUE;
intmaxIndex = -1;
for (inti = 0; i < numbers.size() - 1; i++) {
intsum = numbers.get(i) + numbers.get(i + 1);
if (sum > maxSum) {
maxSum = sum;
maxIndex = i;
}
}
// Displaying the result
if (maxIndex != -1) {
System.out.println("The sum of the two adjacent numbers with the highest value is: " + maxSum);
System.out.println("Those numbers are: " + numbers.get(maxIndex) + " and " + numbers.get(maxIndex + 1));
} else {
System.out.println("There are no adjacent numbers to find the sum.");
}
scanner.close();
}
}