In: Computer Science
Write a Java program that reads a list of 30 fruits from the file “fruits.txt”, inserts them into a string array, and sorts the array in alphabetical order. String objects can be compared using relational operators such as <, >, or ==. For example, “abc” > “abd” is false, but “abc” < “abd” is true. Sample output: Before Sorting: Cherry, Honeydew, Cranberry, Lemon, Orange, Persimmon, Watermelon, Kiwifruit, Lime, Pomegranate, Jujube, Pineapple, Durian, Plum, Banana, Coconut, Apple, Tomato, Raisin, Mandarine, Blackberry, Raspberry, Peach, Mango, Melon, Grape, Strawberry, Blueberry, Pear, Avocado After Sorting: Apple, Avocado, Banana, Blackberry, Blueberry, Cherry, Coconut, Cranberry, Durian, Grape, Honeydew, Jujube, Kiwifruit, Lemon, Lime, Mandarine, Mango, Melon, Orange, Peach, Pear, Persimmon, Pineapple, Plum, Pomegranate, Raisin, Raspberry, Strawberry, Tomato, Watermelon
Fruit.txt:
Cherry Honeydew Cranberry Lemon Orange Persimmon Watermelon Kiwifruit Lime Pomegranate Jujube Pineapple Durian Plum Banana Coconut Apple Tomato Raisin Mandarine Blackberry Raspberry Peach Mango Melon Grape Strawberry Blueberry Pear Avocado
Code:
=====
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class SortFruits {
public static void main(String[] args) throws
FileNotFoundException {
Scanner sc = new Scanner(new
File("fruits.txt"));
String[] fruits = new
String[30];
int i=0;
while(sc.hasNextLine()) {
fruits[i] =
sc.nextLine().trim();
i++;
}
System.out.println("Fruits before
soring: ");
for(String fruit : fruits) {
System.out.print(fruit+", ");
}
String temp="";
for(i=0; i<30; i++) {
for(int j=0;
j<30; j++) {
if(fruits[i].compareTo(fruits[j])<0) {
temp = fruits[j];
fruits[j] = fruits[i];
fruits[i] = temp;
}
}
}
System.out.println("\n\nFruits
after soring: ");
for(String fruit : fruits) {
System.out.print(fruit+", ");
}
sc.close();
}
}
output:
=====