Question:
Find consecutive duplicate numbers in a series of numbers seperated by commas?
Code:
import java.util.Scanner; public class DuplicateNumbers { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // Example: 1,2,3,4,3,2,1 System.out.print("Enter numbers: "); String str = sc.nextLine(); // splitting a comma separated string String[] numbers = str.split(","); Integer last = null; Integer current = null; int total = 0; for (String number: numbers) { current = Integer.parseInt(number); // if last is null then this is the first number if (last != null) { if(last == current){ System.out.println("Duplicates: " + current); total = total +1; } } last = current; } System.out.println("Total duplicates: " + total); } }
Output:
$ java DuplicateNumbers Enter numbers: 1,2,5,5,7,8,8,4,4,3,2,1 Duplicates: 5 Duplicates: 8 Duplicates: 4 Total duplicates: 3