Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Searches for duplicate numbers between inputted and return them grouped in the order of appearing.
package com.javarush.task.task04.task0417;
/*
Существует ли пара?
*/
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) throws Exception {
Map<Integer, Integer> input = new LinkedHashMap<Integer, Integer>(); // create Map for input
for (int i = 0; i < 6; ++i) { // define quantity of numbers to be processed
while (true) { // start of input block
Scanner sc = new Scanner(System.in);
System.out.println("Input number " + (i + 1));
if (sc.hasNextInt()) { // check if such number already exists in map
int x = sc.nextInt();
if (input.containsKey(x)) {
input.put(x, input.get(x) + 1); // if exists - update counter
} else {
input.put(x, 1); // if not exists - add a number as a key
}
break; //stop of current input block
} else {
System.out.println("Invalid input");
}
}
}
for (int i : input.keySet()) { // for each key in the Map loop
for (int j = 0; j < input.get(i); ++j) { // number of loops defined by value of the key i.
if (input.get(i) > 1) { // check if number exists more than 1 time
System.out.print(i + " "); // print result
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.