** MUST BE USING JAVA Write a program that reads from the user 10 numbers and di
ID: 3665862 • Letter: #
Question
** MUST BE USING JAVA
Write a program that reads from the user 10 numbers and displays how many distinct numbers were entered and which are the distinct numbers.
For example, if the numbers entered were: 12, 38, 23, 12, 1, 15, 23, 12, 10, 72
Your program should display: The following 7 distinct numbers were entered
12, 38, 23, 1, 15, 10, 72
The above is just an example, your program should work for any sequence of ten numbers entered.
Hint: Read a number and store it to an array if it is new. If the number is already in the array, ignore it. After the input, the array contains the distinct numbers.
Explanation / Answer
import java.util.*;
import java.lang.*;
import java.io.*;
class PrintingDistinctNumbers {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
String strI;
Scanner input = new Scanner(System.in);
//Scanner dis=new Scanner(System.in);
input.useDelimiter("\D");
System.out.print("Enter ten numbers: ");
int[] values = new int[10];
int qty = 0;
for(int i = 0; i < 10; i++) {
int num = input.nextInt();
boolean distinct = true;
for(int j = 0; j < qty; j++) {
if (num == values[j]) {
distinct = false;
break;
}
}
if (distinct) values[qty++] = num;
}
System.out.println("The distinct numbers are: ");
for(int i = 0 ; i < qty; i++)
{
sb.append("");
sb.append(values[i]+",");
}
strI = sb.toString();
strI = strI.substring(0,strI.length()-1) + " ";
System.out.print(strI);
//System.out.print(values[i]+",");
}
}
input:
Enter ten numbers:
12,38,23,12,1,15,23,12,10,72
OutPut:
Enter ten numbers: The distinct numbers are:
12,38,23,1,15,10,72
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.