Question

In: Computer Science

Searching an Array for an Exact Match in Java Summary In this lab, you use what...

Searching an Array for an Exact Match in Java

Summary

In this lab, you use what you have learned about searching an array to find an exact match to complete a partially prewritten Java program. The program uses an array that contains valid names for 10 cities in Michigan. You ask the user of the program to enter a city name; your program then searches the array for that city name. If it is not found, the program should print a message that informs the user the city name is not found in the list of valid cities in Michigan. The data file provided for this lab includes the input statements and the necessary variable declarations. You need to use a loop to examine all the items in the array and test for a match. You also need to set a flag if there is a match, and then test the flag variable to determine if you should print the "Not a city in Michigan" message. Comments in the code tell you where to write your statements.

Instructions

  1. Study the prewritten code to make sure you understand it.
  2. Write a loop statement that examines the names of cities stored in the array.
  3. Write code that tests for a match.
  4. Write code that, when appropriate, prints the message: "Not a city in Michigan.".
  5. Execute the program using the following as input:
Chicago
Brooklyn
Watervliet
Acme

Grading

When you have completed your program, click the Submit button to record your score.

// MichiganCities.java - This program prints a message for invalid cities in Michigan.

// Input: Interactive.

// Output: Error message or nothing.


import java.util.Scanner;

public class MichiganCities

{

public static void main(String args[]) throws Exception

{

// Declare variables.

String inCity; // name of city to look up in array.

// Initialized array of cities in Michigan.

String citiesInMichigan[] = {"Acme", "Albion", "Detroit", "Watervliet", "Coloma", "Saginaw", "Richland", "Glenn", "Midland", "Brooklyn"};

boolean foundIt = false; // Flag variable.

int x; // Loop control variable.

// Get user input.

Scanner input = new Scanner(System.in);

System.out.println("Enter the name of the city: ");

inCity = input.nextLine();

// Write your loop here.

// Write your test statement here to see if there is

// a match. Set the flag to true if city is found.

}

// Test to see if city was not found to determine if

// "Not a city in Michigan" message should be printed.

System.exit(0);


} // End of main() method.

} // End of MichiganCities class.

Solutions

Expert Solution

CODE:

import java.util.Scanner;

public class MichiganCities {

    public static void main(String args[]) throws Exception {

        // Declare variables.

        String inCity; // name of city to look up in array.

        // Initialized array of cities in Michigan.

        String citiesInMichigan[] = { "Acme", "Albion", "Detroit", "Watervliet", "Coloma", "Saginaw", "Richland",

                "Glenn", "Midland", "Brooklyn" };

        boolean foundIt = false; // Flag variable.

        int x; // Loop control variable.

        // Get user input.

        Scanner input = new Scanner(System.in);

        System.out.println("Enter the name of the city: ");

        inCity = input.nextLine();

        // Write your loop here.

        boolean flag = false;

        for (x = 0; x < citiesInMichigan.length; x++) {

            if (citiesInMichigan[x].equals(inCity)) {

                foundIt = true;

                break;

            }

        }

        // Write your test statement here to see if there is

        // a match. Set the flag to true if city is found.

        if (foundIt == false)

            System.out.println("Error: City not found");

        // Test to see if city was not found to determine if

        // "Not a city in Michigan" message should be printed.

        System.exit(0);

    } // End of main() method.

} // End of MichiganCities class.

OUTPUT:

Please upvote if you like my answer and comment below if you have any queries or need any further explanation.


Related Solutions

