We have seen how to store values in array. While storing values in an array, situation may be such that all the values in the array should be unique. In such situation we have to develop our program in such a manner that it satisfies the need.
Codes of the array program on unique values
public static void main(String args[])throws Exception
Why unique values in an array?
Suppose we are developing a program on array to store roll number of the students of a particular class and section. In such situation the roll number of students must be unique as in a class two or more students can not have the same roll number. Programmer can not expect operator to enter proper roll numbers. The operator may by mistake enter duplicate roll number but it’s the responsibily of the programmer to develop such a program that will never accept duplicate roll number.
How to proceed technically on this array program
We will create an array to store the values. The size of the array will be same as the number of values to be entered. Normally in array programs, we store the values directly in an array using a loop. In this program we will design a nested loop to take the values. Within the body of outer loop the values will be taken in a variable. The inner loop will check the array whether this current value is stored in the array. If the checking shows that the value is already present in the array, the value will be rejected as duplicate value otherwise it will be stored in the array. In case of rejection, the iteration will also be cancelled.
import java.io.*;
class UniqueValues
{
int arr[]=new int[10];
int i,n,j;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void takeData()throws Exception
{
for(i=0;i< 10;i++)
{
System.out.println("Enter the number:");
n=Integer.parseInt(br.readLine().trim());
for(j=0;j< i;j++)
{
if(n==arr[j])
break;
}
if(j< i)
{
System.out.println("Duplicate value...Re-enter:");
i=i-1;
}
else
arr[i]=n;
}
}
public void show()
{
System.out.println("Unique values are\n");
for(i=0;i< 10;i++)
System.out.print(" "+ arr[i]);
}
{
UniqueValues obj=new UniqueValues();
obj.takeData();
obj.show();
}
i have a question which i am not ablw to solve please help!!!
ReplyDeleteQ 1:Write a program to accept a name(containing three words)from the user and display the initials of the first and middle name along with the surname.
Sample Input:
Rajat Kumar Sharma
Sample output:
R.K.Sharma
Posted on January 28, 2011. Please check.
ReplyDelete