**7.5(打印不同的数)编写一个程序,读入10个数,显示互不相同的数的数目,并以输入的顺序显示这些数字,以一个空格分隔(即一个数字出现多次,也仅显示一次)。(提示:读入一个数,如果它是一个新数,则将 它存储在数组中。如果该数已经在数组中国,则忽略它。)输入之后,数组包含的都是不同的数。下面是这个程序的运行示例: Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2 The number of distinct numbers is 6 The distinct numbers are: 1 2 3 6 4 5 **7.5(Print different numbers)Write a program, read in 10 numbers, display the number of different numbers, and display these numbers in the order of input, separated by a space (that is, a number appears many times, but only once). (tip: read in a number and store it in the array if it is a new number. If the number is already in array China, ignore it.) After input, the array contains different numbers. Here is an example of how to run this program: Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2 The number of distinct numbers is 6 The distinct numbers are: 1 2 3 6 4 5
参考代码:
package chapter07;import java.util.ArrayList;import java.util.List;import java.util.Scanner;publicclassCode_05{publicstaticvoidmain(String[] args){
List<Integer> list =newArrayList<Integer>();
Scanner input =newScanner(System.in);
System.out.print("Enter 10 numbers: ");
String[] strings = input.nextLine().split(" ");int count =0;for(int i =0;i < strings.length;i++){if(!list.contains(Integer.parseInt(strings[i]))){
list.add(Integer.parseInt(strings[i]));
count++;}}
System.out.println("The number of distinct numbers is "+ count);
System.out.print("The distinct numbers are: ");for(int i : list)
System.out.print(i +" ");}}
结果显示:
Enter 10 numbers:1232163452
The number of distinct numbers is 6
The distinct numbers are:123645
Process finished with exit code 0