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

来源:互联网 发布:淘宝和田玉店铺 编辑:程序博客网 时间:2024/06/15 20:15

需求描述:

用户任意输入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 numberis 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. Displaythe 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,



0 0
原创粉丝点击