This is the first solution to find the length of all the integers given during input. This program uses the HashMap collection to store the integer values and it’s respective length as key value pairs.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
public class LengthOfIntegersDuringInput {
public static void main(String args[]) {
HashMap<Integer,Integer> DigitsMap= new HashMap<Integer,Integer>();
Scanner inpInt=new Scanner(System.in);
System.out.println("OUTPUT:");
System.out.println("Enter a few integers::At the end enter 9999 to stop entering");
while (true) {
int num=inpInt.nextInt();
if (num!=9999)
DigitsMap.put(num,Integer.toString(num).length());
else
break;
}
inpInt.close();
// Store all the keys of the HashMap in the Set collection.
Set<Integer> allKeys=DigitsMap.keySet();
Iterator<Integer> keyIt=allKeys.iterator();
//Traverse through the keyIt iterator and print the values respectively for each key.
System.out.println("The list of integers along with number of digits in each integer");
System.out.println("Integer NumOfDigits");
while (keyIt.hasNext()) {
int num=keyIt.next();
System.out.println(num+" "+DigitsMap.get(num));
}
}
}
OUTPUT:
Enter a few integers::At the end enter 9999 to stop entering
45
3
261
8754
334
66299
741
9999
The list of integers along with number of digits in each integer
Integer NumOfDigits
8754 4
3 1
261 3
741 3
66299 5
45 2
334 3

Leave a comment