1. 程式人生 > >學以致用——Java原始碼——對使用者輸入進行去重處理(Duplicate Elimination)

學以致用——Java原始碼——對使用者輸入進行去重處理(Duplicate Elimination)

發現之前的程式碼與需求有一定出入,所以改寫了一下:

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