Как мне решить эту проблему во время зацикливания ошибки? - PullRequest
0 голосов
/ 10 ноября 2018

Я работаю над проектом, предложенным профессором информатики в моем университете. У меня его нет, но я подумал, что было бы неплохо попробовать. Целью проекта является завершение успешной сдачи в аренду книги и магазина компакт-дисков, отвечающих всем критериям.

Сейчас моя проблема находится в той части, где я должен дать пользователю возможность изменить существующую информацию о клиенте. В методе ModifyCustomer, который я определил, у меня довольно много вложенных циклов. Все работало без сбоев, пока мне не пришлось реализовать цикл do while для всего метода, чтобы пользователь мог снова при необходимости изменить существующую информацию о клиенте. Есть только два клиента. Всякий раз, когда я изменяю клиента 1 несколько раз, все мои операторы переключения работают нормально. ОДНАКО, всякий раз, когда я изменяю клиента 2 несколько раз, компилятор решает, что он хочет перейти к основанию, даже когда предлагает компилятору изменить определенный аспект информации клиента. Единственное, что я могу отредактировать для клиента 2, это его адрес, но я не могу предложить компилятору редактировать имя или номер телефона клиента 2, не пропустив его до конца цикла do while, не позволяя мне изменить одну вещь. Это хороший кусок кода, поэтому, если кто-то захочет скопировать и вставить в свою собственную среду IDE и помочь мне понять, какого черта я ошибся, это будет оценено!

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class ShopWithMethods {

public static void main (String[] Args) {
    Scanner scan1 = new Scanner(System.in);
    String name = "n/a";
    String date1 = "n/a";
    String address = "n/a";
    String phone = "n/a";
    String decide = "n/a";
    String rentalRecord = "No books or CDs rented yet.";
    System.out.println("Welcome to Eli's bookshop and CD rental shop!");
    Addcustomer(name, address, phone, date1, rentalRecord);

}

private static void Addcustomer(String name, String address, String phone, String date1, String rentalRecord) {
    Scanner scan1 = new Scanner(System.in);
    String decide;
    loop:
        while (true) {
        System.out.println("Would you like to create a customer profile with us? (Enter y or n):");
        decide = scan1.next();

        switch (decide) {

        case "y" : {
            System.out.println("Enter your name: ");
            scan1.nextLine();
            name = scan1.nextLine();
            System.out.println("Enter your address: ");
            address = scan1.nextLine();
            break loop;

        }


        case "n" : {
            System.out.print("Okay, please visit us another time.");
            break loop;
        }

        default : {
            System.out.print("(Try again)  ");
        }

    }
            }

        loop:
            while (true) {
                System.out.println("Enter your phone number(0000000000): ");
                phone = scan1.nextLine();
                if (phone.length() != 10) {
                    continue loop;
                }


                break loop;

            }

        loop:
            while(true) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the Date(mm-dd-yyyy): ");

        date1 = scanner.next();

        SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
        Date date2=null;
            try {

        date2 = dateFormat.parse(date1);
        } 
            catch (ParseException e) {

                e.printStackTrace();
                continue loop;
            }

            System.out.println("The date you've entered is: " + date2);
            break loop; 
            }



            String [][] CustomerProfile1 = {
                {"Name:", name},
                {"Address:", address},
                {"Phone Number:", phone},
                {"Enrollment Date:", date1},
                {"Rental Record:", rentalRecord}
        };

            System.out.println();
            loop:
                while(true) {
                    System.out.print("Adding a second customer, press c to continue: ");
                    decide = scan1.next();

            switch (decide.toLowerCase()) {

            case "c": {
                System.out.println("Enter your name: ");
                scan1.nextLine();
                name = scan1.nextLine();
                System.out.println("Enter your address: ");
                address = scan1.nextLine();
                break loop;

            }


            default : {
                System.out.print("(Try again)  ");
            }

        }
                }

            if (decide.equals("c")) {
            loop:
                while (true) {
                    System.out.println("Enter your phone number(0000000000): ");
                    phone = scan1.nextLine();
                    if (phone.length() != 10) {
                        continue loop;
                    }


                    break loop;

                }
            }

            if (decide.equals("c")) {
            loop:
                while(true) {
            Scanner scanner = new Scanner(System.in);
            System.out.println("Enter the Date(mm-dd-yyyy): ");

            date1 = scanner.next();

            SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
            Date date2=null;
                try {

            date2 = dateFormat.parse(date1);
            } 
                catch (ParseException e) {

                    e.printStackTrace();
                    continue loop;
                }

                System.out.println("The date you've entered is: " + date2);
                break loop; 
                }
            }

                System.out.println();
                if (decide.equals("c")) {
                    String [][] CustomerProfile2 = {
                        {"Name:", name},
                            {"Address:", address},
                            {"Phone Number:", phone},
                            {"Enrollment Date:", date1},
                            {"Rental Record:", rentalRecord}
                    };

                    System.out.println("Customer profile 1: ");
                    for (String i []: CustomerProfile1) {
                        System.out.println();
                        for (String print1: i) {
                            System.out.print(print1 + " ");

                        }
                    }

                    System.out.println();
                    System.out.println();
                    System.out.println("Customer profile 2: ");
                    for (String j []: CustomerProfile2) {
                        System.out.println();
                        for (String print2: j) {
                            System.out.print(print2 + " ");

                        }
                    }

                }


                String [][] CustomerProfile2 = {
                        {"Name:", name},
                            {"Address:", address},
                            {"Phone Number:", phone},
                            {"Enrollment Date:", date1},
                            {"Rental Record:", rentalRecord}
                    };

                System.out.println();

                ModifyCustomer(CustomerProfile1, CustomerProfile2, name, address, phone, date1, rentalRecord);

}

