Please help, I\'d like to write a Java program that prompts the user for a list
ID: 3868204 • Letter: P
Question
Please help, I'd like to write a Java program that prompts the user for a list of words ("quit" to end the list), the prints the list in sorted order. You may use either selection sort or insertion sort.
*/ Please DO NOT use
import java.util.ArrayList;
import java.util.Collections;
I have yet to learn this and do not understand it. I also have not learned private class. */
My code:
import java.util.Scanner;
public class Lab15 {
public static void main(String[] args) {
System.out.println("Enter a list of words (enter 'quit' to quit) : ");
Scanner in = new Scanner(System.in);
String word = in.nextLine();
String[] list = new String[word];
do {
word = in.nextLine();
}while (!word.equals("quit"));
sortedList(list);
for (int i = 0; i < list.length; i++) {
System.out.println(list[i]);
}
in.close();
}
//insertion sort
public static void sortedList(String[] list ) {
String key;
for (int i = 0; i < list.length; ++i) {
key = list[i];
int j = i - 1;
if (j>i)
{
swap(list, i,j);
}
}
}
public static void swap(String[] list, int i, int j ) {
String pos=list[i];
list[i]=list[j];
list[j]=pos;
}
}
Explanation / Answer
Hi ,
we cannot simply use array to solve this problem. Because array size must be declared in the beginning and we dont know when user will enter the quit keyword. Because of variable size only we use ArrayList
Anyways, as you dont want to use ArrayList anywhere, I have done a workaround. I am concatening each word entered by user to a string. So after entering quit, the string will contain all the words saperated by space.
After that i am using split() function to convert string to array of strings i.e. words..
Let me know if you have any issue in this.
Below is your code: -
import java.util.Scanner;
public class Lab15 {
public static void main(String[] args) {
System.out.println("Enter a list of words (enter 'quit' to quit) : ");
Scanner in = new Scanner(System.in);
String word = in.nextLine();
String arr = "";
do {
arr = arr + word + " "; // adding each word to string to create one
// string of all words
word = in.nextLine();
} while (!word.equals("quit"));
String[] list = arr.split(" "); // splitting string to array
sortedList(list);
for (int i = 0; i < list.length; i++) {
System.out.println(list[i]);
}
in.close();
}
private static void sortedList(String[] list) {
int n = list.length;
for (int i = 0; i < n; ++i) {
String key = list[i];
int j = i - 1;
while (j >= 0 && list[j].compareTo(key) > 0) {
list[j + 1] = list[j];
j = j - 1;
}
list[j + 1] = key;
}
}
}
Sample Run: -
Enter a list of words (enter 'quit' to quit) :
a
small
string
to
test
all
parts
quit
a
all
parts
small
string
test
to