第七章第五题(打印不同的数)(Print different numbers)

第七章第五题(打印不同的数)(Print different numbers)

  • **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;

public class Code_05 {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>();
        Scanner input = new Scanner(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: 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 
Process finished with exit code 0

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值