Sort in Dictionary Order
- Program that accepts up to n words and outputs them in dictionary order. (Hint: sort an array of numbers that represent the words; don’t directly sort the words.) Do NOT use the sort functions provided in the standard library.
Program
import
java.util.Scanner;
public class
SortAsDictionary {
private static
Scanner input;
private static int limit;
public static void
main(String[] args) {
input=new
Scanner(System.in);
System.out.println("Enter
the limit:");
limit=input.nextInt();
String[] arr=new
String[limit];
System.out.println("Enter
the elements of the array:");
for(int
j=0;j<limit;j++) {
arr[j]=input.next();
}
SortAsDictionary ob=new
SortAsDictionary();
ob.sort(arr);
}
public void
sort(String[] arr) {
for(int
i=0;i<limit;i++) {
for(int
j=i+1;j<limit;j++) {
if(arr[j].compareTo(arr[i])<0)
{
String
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
System.out.println("The
sorted array is:");
for(int
j=0;j<limit;j++) {
System.out.println(arr[j]);
}
}
}
Output
Enter
the limit:
5
Enter
the elements of the array:
Ricky
Michael
Watsnon
Shane
Johnson
The
sorted array is:
Johnson
Michael
Ricky
Shane
Watsnon
- Program to count number of words in a given text file.
Program
import
java.io.File;
import
java.io.FileNotFoundException;
import
java.util.Scanner;
public class
CountWordsInFile {
private static
Scanner input;
public static void
main(String[] args) throws FileNotFoundException {
int
count=0;
input=new
Scanner(new File("path\\test.txt"));
while(input.hasNext())
{
input.next();
count++;
}
System.out.println("The
file contains "+count+" words.");
}
}
Output
The
file contains 51 words.
No comments:
Post a Comment