3 ZIPS, What Order?: Write a program named ZipOrder that the reads in three zip
ID: 3727663 • Letter: 3
Question
3 ZIPS, What Order?: Write a program named ZipOrder that the reads in three zip codes from standard input and prints to standard output one of three words: "ASCENDING", "DESCENDING", "UNSORTED". The zip codes are guaranteed to be distinct from each other. In particular: if each zip code read in is greater than to the previous one, "ASCENDING" is printed. if each zip code read in is less than to the previous one, "DESCENDING" is printed. otherwise, "UNSORTED" is printed. The program accomplishes this by reading the zip codes and passing them as arguments to a method named direction. This method returns a string ("ASCENDING", "DESCENDING", or "UNSORTED") that the program prints out. The function carries out the zip code order logic. CONSTRAINT: You must define and use the method direction.
Explanation / Answer
Hi.. I have written program for the above. Please check below code.
ZipOrder.java
import java.util.Scanner;
public class ZipOrder {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int n = 0;
System.out.println("Enter number of zipcodes to be entered: ");
n = input.nextInt();
long array[] = new long[n];
System.out.println("Enter zipcodes:");
for(int i=0;i<n;i++){
String zip = input.next();
array[i] = Long.parseLong(zip);
}
String path="ascending";
direction(array,path);
path="descending";
direction(array,path);
path="unsorted";
direction(array,path);
}
private static void direction(long[] array, String path) {
// TODO Auto-generated method stub
int n = array.length;
if(path.equalsIgnoreCase("ascending")){
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (array[i] > array[j])
{
long temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
System.out.print("Ascending Order:");
}else if(path.equalsIgnoreCase("descending")){
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (array[i] < array[j])
{
long temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
System.out.print("Descending Order:");
}else{
System.out.print("Unsorted Order:");
}
for (int i = 0; i < n - 1; i++)
{
System.out.print(array[i] + ",");
}
System.out.print(array[n - 1]+" ");
}
}
Output:Enter number of zipcodes to be entered:
5
Enter zipcodes:
344553
123457
536161
234533
987865
Unsorted Order:344553,123457,536161,234533,987865
Ascending Order:123457,234533,344553,536161,987865
Descending Order:987865,536161,344553,234533,123457
Please test the code and let me know any issues. Thank you. All the best.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.