Question 9
Write a program to store 10 names in an array, Arrange these in alphabetical order by
sorting. Print the sorted list. Take single word names, all in capital letters,
e.g. SAMSON, AJAY, LUCY, etc.
Answers
Sorting Names - Java
We will be using the package, for the Scanner and Arrays utilities.
We create a Scanner object to take in user input. We then initialize a String array of length 10 and run a loop to take user input of 10 names.
Then, we use the function to convert everything to upper case, just for safety.
The then sorts the whole array alphabetically. Finally, we run a loop to print the names.
NameSorter.java
import java.util.*; //Import the utils package
public class NameSorter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); //Create Scanner object
String names[] = new String[10]; //Initialize array
for(int i = 0; i < 10; i++) {
System.out.print("Enter Name ["+(i+1)+"]: ");
names[i] = sc.next(); //Take Array input
names[i] = names[i].toUpperCase(); //Convert to upper case, for safety
}
Arrays.sort(names); //Sort the array
System.out.println("The sorted list is: ");
for(int i = 0; i < 10; i++) { //Print the sorted list
System.out.println(names[i]);
}
}
}
Answer:
Java is a machine independent language which can work on any platform. Its an object oriented programming which stress on object rather than data.
The main parts while doing Java programming are package, Class ,input variables, condition updating.
◼Array is the representation of number of values of same data type.
◼Sorting means arranging elements of array in ascending descending or any other specific order.
import java . util. *;
class arrange
{
public static void main(String args[])
{
String n[] = new String[10]:
String s=" ";
int i, j;
Scanner Sc=new Scanner(System . in);
System . out. println("Enter the names");
for(i=0;i<10;i++)
{
n[i] = sc . next();
}
for(i=0;i<9;i++)
{
for(j=0;j<(9-i) ;j++)
{
if(n[j] . compareTo(n[j+1]>0)
{
s=n[j]
n[j]=n[j+1]
n[j+1]=s;
}
}
System . out. println("THE SORTED LIST IS");
for(i=0;i<10;i++)
{
System . out. println(n[i]);
}
}
}