学以致用——Java源码——对用户输入进行去重处理(Duplicate Elimination)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hpdlzu80100/article/details/85247616

发现之前的代码与需求有一定出入,所以改写了一下:

1. 如果用户输入不重复的值,显示该值,否则提示用户重复输入,不显示该值

2. 使用了增强for语句(enhanced for statement)遍历数组

3. 仅打印不重复值

上一个版本的代码参考:

https://blog.csdn.net/hpdlzu80100/article/details/51850689

代码如下:

package exercises.ch7Arrays;

//JHTP Exercise 7.12: Duplicate Elimination
//by [email protected]
/**(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)
{

	final int SIZE=5;	
	int[] entry=new int[5];
	int number=0;
	boolean flag=false; //重复标记
	int count=0;
	int entries =0; //输入总次数

	Scanner input=new Scanner(System.in);
	
	for (int i=0;i<SIZE;i++){
		flag = false;  //重新输入时,重置重复标记
		System.out.print("请输入10-100中的一个整数(输入-1退出):");
		number=input.nextInt();
		if(number==-1){
			System.out.print("已退出程序。\n");
			break;
		}
		for (int x: entry){  //遍历现有数组,判断是否重复(使用增强for语句遍历数组元素)
		if (x ==number){
			System.out.print("该数值之前已输入,不能重复输入!\n"); //2018年12月25日改进
			flag = true;
		}
		}
		if (!flag){		//如果未重复,显示该值
		entry[count]=number;
		System.out.printf("您所输入的值为:%d%n",number);
		count++;
		}
		entries++;
		
	}

		System.out.printf("共输入了%d个数,输入了重复值%d次,输入的不重复值有%d个,依次为:\n",entries, entries - count, count);
		for (int i=0; i<count;i++) 
			System.out.printf(entry[i]+"\t");
	
	input.close();
}
}
	





运行结果:

请输入10-100中的一个整数(输入-1退出)10

您所输入的值为:10

请输入10-100中的一个整数(输入-1退出)10

该数值之前已输入,不能重复输入!

请输入10-100中的一个整数(输入-1退出)20

您所输入的值为:20

请输入10-100中的一个整数(输入-1退出)30

您所输入的值为:30

请输入10-100中的一个整数(输入-1退出)-1

已退出程序。

共输入了4个数,输入了重复值1次,输入的不重复值有3个,依次为:

10                   20                   30                  

猜你喜欢

转载自blog.csdn.net/hpdlzu80100/article/details/85247616
今日推荐