Проблема вызова метода Java, возвращение в главное меню из нового класса .java, возможная проблема с массивом - PullRequest
0 голосов
/ 30 июня 2019

Сначала я прошу прощения за все вопросы, но я в растерянности и провел последнюю неделю, работая над этим.Я новичок в сообществе, поэтому, пожалуйста, работайте со мной, пока я изучаю формат, который мне нужен.

Хорошо, я работаю над своим окончательным проектом для класса, и мне дали справочный документ и два файла .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

Это мои места обитания. Текст:

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

Ответы [ 2 ]

0 голосов
/ 01 июля 2019

Вот пример выбора некоторых меню и подменю

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());
    }
}
0 голосов
/ 30 июня 2019

Это у вас работает?

Monitor.java


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");
                break;

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

                methodCall.askForWhichDetails("habitats");

                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;
    }
}

AnimalsHabitat.java

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
            {
                while(option != (i + 1))
                {
                    System.out.print("Enter selection or enter " + (i + 1) + " to exit: ");
                    option = scnr.nextInt();

                    System.out.println("");

                    if (option <= i)
                    {
                        String detailOption = aList1.remove(option - 1).toString();
                        showData(fileName, detailOption);
                    }
                }
                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.
    }
}

Пример выполнения

javac AnimalsHabitat.java Monitor.java && java Monitor
...