Write a program named CheckZips that is used by a package delivery service to check delivery areas.
The program contains an array that holds the 10 zip codes of areas to which the company makes deliveries. (Note that this array is created for you and does not need to be changed.)
Prompt a user to enter a zip code, and display a message indicating whether the zip code is in the company’s delivery area.
For example if the user enters a zip code in the array, such as 60007, the output should be Delivery to 60007 ok.
If the user enters a zip code not in the array, such as 60008, the output should be Sorry - no delivery to 60008.
CODE:
using static System.Console;
class CheckZips
{
static void Main()
{
string[] zips = {"12789", "54012", "54481", "54982", "60007",
"60103", "60187", "60188", "71244", "90210"};
// Write your main here
}
}
Answer
Here is your answer, here we can see the list of array values are given. Here we need a program that when user input one zip code, the program should search the array for check if the user input zip code is presented on the array. If it is occured we can print apropriate message for this. We can use different type of searching techinque such binary search and etc. But here i implemented linear search method. So here is the code for the above problem.
ChecZips.java
import java.util.Scanner;
class CheckZips
{
public static void main(String[] args)
{
String[] zips = {"12789", "54012", "54481","54982", "60007","60103", "60187", "60188", "71244","90210"};
Scanner in = new Scanner(System.in); //this is for user input, we need scanner object for getting the value from standard devices
System.out.println("Enter zip:");
String zip = in.nextLine();
int flag=0; //flag is used for avoid the printing multiple time sorry, and delivery msg.
for (int i=0;i<10;i++)
{
if(zips[i].compareTo(zip)==0) //java inbuit string comarison functions. compare user input with each element in the item.
{
flag=0; //if item occured in the array, it will display.
break;
}
else
{
flag=1;
}
}
if(flag==1)
{
System.out.println("Sorry - no delivery to "+zip+"\n");
}
else
{
System.out.println("Delivery to "+zip+" ok\n");
}
}
}
output
Any doubt please comment
Thanks in advance
Get Answers For Free
Most questions answered within 1 hours.