n this lab, you use what you have learned about searching an array to find an...
n this lab, you use what you have learned about searching an array to find an exact match to complete a partially prewritten C++ program. The program uses an array that contains valid names for 10 cities in Michigan. You ask the user to enter a city name; your program then searches the array for that city name. If it is not found, the program should print a message that informs the user the city name is not found in...
Summary In this lab, you use a counter-controlled while loop in a Java program provided for...
Summary In this lab, you use a counter-controlled while loop in a Java program provided for you. When completed, the program should print the numbers 0 through 10, along with their values multiplied by 2 and by 10. The data file contains the necessary variable declarations and some output statements. Instructions Ensure the file named Multiply.java is open. Write a counter-controlled while loop that uses the loop control variable to take on the values 0 through 10. Remember to initialize...
Summary In this lab, you add the input and output statements to a partially completed Java...
Summary In this lab, you add the input and output statements to a partially completed Java program. When completed, the user should be able to enter a year, a month, and a day to determine if the date is valid. Valid years are those that are greater than 0, valid months include the values 1 through 12, and valid days include the values 1 through 31. Instructions Notice that variables have been declared for you. Write the simulated housekeeping() method...
Understanding if-elseStatements Summary In this lab, you will complete a prewritten Java program that computes the...
Understanding if-elseStatements Summary In this lab, you will complete a prewritten Java program that computes the largest and smallest of three integer values. The three values are –50, 53, and 78. Instructions Two variables named largest and smallest are declared for you. Use these variables to store the largest and smallest of the three integer values. You must decide what other variables you will need and initialize them if appropriate. Write the rest of the program using assignment statements, if...
Summary In this lab, you complete a prewritten Java program that calculates an employee’s productivity bonus...
Summary In this lab, you complete a prewritten Java program that calculates an employee’s productivity bonus and prints the employee’s name and bonus. Bonuses are calculated based on an employee’s productivity score as shown below. A productivity score is calculated by first dividing an employee’s transactions dollar value by the number of transactions and then dividing the result by the number of shifts worked. Productivity Score Bonus <=30 $50 31–69 $75 70–199 $100 >= 200 $200 Instructions Ensure the file...
In this lab, you will practice the use of array by building an simple maze game,...
In this lab, you will practice the use of array by building an simple maze game, where your task is to control the prince to defeat the monster and save Snow White. You have to work based on the given skeleton code. Game Description The Snow White is detained in the maze by the monster, who needs the prince's help to rescure her out from the exit. The pre-set maze is shown below, with width 11 and height 8. The...
In this lab, you will practice the use of array by building an simple maze game,...
In this lab, you will practice the use of array by building an simple maze game, where your task is to control the prince to defeat the monster and save Snow White. You have to work based on the given skeleton code. Game Description The Snow White is detained in the maze by the monster, who needs the prince's help to rescure her out from the exit. The pre-set maze is shown below, with width 11 and height 8. The...
For Java 3.25 LAB: Exact change Write a program with total change amount in pennies as...
For Java 3.25 LAB: Exact change Write a program with total change amount in pennies as an integer input, and output the change using the fewest coins, one coin type per line. The coin types are Dollars, Quarters, Dimes, Nickels, and Pennies. Use singular and plural coin names as appropriate, like 1 Penny vs. 2 Pennies. Ex: If the input is: 0 the output is: No change Ex: If the input is: 45 the output is: 1 Quarter 2 Dimes...
In this Java lab, you use the flowchart and pseudocode found in the figure below to...
In this Java lab, you use the flowchart and pseudocode found in the figure below to add code to a partially created Java program. When completed, college admissions officers should be able to use the Java program to determine whether to accept or reject a student, based on his or her test score and class rank. Declare the variables testScoreString and classRankString. Write the interactive input statements to retrieve: A student’s test score (testScoreString) A student's class rank (classRankString) Write...
JAVA Lab Assignment #13:  Looping Lab with both types of loops. This lab demonstrates the use of...
JAVA Lab Assignment #13:  Looping Lab with both types of loops. This lab demonstrates the use of the While Loop and the Do While Loop as error checking mechanisms. You will be using each of these loops to solve the same problem. Please put them both in the same program. When you test the code, you will not see a difference in the way they execute - but there will be a difference in the logic when writing the code. You...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT