简体   繁体   English

在 Java 中使用二维数组和 try/catch 语句进行编程

[英]Program using 2D array and try/catch statement in Java

I just started an intro to Java college course and the HW is really throwing me.我刚开始介绍 Java 大学课程,HW 真的让我大吃一惊。 I've spent tens of hours pouring over tutorials, the textbook, videos, and Stack Overflow answers and am still struggling with this assignment.我花了几十个小时来翻阅教程、教科书、视频和 Stack Overflow 的答案,但我仍在为这项任务苦苦挣扎。 I've got a lot of the base code done...I think...but it is still far from executable.我已经完成了很多基本代码......我认为......但它仍然远非可执行。 I don't even know what I'm doing right so it's hard to figure anything else out.我什至不知道我在做什么正确,所以很难弄清楚其他任何事情。

This is what the assignment is asking for:这是作业要求的:

-Two dimensional array hard coded with distances between the listed 7 major US cities - 二维数组硬编码列出的 7 个美国主要城市之间的距离

-Single-dimension array hard coded with the names of the 7 cities - 用 7 个城市的名称硬编码的一维数组

-Method in the base class and outside of main() that prompts the user to enter a departure city and a destination city - 基础 class 和 main() 之外的方法,提示用户输入出发城市和目的地城市

-Method that searches in the array of cities for both departure name and destination name and display the distance between the two if found - 在城市数组中搜索出发地名称和目的地名称并显示两者之间距离的方法

-Method that prompts the user to enter the price per gallon of gas, and the MPG - 提示用户输入每加仑汽油价格和 MPG 的方法

-Method that uses a TRY/CATCH to validate numeric input - 使用 TRY/CATCH 验证数字输入的方法

-Method that calculates the cost of a round trip between departure and destination city -计算出发地和目的地城市之间往返费用的方法

-Method that outputs information about the trip and allow user to repeat for other trips as desired - 输出有关行程的信息并允许用户根据需要重复其他行程的方法

This is what I'm stuck on:这就是我坚持的:

-Calling methods outside of the main method into the main method - 将主方法外的方法调用到主方法中

-How to assign the single array as the 2d array index and use the user input to search the index for the point of intersection (distance) then use that value for future calculations. -如何将单个数组指定为二维数组索引并使用用户输入搜索交叉点(距离)的索引,然后将该值用于将来的计算。 Reference photo: table of cities and distances参考照片:城市和距离表

-How to return "Cities not found" if the user inputs cities not on the array index -如果用户输入的城市不在数组索引上,如何返回“未找到城市”

-How to code a method to calculate the cost of the trip (I'm pretty sure I can figure this one out on my own once I figure out how to work with the array/index and assign those values to variables) -如何编写一种计算旅行成本的方法(我很确定一旦我弄清楚如何使用数组/索引并将这些值分配给变量,我就可以自己解决这个问题)

Here is the code I've got so far:这是我到目前为止的代码:

import java.util.*;

package com.mycompany.milagecalculator;

/* 
Program to calculate milage between two cities 
*/


public class MilageCalculator {
                
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        
        //declare 2D array
        String[][] cityDistances = {
                             {"0", "983", "787", "714", "1375", "967", "1087"},
                             {"983", "0", "214", "1102", "1763", "1723", "1842"},
                             {"787", "214", "0", "888", "1549", "1548", "1627"},
                             {"714", "1102", "888", "0", "661", "781", "810"},
                             {"1375", "1723", "1549", "661", "0", "1426", "1187"},
                             {"967", "1723", "1548", "781", "1426", "0", "239"},
                             {"1087", "1842", "1627", "810", "1187", "239", "0"}
            };
         
        //Declare single array for 2D array index
        String[] city = new String[7];
        
        //initialize array
        city[0] = "Chicago";
        city[1] = "Boston";
        city[2] = "New York";
        city[3] = "Atlanta";
        city[4] = "Miami";
        city[5] = "Dallas";
        city[6] = "Houston";
    }  
    
           
        //method that gets user input for departure and destination cities
        public static void userInput(String[] args){
     
            System.out.print("Please enter a departure city:");
            String departure = sc.next();
        
            System.out.print("Please enter a destination city: ");
            String destination = sc.next();
      }
     
        /*method that searches in the array of cities for both 
        departure name and destination name, then returns the 
        distance between them if found */
         public static void tripDistance(String[] args){/*???*/
        }
      
         //Method that gets user input for the cost per gallon for gas and mpg on their vehicle
         public static void mpgCalculator(String[] args){
            System.out.print("How much, in dollars, is a gallon of gas? ");
            Double gallonGas = Double.parseDouble(sc.next());
        
            //Get user input for the cost per gallon for gas
            System.out.print("How many miles per gallon does your car get? ");
            Double mpg = Double.parseDouble(sc.next());
            
             // see if the user wants to continue
            choice = getChoiceString(sc, "Would you like to calculate tha milage between two more cities? (y/n): ", "y", "n");
            System.out.println();      
        }
    
        //method that uses try/catch to validates numeric input for MPG and cost of gas
        public static double getDouble(Scanner sc, String prompt) {
            while (true) {
            System.out.print(prompt);
            try {
                double value = Double.parseDouble(sc.nextLine());
                return value;
            } 
            catch (NumberFormatException e) {
                System.out.println(
                        "Error! Invalid input. Must input valid positive decimal number. Please try again.");
                }
            }
        }
     
        //Method that calculates the cost of a trip based on user input 
        public static /*?double?*/ tripCost () { /*need to figure out how to assign array 
                                                     intersection to variable first*/
        }
        
        /*
        Method that outputs the trip information and asks if the user 
        wants to calculate another trip
       */
        public static double tripCalculator(Double[] args){
            String choice = "y";
              
            while (choice.equalsIgnoreCase("y")) {
                System.out.print("The distance between " + departure + " and " + destination + " is " + distance + " miles.");
                   
                System.out.print("At $" + gallonGas + " a gallon, the cost of the trip will be $" + /*use calculation from tripCost method*/ + "." );
                 Double mpg = Double.parseDouble(sc.next());
            
                // see if the user wants to continue
                choice = getChoiceString(sc, "Would you like to calculate the cost of a trip between two more cities? (y/n): ", "y", "n");
                System.out.println();  
            }
        }
}

