Array Methods
Write a program to show use of different array method.
import java.util.*;
class P17ArrayMethods
{
public static void main()
{
int[] a= getInt();
String[] b= getString();
int n= a.length;// length is used to get total no of elements
int m= b.length;
Arrays.sort(a); Arrays.sort(b);
System.out.println(" \n Integer In acending order using Sort method of array\n");
for(int i=0;i<n;i++)
System.out.print(a[i]+"\t");
System.out.println("\n Words In dictionary order using Sort method of array \n");
for(int i=0;i<m;i++)
System.out.print(b[i]+"\t");
Arrays.fill(a,2,5,0);//fill array element with zero from index 2 to 4
System.out.println(" \n Printing arrays without using loop\n" +Arrays.toString(a));
System.out.println(" \n Printing arrays without using loop\n" +Arrays.toString(b));
}
static int[] getInt()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the no. of integer you want to input ");
int n=in.nextInt();
int[] a= new int[n];// create an array of length n
for(int i=0;i<n;i++)
{
System.out.print(" \n Enter integer "+(i+1) + "\t");
a[i]=in.nextInt(); // store in value input by user in array
}
return a;
}
static String[] getString()
{
Scanner in = new Scanner(System.in);
System.out.println("\n Enter the no. of Words you want to input ");
int n=in.nextInt();
String[] a= new String[n];// create an array of length n
for(int i=0;i<n;i++)
{
System.out.print(" \n Enter Word "+(i+1) + "\t");
a[i]=in.next(); // store in value input by user in array
}
return a;
}
}
Comments
Post a Comment