private static void ModifyCustomer(String[][] customerProfile1, String[][] customerProfile2, String name,
        String address, String phone, String date1, String rentalRecord) {

    System.out.println();
    String decide;
    String change;
    String repeat;
    int modify;

    Scanner scan1 = new Scanner(System.in);

    do {
    loop:
        while(true) {
            System.out.println("Would you like to modify a customer? (Enter y or n): ");
            decide = scan1.next();

            switch (decide.toLowerCase()) {

            case "y" : {
                System.out.println();
                break loop;
            }
            case "n" : {
                System.out.println();
                break loop;
            }
            }
        }

    loop:
        while(true) {
    if (decide.equals("y")) {
        System.out.println("Would you like to modify customer 1 or customer 2? ");
        modify = scan1.nextInt();
        switch (modify) {
        case 1:{
            System.out.println();
            break loop;
        }

        case 2: {
            System.out.println();
            break loop;
        }


        }
    }
        }


            loop:
                while(true) {
                    System.out.print("Would you like to modify the name, address, or phone?");
                    change = scan1.next();
            switch(change) {

            case "name": {
                if (modify == 1) {
                    System.out.print("Modify customer 1's name: ");
                    scan1.nextLine();
                    customerProfile1[0][1] = scan1.nextLine();
                    System.out.println("Customer 1's updated profile: ");
                    for (String [] i: customerProfile1) {
                        System.out.println();
                        for (String printData1: i) {
                            System.out.print(printData1 + " ");
                        }
                    }
                if (modify == 2) {
                    System.out.print("Modify customer 2's name: ");
                    scan1.nextLine();
                    customerProfile2[0][1] = scan1.next();
                    System.out.println("Customer 2's updated profile: ");
                    for (String [] j: customerProfile2) {
                        System.out.println();
                        for (String printData2: j) {
                            System.out.print(printData2 + " ");
                        }
                    }
                }
            }
                break loop;
            }

            case "address": {
                if (modify == 1) {
                    System.out.print("Modify customer 1's address: ");
                    scan1.nextLine();
                    customerProfile1[1][1] = scan1.nextLine();
                    System.out.println("Customer 1's updated profile: ");
                    for (String [] i: customerProfile1) {
                        System.out.println();
                        for (String printData1: i) {
                            System.out.print(printData1 + " ");
                        }
                    }
                }

                if (modify == 2) {
                    System.out.print("Modify customer 2's addresss: ");
                    scan1.nextLine();
                    customerProfile2[1][1] = scan1.nextLine();
                    System.out.println("Customer 2's updated profile: ");
                    for (String [] j: customerProfile2) {
                        System.out.println();
                        for (String printData2: j) {
                            System.out.print(printData2 + " ");
                        }
                    }
                }
                break loop;
            }

            case "phone": {
                if (modify == 1) {
                    do {
                        System.out.print("Modify customer 1's phone number: ");
                        scan1.nextLine();
                        phone = scan1.nextLine();
                        customerProfile1[2][1] = phone;
                        System.out.println("Customer 1's updated profile: ");
                        for (String [] i: customerProfile1) {
                            System.out.println();
                            for (String printData1: i) {
                                System.out.print(printData1 + " ");
                            }
                        }
                    }
                    while (phone.length() != 10);
                    if (phone.length() == 10) {
                        break loop;
                    }

                    if (modify == 2) {
                        do {
                            System.out.print("Modify customer 2's phone number: ");
                            scan1.nextLine();
                            phone = scan1.nextLine();
                            customerProfile2[2][1] = phone;
                            System.out.println("Customer 2's updated profile: ");
                            for (String [] j: customerProfile2) {
                                System.out.println();
                                for (String printData2: j) {
                                    System.out.print(printData2 + " ");
                                }
                            }
                        }
                        while (phone.length() != 10);
                        if (phone.length() == 10) {
                            break loop;
                        }
                    }

                }
                break loop;
            }
}






}


        System.out.print("Would you like to modify anything else? (Enter y or n): ");
        repeat = scan1.next();
        if (repeat.equals("n")) {
            break;
        }
        else 
            continue;

    }
    while (repeat.equals("y"));



}
}
...