Thank you for any help you can provide.感谢您提供任何帮助。 I'm trying really hard to figure the concepts out myself but I am just so lost:(我正在努力自己弄清楚这些概念,但我迷路了:(

You need to understand the relationship between the cities[] array and the cityDistances[][] array.您需要了解 city[ cities[]数组和cityDistances[][]数组之间的关系。 To start, a Two Dimensional (2D) Array in Java is an Array of Arrays.首先,Java 中的二维 (2D) 数组是 Arrays 的数组。 A way to look at this could be more like a table of Rows and Columns where the outer array depicts the Rows and the inner arrays depict the columns for each of those rows.看待这一点的方法可能更像是一个行和列的表,其中外部数组描述行,内部 arrays 描述每一行的列。 The Cities within the city[] array is laid out in a specific order which should never be be changed because they directly related to each row of the cityDistances[][] array. city[]数组中的 Cities 以特定顺序排列,该顺序不应更改,因为它们与cityDistances[][]数组的每一行直接相关。

Take the first inner array (row) of the cityDistances[][] array:cityDistances[][]数组的第一个内部数组(行):

{"0", "983", "787", "714", "1375", "967", "1087"}

Each distance value element is related to a city within the city[] array in the order of that array.每个距离值元素都按该数组的顺序与city[]数组中的一个城市相关。 The "0" means Chicogo , "983" is the distance from Chicogo to Boston , "787" is the distance from Chicogo to New York , "714" is the distance from Chicogo to Atlanta , and so forth. “0”表示芝加哥,“983”是芝加哥波士顿的距离,“787”是芝加哥纽约的距离,“714”是芝加哥亚特兰大的距离,以此类推。 Here is another way to look at it:这是另一种看待它的方式:

{   "0",      "983",    "787",      "714",   "1375",   "967",    "1087"}    
{"Chicago", "Boston", "New York", "Atlanta", "Miami", "Dallas", "Houston"}

Now, take the second inner array (row) of the cityDistances[][] array:现在,取cityDistances[][]数组的第二个内部数组(行):

{"983", "0", "214", "1102", "1763", "1723", "1842"}

Note where the "0" is.注意“0”在哪里。 This is for the next element within the city[] array which is Boston .这是针对city[]数组中的下一个元素Boston This "0" indicates where Boston is so, the distance between Chicogo and Boston is "983".这个“0”表示波士顿在哪里,芝加哥波士顿的距离是“983”。 Remember, the elemental values within each Row (inner array) of the cityDistances[][] array are related to the Cities contained within the city[] array:请记住, cityDistances[][]数组的每一行(内部数组)中的元素值与city[] [] 数组中包含的 Cities 相关:

{  "983",     "0",      "214",     "1102",   "1763",  "1723",    "1842"}
{"Chicago", "Boston", "New York", "Atlanta", "Miami", "Dallas", "Houston"}

Once you understand this correlation between the two arrays, determining distances is relatively easy.一旦您了解了两个 arrays 之间的这种相关性,确定距离就相对容易了。

Read the extensive comments within the runnable code below:阅读以下可运行代码中的大量注释:

/* 
    Program to calculate milage between two cities 
*/
public class MilageCalculator {

    /* Class Member Variables. These variables are class global
       which makes them available to all methods within the class. 
    */
    
    private final java.util.Scanner input = new java.util.Scanner(System.in);
    
    private final String[][] cityDistances = {
            {"0", "984", "790", "691", "1353", "926", "1074"},
            {"984", "0", "217", "1062", "1502", "1723", "1842"},
            {"790", "217", "0", "888", "1549", "1548", "1627"},
            {"691", "1062", "888", "0", "661", "781", "810"},
            {"1353", "1502", "1549", "661", "0", "1426", "967"},
            {"926", "1723", "1548", "781", "1426", "0", "239"},
            {"1074", "1842", "1627", "810", "967", "239", "0"}
        };
    
    private final String[] city = {"Chicago", "Boston", "New York", 
                                   "Atlanta", "Miami", "Dallas", 
                                   "Houston"}; 
    
    private String departure = "";          // Holds departure city.
    private String destination = "";        // Holds destination city.
    private int tripDistanceInMiles = 0;    // Holds the distance in mile between the two cities.
    private double priceOfGallonGas = 0.0d; // Holds the price per gallon of gas.
    private double milesPerGallon = 0.0d;   // Holds the vehicle miles per gallon.
    private double fuelCostForTrip = 0.0d;  // Holds the determined fuel cost for trip.
    
    
    // Application entry point.
    public static void main(String[] args) {
        // App started this way to avoid the need for statics.
        new MilageCalculator().startApp(args);
    }

    // Starts the ball rolling...
    private void startApp(String[] args) {
        /* Keep looping the application until 'n' is supplied
           in the getChoiceString() method.        */
        String yn = "y";
        while (yn.equalsIgnoreCase("y")) {
            userInput();                        // Get all the required User Input.
            System.out.println();               // Blank line
            yn = getChoiceString();             // Ask to check another Departure/Destination.
        }
        System.out.println("Bye-Bye");          // 'n' was supplied.
    }

    //method that gets user input for departure and destination cities
    public void userInput() {
        String dept = "";
        while (dept.isEmpty()) {
            System.out.print("Please enter a departure city:   -> ");
            dept = input.nextLine().trim();
            // Validate the Departure entry...
            if (dept.isEmpty() || !doesCityExist(dept)) {
                System.out.println("Invalid Entry! The supplied departure city");
                System.out.println("(" + dept + ") does not exist within the list!");
                System.out.println();
                dept = "";
            }
        }
        departure = dept;
        
        String dest = "";
        while (dest.isEmpty()) {
            System.out.print("Please enter a destination city: -> ");
            dest = input.nextLine().trim();
            // Validate the Destination entry...
            if (dept.isEmpty() || !doesCityExist(dest)) {
                System.out.println("Invalid Entry! The supplied destination city");
                System.out.println("(" + dest + ") does not exist within the list!");
                System.out.println();
                dest = "";
            }
        }
        destination = dest;
        
        // Get the trip distance from Arrays data...
        getTripDistance();
        
        // Acquire the fuel cost to make the trip.
        fuelCostCalculator();
        
        // Display the gathered information n Console Window.
        System.out.println();
        tripCalculator();
    }
    
    // Checks to see if a supplied City exists.
    private boolean doesCityExist(String dCity) {
        for (String str : city) {
            if (str.equalsIgnoreCase(dCity)) {
                return true;
            }
        }
        return false;
    }

    /**
       Method that searches in the array of cities for both departure name and 
       destination name. Places the determined distance between them within the 
       tripDistanceInMiles class member variable.     
      
       You need to understand the relationship between the cities[] array and
       the cityDistances[][] array. To start, a Two Dimensional (2D) Array in
       Java is an Array of Arrays. A way to look at this could be more like a 
       table of Rows and Columns where the outer array depics the Rows and the 
       inner arrays depic the columns for each of those rows. The Cities within 
       the city[] array is layed out in a specific order which should never be
       be changed because they directly relate to each row of the cityDistances[][] 
       array. 
    
       Take the first inner array (row) of the cityDistances[][] array:
    
          {"0", "983", "787", "714", "1375", "967", "1087"}
    
       Each distance value element is related to a city within the city[] array 
       in the order of that array. The "0" means 'Chicogo', "983" is the distance 
       from 'Chicogo' to 'Boston', "787" is the distance from 'Chicogo' to 
       'New York', "714" is the distance from 'Chicogo' to 'Atlanta', and so 
       forth. Here is another way to look at it:
        
       {   "0",      "983",    "787",      "714",   "1375",   "967",    "1087"}    
       {"Chicago", "Boston", "New York", "Atlanta", "Miami", "Dallas", "Houston"}
    
       Now, take the second inner array (row) of the cityDistances[][] array:
    
          {"983", "0", "214", "1102", "1763", "1723", "1842"}
    
       Note where the "0" is. This is for the next element within the city[] 
       array which is 'Boston'. This "0" indicates where 'Boston' is so, the 
       distance between 'Chicogo' and 'Boston' is "983". Remember, the elemental 
       values within each Row (inner array) of the cityDistances[][] array are 
       related to the Cities contained within the city[] array:
    
       {  "983",     "0",      "214",     "1102",   "1763",  "1723",    "1842"}
       {"Chicago", "Boston", "New York", "Atlanta", "Miami", "Dallas", "Houston"}
    
       Once you understand this correlation between the two arrays, determining 
       distances is relatively easy.
    */
    private void getTripDistance() {
        int cityDistancesRowIndex = 0;      // Will Hold the Row index  
        int cityDistancesColumnIndex = 0;   // Will Hold the Column Index
        
        /* Iterate through the city[] array to find the 
           departure City so as to get its index value
           which will be used to get the Inner array row
           of the cityDistances[][] array. */
        for (int i = 0; i < city.length; i++) {
            if (departure.equalsIgnoreCase(city[i])) {
                departure = city[i]; // To ensure same letter case as in city[] array
                cityDistancesRowIndex = i;
                /* Iterate through the city[] array again to find the 
                   destination City so as to get its index value which 
                   will be used to get the Inner array Column of the 
                   cityDistances[][] array.        */
                for (int j = 0; j < city.length; j++) {
                    if (destination.equalsIgnoreCase(city[j])) {
                        destination = city[j]; // To ensure same letter case as in city[] array
                        cityDistancesColumnIndex = j;
                        break;  // Got what we need, break out of inner loop.
                    }
                }
                break;  // Got all what we need, break out of oter loop.
            }
        }
        /* Now that we have the required Row/Column index 
           values related to the departure and destination
           cities, we can grab the distance that is contained
           within the cityDistances[][] array        */
        int distance = Integer.parseInt(cityDistances[cityDistancesRowIndex][cityDistancesColumnIndex]);
        
        /* Supply the acquired distance to the tripDistanceInMiles 
           member for use anywhere.        */
        tripDistanceInMiles = distance;
    }

    /* A method that gets User's input for the cost per gallon of gas 
       and Miles Per Gallon (mpg) on their vehicle.      */
    private void fuelCostCalculator() {
        //Get User input for the cost per gallon of gas.
        priceOfGallonGas = getDouble("How much, in dollars, is a gallon of gas? -> ");

        //Get User input for MPG
        milesPerGallon = getDouble("How many miles per gallon does your car get? -> ");
        
        // Calculate the estimated fuel cost.
        fuelCostForTrip = ((tripDistanceInMiles / milesPerGallon) * priceOfGallonGas);
    }

    // Validates numeric input for MPG and cost of gas
    private double getDouble(String prompt) {
        String value = "";
        while (value.isEmpty()) {
            System.out.print(prompt);
            value = input.nextLine().trim();
            /* Validate the supplied value. The String.matches() method
               is used here for that with a small Regular Expression that
               will supply boolean true if an unsigned (positive) integer
               ot floating point string numerical value is supplied (Integer 
               values will automatically be converted to double type).    */
            if (!value.matches("\\d+(\\.\\d+)?")) {
                System.out.println("Error! Invalid Entry! (" + value + ") - You Must input");
                System.out.println("a valid positive decimal number. Please try again.");
                System.out.println();
                value = "";   // Empty value so to re-loop.
            }
        }
        
        /* Convert String numerical value to double type and return.
           Because value passed validation, we're not going to have 
           problem doing the convertion.        */
        return Double.parseDouble(value); 
    }

    private String getChoiceString() {
        String yn = "";
        while (yn.isEmpty()) {
            System.out.println("Would you like to calculate tha milage");
            System.out.print("between two more cities? (y/n): -> ");
            yn = input.nextLine();
            // Validate input...
            if (!yn.matches("[yn]")) {
                System.out.println("Invalid Entry! (" + yn + ") - Try again...");
                System.out.println();
                yn = ""; // Empty yn so to re-loop
            }
        }
        System.out.println();
        return yn;
    }

    /* Method that outputs the trip information     */
    private void tripCalculator() {
            System.out.println("The distance between " + departure + " and " 
                             + destination + " is " + tripDistanceInMiles 
                             + " miles.");

            System.out.println("At $" + priceOfGallonGas + " a gallon, the cost of "
                           + "the trip will be $" + String.format("%.2f", fuelCostForTrip) 
                           + ".");
    }
    
}

On a Side: Double check the distances contained within the cityDistances[][] Array.另一方面:仔细检查cityDistances[][]数组中包含的距离。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM