The task is : Write a java program that takes an input stream of integers from the user and finds the smallest distance between two neighboring numbers in the stream. It should output the indices of the two neighboring numbers.
This is the code, I stored some number in an arraylist, then i took the last index of the arraylist and tried to create an array with the same number of elements
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Pr6
{
public Pr6 ()
{
Scanner sc = new Scanner (System.in);
String x = "";
int Distance =0;
int Index1 = 0;
int Index2 = 0;
List<Integer> AllNum = new ArrayList<>();
do
{
System.out.println ("Please enter a number");
int NewNumber = sc.nextInt();
AllNum.add (NewNumber);
System.out.println ("Do you want to enter a new number? Enter Y for yes and N for no");
x = sc.nextLine();
} while ("Y".equals(x));
int Index = AllNum.size();
int [] AllNumArray = new int [Index];
for (int i = 0; i < Index; i++)
{
AllNumArray[i] = AllNum.get(i);
}
for (int i = 0; i < Index; i++)
{
int NewDistance = AllNumArray[i] - AllNumArray [i+1];
if (NewDistance > Distance)
{
Distance = NewDistance;
Index1 = i;
Index2 = i+1;
}
}
System.out.println ("The smallest distance between two neighboring numbers is: " + Distance);
System.out.println("The first Nnumber is " + AllNumArray[Index1] + ", and its index is " + Index1);
System.out.println("The second Nnumber is " + AllNumArray[Index2] + ", and its index is " + Index2);
}
}