判断用户输入的数字是否有重复(Duplicate Elimination)

需求描述:

用户任意输入10-100内的数字,如果该数字之前输入过,提示用户重复输入,结束程序;

如果输入的5个数字都不重复,则提示用户没有重复输入,程序结束。


算法要点:将用户的输入保存在数组中,每次用户输入新的数字时,遍历(traverse)由之前输入的数字构成的数组,如果发现某个数字和新输入的数字相同,则设置重复标记为true,退出当前循环。


代码如下:

package example;
//JHTP Exercise 7.12: Duplicate Elimination
//by pandenghuang@163.com
/**(Duplicate Elimination) Use a one-dimensional array to solve the following problem:
Write an application that inputs five numbers, each between 10 and 100, inclusive. As each number
is read, display it only if it’s not a duplicate of a number already read. Provide for the “worst case,”
in which all five numbers are different. Use the smallest possible array to solve this problem. Display
the complete set of unique values input after the user enters each new value.:*/
import java.util.Scanner;

public class DuplicateRemoval 
{
	
	public static void main(String[] args)
{

	int[] entry=new int[5];
	int number=0;
	boolean flag=false;
	final int SIZE=5;
	int count=0;

	Scanner input=new Scanner(System.in);
	
	for (int i=0;i<SIZE;i++){
		System.out.print("请输入10-100中的一个整数(输入-1退出):");
		number=input.nextInt();
		if(number==-1){
			System.out.print("已退出程序。\n");
			break;
		}
		for (int j=0;j<=i;j++){
		if (entry[j]==number){
			flag=true;
			break;}
		}
		entry[i]=number;
		count++;
		if (flag)
			break;
		
	}
	if (!flag && count>0){
		System.out.printf("共输入了以下%d个数,没有出现重复。\n",SIZE);
		for (int i=0;i<count;i++)
			System.out.print(entry[i]+",");
	}
	else if (flag && count>0){
		System.out.printf("共输入了以下%d个数,输入了重复值!程序已退出。\n",count);
		for (int i=0;i<count;i++)
			System.out.print(entry[i]+",");
			}
}
}
	




运行结果:

Round 1:

请输入10-100中的一个整数(输入-1退出):11
请输入10-100中的一个整数(输入-1退出):12
请输入10-100中的一个整数(输入-1退出):12
共输入了以下3个数,输入了重复值!程序已退出。
11,12,12,

Round 2:

请输入10-100中的一个整数(输入-1退出):188
请输入10-100中的一个整数(输入-1退出):169
请输入10-100中的一个整数(输入-1退出):158
请输入10-100中的一个整数(输入-1退出):198
请输入10-100中的一个整数(输入-1退出):189
共输入了以下5个数,没有出现重复。
188,169,158,198,189,



  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值