Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 10
- freddy
- at
- elephant
- whoooooodat
- alice
- tommy
- bobby
- it
- at
- about
- ------------------------------------------------------------------------------------------------------------------------------
- // Name: Sammy Samkough
- // Prog: Word Sort
- // Spec: Sort all words by comparing the length of each word. The word with the smallest length would come first. If you have
- // more than one word with the same length, that group would be sorted alphabetically.
- public class Word implements Comparable<Word>
- {
- private String word;
- public Word(String s)
- {
- word = s;
- }
- public int compareTo(Word rhs)
- {
- if(word.length() > rhs.toString().length())
- {
- return 1;
- }
- if(word.length() < rhs.toString().length())
- {
- return -1;
- }
- if(word.length() == rhs.toString().length())
- {
- for(int i = 0; i < word.length(); i++)
- {
- if(word.charAt(i) > rhs.toString().charAt(i))
- {
- return 1;
- }
- if(word.charAt(i) < rhs.toString().charAt(i))
- {
- return -1;
- }
- else
- {
- }
- }
- }
- return 0;
- }
- public String toString()
- {
- return "Word: " + word;
- }
- }
- ------------------------------------------------------------------------------------------------------------------------------
- // Name: Sammy Samkough
- // Prog: Word Sort
- // Spec: Sort all words by comparing the length of each word. The word with the smallest length would come first. If you have
- // more than one word with the same length, that group would be sorted alphabetically.
- import java.io.File;
- import java.io.IOException;
- import java.util.Scanner;
- import java.util.Arrays;
- public class WordRunner
- {
- public static void main( String args[] ) throws IOException
- {
- Scanner file = new Scanner(new File("words.dat"));
- int size = file.nextInt();
- Word [] words = new Word[size];
- file.nextLine();
- for(int i = 0; i < size; i++)
- {
- words[i] = new Word(file.next());
- }
- System.out.println("Words before it was sorted:");
- for(int i = 0; i < size; i++)
- {
- System.out.println(words[i]);
- }
- System.out.println("\n======= \n");
- System.out.println("Words after it was sorted:");
- Arrays.sort(words);
- for(int i = 0 ; i < size ; i++)
- {
- System.out.println(words[i]);
- }
- System.out.println("\n");
- }
- }
- /*
- Words before it was sorted:
- Word: freddy
- Word: at
- Word: elephant
- Word: whoooooodat
- Word: alice
- Word: tommy
- Word: bobby
- Word: it
- Word: at
- Word: about
- =======
- Words after it was sorted:
- Word: about
- Word: at
- Word: it
- Word: bobby
- Word: tommy
- Word: alice
- Word: at
- Word: whoooooodat
- Word: elephant
- Word: freddy
- Press any key to continue . . .
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement