Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Class : Java Book : Introduction To Java Programming 10th Edition, Comprehensive

ID: 3889101 • Letter: C

Question

Class: Java

Book: Introduction To Java Programming 10th Edition, Comprehensive by Daniel Liang

Problem:

****** Parse the text file by splitting on "[ .,;:!?(){}<>"]", that is call the split method with this parameter: For example, call contents.split("[ .,;:!?(){}<>"]"), where contents is a String object containing the contents of the text file. ******

isplay words in ascending alphabetical order) Write a program that reads words from a text file and displays all the words (duplicates allowed) in ascend- ing alphabetical order. The words must start with a letter. The text file is passed as a command-line argument.

Explanation / Answer

StringsSort.java

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Arrays;

import java.util.Scanner;

public class StringsSort {

public static void main(String[] args) throws FileNotFoundException {

File file = new File(args[0]);

if(file.exists())

{

Scanner scan = new Scanner(file);

String contents = "";

while(scan.hasNextLine()) {

contents+=scan.nextLine();

}

String words[] = contents.split("[ .,;:!?(){}<>"]");

System.out.println("Before sorting, words are: ");

System.out.println(Arrays.toString(words));

String temp = "";

int n = words.length;

for(int i=0; i < n; i++){

for(int j=1; j < (n-i); j++){

if(words[j-1].toLowerCase().compareTo(words[j].toLowerCase()) > 0){

//swap the elements!

temp = words[j-1];

words[j-1] = words[j];

words[j] = temp;

}

}

}

  

System.out.println("After sorting, words are: ");

System.out.println(Arrays.toString(words));

} else {

System.out.println(args[0]+" file does not exist");

}

}

}

Output:

Before sorting, words are:
[Mary, had, a, little, lambIts, fleece, was, white, as, snowAnd, everywhere, that, Mary, wentThe, lamb, was, sure, to, go]
After sorting, words are:
[a, as, everywhere, fleece, go, had, lamb, lambIts, little, Mary, Mary, snowAnd, sure, that, to, was, was, wentThe, white]

input.txt

Mary had a little lamb
Its fleece was white as snow
And everywhere that Mary went
The lamb was sure to go.