首页 > 解决方案 > Java 方法调用问题,从新的 .java 类返回主菜单,可能存在数组问题

问题描述

首先,我很抱歉所有的问题,但我很茫然,上周一直在努力解决这个问题。我是社区的新手,所以请在我学习我需要的格式时与我一起工作。

好的,所以我正在为一个班级做我的最后一个项目,我得到了一个帮助文档和两个 .txt 文件。我在正确的级别上有 .txt 文件,可以从任何计算机调用它们。我还把我的代码放到了它调用正确数组的地方,以便在从主菜单中选择后出现一个新的子菜单。从那里我在调用方法(showdata)时遇到问题,弹出一个带有警报的 JOptionPane,如果从 .txt 文件中调用它,则必须显示该警报,即它前面将有(*****)其中。我还必须为用户添加一个返回主菜单的选项,而不是仅仅关闭程序,但我不确定我可以把这个选项放在哪里。我不知道是否应该将它添加到默认循环或我的 switch 语句中。任何帮助都会很棒。非常感谢。

我现在在下面包含了我的 .txt 文件。

我的主要代码是:import java.util.Scanner;

public class Monitor {

    private static Scanner usrch = new Scanner(System.in);

    /**
     *
     * @param args
     */
    public static void main(String[] args) {

    AnimalsHabitat methodCall = new AnimalsHabitat();

    try {

        int userChoice = mainMenu();

        switch(userChoice) {
            case 1:
                System.out.println("Please pick the animal you would like to monitor: ");
                System.out.println("");

                methodCall.askForWhichDetails("animals");

                System.out.println("Press 0 to go back.");

                break;

            case 2:
                System.out.println("Please pick the habitat you would like to monitor: ");
                System.out.println("");

                methodCall.askForWhichDetails("habitats");

                System.out.println("Press 0 to go back.");

                break;

            case 3:
                System.out.println("Have a nice day!");
                System.exit(0);

                break;

            default:
                int loopError = 0;

                while (loopError < 3) {
                    loopError++;

                    if (loopError == 3) {
                        System.out.println("Error in program loop, exiting program.");
                        System.exit(0);
                    }
                } 
            }
        }
        catch (Exception e) {
            System.out.println("Wrong input " + e.getMessage());
        }
    }

    public static int mainMenu() {

        System.out.println("Welcome to the Zoo Monitoring System!");
        System.out.println("Please select what you would like to monitor: ");
        System.out.println("");
        System.out.println("1.) Animals");   
        System.out.println("2.) Habitats");   
        System.out.println("3.) Exit program");
        int userChoice = Integer.parseInt(usrch.nextLine());
        return userChoice;
    }
}

我的帮助代码是:

import java.util.Scanner;
import java.io.IOException;
import java.io.FileInputStream;
import java.util.ArrayList;
import javax.swing.JOptionPane;

public class AnimalsHabitat {

    private String filePath;
    final private Scanner scnr;

    public AnimalsHabitat() {
        filePath = "";
        scnr = new Scanner(System.in);
    }

    public void askForWhichDetails(String fileName) throws IOException {
        FileInputStream fileByteStream = null; // File input stream
        Scanner inFS = null;                   // Scanner object

        String textLine = null;
        ArrayList aList1 = new ArrayList();

        int i = 0;
        int option = 0;

        boolean bailOut = false;

        // Try to open file
        fileByteStream = new FileInputStream(filePath + fileName + ".txt");
        inFS = new Scanner(fileByteStream);

        while (inFS.hasNextLine() && bailOut == false) {
            textLine = inFS.nextLine();

            if (textLine.contains("Details")) {
                i += 1;
                System.out.println(i + ". " + textLine);

                ArrayList aList2 = new ArrayList();

                for (String retval : textLine.split(" ")) {
                    aList2.add(retval);
                }

                String str = aList2.remove(2).toString();
                aList1.add(str);
            } else {
                System.out.print("Enter selection: ");
                option = scnr.nextInt();

                System.out.println("");

                if (option <= i) {
                    String detailOption = aList1.remove(option - 1).toString();
                    showData(fileName, detailOption);

                    bailOut = true;
                }

                break;
            }
        }

        // Done with file, so try to close it
        fileByteStream.close(); // close() may throw IOException if fails  
    }

    public void showData(String fileName, String detailOption) throws IOException {
        FileInputStream fileByteStream = null; // File input stream
        Scanner inFS = null;                   // Scanner object      

        String textLine = null;
        String lcTextLine = null;
        String alertMessage = "*****";

        int lcStr1Len = fileName.length();
        String lcStr1 = fileName.toLowerCase().substring(0, lcStr1Len - 1);

        int lcStr2Len = detailOption.length();
        String lcStr2 = detailOption.toLowerCase().substring(0, lcStr2Len - 1);

        boolean bailOut = false;

        // Try to open file
        fileByteStream = new FileInputStream(filePath + fileName + ".txt");
        inFS = new Scanner(fileByteStream);

        while (inFS.hasNextLine() && bailOut == false) {
            textLine = inFS.nextLine();
            lcTextLine = textLine.toLowerCase();

            if (lcTextLine.contains(lcStr1) && lcTextLine.contains(lcStr2)) {
                do {
                    System.out.println(textLine);

                    textLine = inFS.nextLine();
                    if (textLine.isEmpty()) {
                        bailOut = true;
                    }

                    if (textLine.contains(alertMessage)) {
                        JOptionPane.showMessageDialog(null, textLine.substring(5));
                    }

                } while (inFS.hasNextLine() && bailOut == false);
            }
        }

        // Done with file, so try to close it
        fileByteStream.close(); // close() may throw IOException if fails      
    }

    void showData() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}

这是我的动物.txt

Details on lions
Details on tigers
Details on bears
Details on giraffes

Animal - Lion
Name: Leo
Age: 5
*****Health concerns: Cut on left front paw
Feeding schedule: Twice daily

Animal - Tiger
Name: Maj
Age: 15
Health concerns: None
Feeding schedule: 3x daily

Animal - Bear
Name: Baloo
Age: 1
Health concerns: None
*****Feeding schedule: None on record

Animal - Giraffe
Name: Spots
Age: 12
Health concerns: None
Feeding schedule: Grazing

这是我的habits.txt:

Details on penguin habitat
Details on bird house
Details on aquarium

Habitat - Penguin
Temperature: Freezing
*****Food source: Fish in water running low
Cleanliness: Passed

Habitat - Bird
Temperature: Moderate
Food source: Natural from environment
Cleanliness: Passed

Habitat - Aquarium
Temperature: Varies with output temperature
Food source: Added daily
*****Cleanliness: Needs cleaning from algae

标签: javaclassmethodsjoptionpane

解决方案


这是一些菜单和子菜单选择的示例

package com.hnb;

public class Monitor {

    public Monitor(FileParser fileParser) {
        final Menu main = new Menu(fileParser.getOptions());
        System.out.println("Welcome to the Zoo Monitoring System!");

        MenuSelection selection = null;
        Selection subselection = null;

        do {
            selection = main.displaySubMenu();
            if(selection.isValid()){
                do {
                    final Menu submenu = new Menu(selection.getSelection());
                    subselection = submenu.display();
                    if (subselection.isValid()) {
                        final Monitorable item = (Monitorable) subselection.getSelection();
                        System.out.println(item);
                        item.showAsterisk();
                    }
                } while (!subselection.isExit());
            }
        } while (!selection.isExit());
    }

    public static void main(String[] args) {
        new Monitor(new FileParser());
    }
}

推荐阅读