Не удается заставить мою рассогласованность работать правильно с переключателем - PullRequest
0 голосов
/ 18 января 2020

ПРОБЛЕМА РЕШЕНА.

Итак, я заканчиваю свое задание, последнее, что нужно сделать, - это реализовать некоторую простую обработку ошибок, но оказывается, что я не совсем уверен, что я делаю неправильно.

У меня есть 5 дел, которые принимают ввод 0, 1, 2, 3, 4. Он работает нормально.

Но если ввод не число, он должен отобразить сообщение, и пользователь может ввести некоторые новый вход. После того, как каждое задание выполнено, вам должно быть представлено меню и возможность сделать новый выбор.

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



import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.Scanner;

public class ObscureLovecraft {

    public static void main(String[] args) {
        // Looking for files and opening scanner
        File file = new File("./lovecraft.txt");
        File readObscure = new File("./obscure.txt");
        Scanner sc = new Scanner(System.in);

        // Printing UI

        printMenu();

        // Taking input, looping until case 0 is executed
        // Printing menu after each iteration
        // Switch, prints a new menu after every iteration
        try {
        int input = sc.nextInt();

            while (input != 0) {

                switch (input) {
                case 1:
                    writeObscure(file);
                    printMenu();
                    input = sc.nextInt();
                    break;

                case 2:
                    translateObscure(readObscure);
                    printMenu();
                    input = sc.nextInt();
                    break;

                case 3:
                    printObscure();
                    printMenu();
                    input = sc.nextInt();
                    break;

                case 4:
                    printTranslated();
                    printMenu();
                    input = sc.nextInt();
                    break;

                case 0:
                    kill();
                    break;

                }
            }
        } catch (InputMismatchException e) {
            System.out.println("You must use numbers.");
            sc.nextInt();
        }

        sc.close();

        System.out.println(":(");

    }

    public static void switches() {

    }

    /**
     * Just a method printing our menu
     */
    public static void printMenu() {
        System.out.println();
        System.out.println("Obscure");
        System.out.println("=======");
        System.out.println("1. Make obscure");
        System.out.println("2. Make readable");
        System.out.println("3. Print obscure");
        System.out.println("4. Print readable");
        System.out.println("0. Exit");
    }

    /**
     * Method which will print the "obscured" version of the text
     * 
     * @param file path to the file
     */
    public static void writeObscure(File file) {
        // Create new output file, creating PrintWriter, StringBuilder and placeholder
        // for the text
        File outFile = new File("./obscure.txt");
        StringBuilder buf = new StringBuilder();
        try {
            PrintWriter pw = new PrintWriter(outFile);
            Scanner fileSc = new Scanner(file);
            String text = "";

            // Placeholder for chars, looping through the file, adding it to placeholder
            // text, with new line
            char c;
            while (fileSc.hasNextLine()) {
                text = (fileSc.nextLine() + "\n");
                // Looping through the text, taking each character, pushing it 3 steps in the
                // alphabet
                // Taking care of z/Z pushing it to a/A, should maybe be c/C? Oh well.
                // Appending it to the stringbuilder in the new order
                // Casting char to int, to get ascii value
                for (int i = 0; i < text.length(); i++) {
                    c = text.charAt(i);
                    if (c == 'z') {
                        buf.append('a');
                    } else if (c == 'Z') {
                        buf.append('A');
                    } else {
                        int ascii = (int) c;
                        char nextChar = (char) (ascii + 3);
                        buf.append(nextChar);
                    }

                }
            }
            fileSc.close();

            // Printing and closing
            pw.print(buf);
            pw.close();
            System.out.println("Done");
        } catch (FileNotFoundException e) {
            System.out.println("Seems like a file gone missing, check error message: " + e.getMessage());
            System.out.println("Printing stacktrace: ");
            e.printStackTrace();
        }
    }

    /**
     * Method which will translate the obscured text to normal, Basically same as
     * the method above, but in reversed order
     * 
     * @param file
     */
    public static void translateObscure(File file) {
        // Read the file:
        StringBuilder obsBuf = new StringBuilder();
        try {
            Scanner readSC = new Scanner(file);
            // Print the file
            File printReadable = new File("./readableLovecraft.txt");
            PrintWriter pwRead = new PrintWriter(printReadable);

            // Text
            String readableText = "";
            char readC;

            // Loop thru
            // Something weird happend with empty lines,
            // Had to manually skip them
            while (readSC.hasNextLine()) {
                readableText = (readSC.nextLine() + "\n");

                for (int i = 0; i < readableText.length(); i++) {
                    readC = readableText.charAt(i);
                    if (readC == '\n') {
                        obsBuf.append(readC);
                    } else if (readC == 'z') {
                        obsBuf.append('a');
                    } else if (readC == 'Z') {
                        obsBuf.append('z');
                    } else {
                        int ascii = (int) readC;
                        char nextChar = (char) (ascii - 3);
                        obsBuf.append(nextChar);
                    }
                }

            }
            readSC.close();

            // Printing and closing
            pwRead.print(obsBuf);
            pwRead.close();
            System.out.println("Done");
        } catch (FileNotFoundException e) {
            System.out.println("Seems like a file gone missing, check error message: " + e.getMessage());
            System.out.println("Printing stacktrace: ");
            e.printStackTrace();
        }
    }

    /**
     * Simple method which loops through the text and prints it
     */
    public static void printObscure() {
        File readOutFile = new File("./obscure.txt");
        try {

            Scanner fileSc = new Scanner(readOutFile);
            String readText = "";
            while (fileSc.hasNextLine()) {
                readText = (fileSc.nextLine());
                System.out.println(readText);
            }
            fileSc.close();
        } catch (FileNotFoundException e) {
            System.out.println("Seems like a file gone missing, check error message: " + e.getMessage());
            System.out.println("Printing stacktrace: ");
            e.printStackTrace();

        }
    }

    /**
     * Simple method which loops through the text and prints it
     */
    public static void printTranslated() {
        File readReadOutFile = new File("./readableLovecraft.txt");
        String readReadText = "";
        Scanner fileSc;
        try {
            fileSc = new Scanner(readReadOutFile);

            while (fileSc.hasNextLine()) {
                readReadText = (fileSc.nextLine() + "\n");
                System.out.println(readReadText);

            }
            fileSc.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            System.out.println("Seems like a file gone missing, check error message: " + e.getMessage());
            System.out.println("Printing stacktrace: ");
            e.printStackTrace();
        }
    }

    /**
     * Method which kills the program
     */
    public static void kill() {
        System.exit(1);
    }
}

Ответы [ 3 ]

0 голосов
/ 18 января 2020

проверьте строку 60. Вам нужно прочитать до конца строки, а затем прочитать следующее целое число. Это решает вашу текущую проблему, но у вас все еще есть другие

   import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.Scanner;

public class ObscureLovecraft {

public static void main(String[] args) {
    // Looking for files and opening scanner
    File file = new File("./lovecraft.txt");
    File readObscure = new File("./obscure.txt");
    Scanner sc = new Scanner(System.in);

    // Printing UI

    printMenu();

    // Taking input, looping until case 0 is executed
    // Printing menu after each iteration
    // Switch, prints a new menu after every iteration
    while (true) {
       try {
       int input = sc.nextInt();

        

            switch (input) {
            case 1:
                writeObscure(file);
                printMenu();
                input = sc.nextInt();
                break;

            case 2:
                translateObscure(readObscure);
                printMenu();
                input = sc.nextInt();
                break;

            case 3:
                printObscure();
                printMenu();
                input = sc.nextInt();
                break;

            case 4:
                printTranslated();
                printMenu();
                input = sc.nextInt();
                break;

            case 0:
                kill();
                break;

            }
        
    } catch (InputMismatchException e) {
        System.out.println("You must use numbers.");
        sc.nextLine();
       
    }
    
    

    System.out.println(":(");
}

   

}

public static void switches() {

}

/**
 * Just a method printing our menu
 */
public static void printMenu() {
    System.out.println();
    System.out.println("Obscure");
    System.out.println("=======");
    System.out.println("1. Make obscure");
    System.out.println("2. Make readable");
    System.out.println("3. Print obscure");
    System.out.println("4. Print readable");
    System.out.println("0. Exit");
}

/**
 * Method which will print the "obscured" version of the text
 * 
 * @param file path to the file
 */
public static void writeObscure(File file) {
    // Create new output file, creating PrintWriter, StringBuilder and placeholder
    // for the text
    File outFile = new File("./obscure.txt");
    StringBuilder buf = new StringBuilder();
    try {
        PrintWriter pw = new PrintWriter(outFile);
        Scanner fileSc = new Scanner(file);
        String text = "";

        // Placeholder for chars, looping through the file, adding it to placeholder
        // text, with new line
        char c;
        while (fileSc.hasNextLine()) {
            text = (fileSc.nextLine() + "\n");
            // Looping through the text, taking each character, pushing it 3 steps in the
            // alphabet
            // Taking care of z/Z pushing it to a/A, should maybe be c/C? Oh well.
            // Appending it to the stringbuilder in the new order
            // Casting char to int, to get ascii value
            for (int i = 0; i < text.length(); i++) {
                c = text.charAt(i);
                if (c == 'z') {
                    buf.append('a');
                } else if (c == 'Z') {
                    buf.append('A');
                } else {
                    int ascii = (int) c;
                    char nextChar = (char) (ascii + 3);
                    buf.append(nextChar);
                }

            }
        }
        fileSc.close();

        // Printing and closing
        pw.print(buf);
        pw.close();
        System.out.println("Done");
    } catch (FileNotFoundException e) {
        System.out.println("Seems like a file gone missing, check error message: " + e.getMessage());
        System.out.println("Printing stacktrace: ");
        e.printStackTrace();
    }
}

/**
 * Method which will translate the obscured text to normal, Basically same as
 * the method above, but in reversed order
 * 
 * @param file
 */
public static void translateObscure(File file) {
    // Read the file:
    StringBuilder obsBuf = new StringBuilder();
    try {
        Scanner readSC = new Scanner(file);
        // Print the file
        File printReadable = new File("./readableLovecraft.txt");
        PrintWriter pwRead = new PrintWriter(printReadable);

        // Text
        String readableText = "";
        char readC;

        // Loop thru
        // Something weird happend with empty lines,
        // Had to manually skip them
        while (readSC.hasNextLine()) {
            readableText = (readSC.nextLine() + "\n");

            for (int i = 0; i < readableText.length(); i++) {
                readC = readableText.charAt(i);
                if (readC == '\n') {
                    obsBuf.append(readC);
                } else if (readC == 'z') {
                    obsBuf.append('a');
                } else if (readC == 'Z') {
                    obsBuf.append('z');
                } else {
                    int ascii = (int) readC;
                    char nextChar = (char) (ascii - 3);
                    obsBuf.append(nextChar);
                }
            }

        }
        readSC.close();

        // Printing and closing
        pwRead.print(obsBuf);
        pwRead.close();
        System.out.println("Done");
    } catch (FileNotFoundException e) {
        System.out.println("Seems like a file gone missing, check error message: " + e.getMessage());
        System.out.println("Printing stacktrace: ");
        e.printStackTrace();
    }
}

/**
 * Simple method which loops through the text and prints it
 */
public static void printObscure() {
    File readOutFile = new File("./obscure.txt");
    try {

        Scanner fileSc = new Scanner(readOutFile);
        String readText = "";
        while (fileSc.hasNextLine()) {
            readText = (fileSc.nextLine());
            System.out.println(readText);
        }
        fileSc.close();
    } catch (FileNotFoundException e) {
        System.out.println("Seems like a file gone missing, check error message: " + e.getMessage());
        System.out.println("Printing stacktrace: ");
        e.printStackTrace();

    }
}

/**
 * Simple method which loops through the text and prints it
 */
public static void printTranslated() {
    File readReadOutFile = new File("./readableLovecraft.txt");
    String readReadText = "";
    Scanner fileSc;
    try {
        fileSc = new Scanner(readReadOutFile);

        while (fileSc.hasNextLine()) {
            readReadText = (fileSc.nextLine() + "\n");
            System.out.println(readReadText);

        }
        fileSc.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        System.out.println("Seems like a file gone missing, check error message: " + e.getMessage());
        System.out.println("Printing stacktrace: ");
        e.printStackTrace();
    }
}

/**
 * Method which kills the program
 */
public static void kill() {
    System.exit(1);
}
}

   
0 голосов
/ 18 января 2020

1- Создайте новый метод и поместите в него свои логи c

2- Удалите while из вашего кода

3- Броски InputMismatchException по умолчанию block

4- Вызов newMethod() in cases вместо input = sc.nextInt. (рекурсивный)

5- Вызов newMethod() в блоке перехвата (рекурсивный)

public static void newMethod() {

        Scanner sc = new Scanner(System.in);

        try {

            int input = sc.nextInt();

            switch (input) {
                case 1:
                    writeObscure(file);
                    printMenu();
                    newMethod();
                    break;

                case 2:
                    translateObscure(readObscure);
                    printMenu();
                    newMethod();
                    break;

                case 3:
                    printObscure();
                    printMenu();
                    newMethod();
                    break;

                case 4:
                    printTranslated();
                    printMenu();
                    newMethod();
                    break;

                case 0:
                    kill();
                    break;

                default:
                    throw new InputMismatchException();
            }

        } catch (InputMismatchException e) {
            System.out.println("You must use numbers.");
            newMethod();
        }

      sc.close();

}

Измените свой метод main следующим образом

 public static void main(String[] args) {

            File file = new File("./lovecraft.txt");
            File readObscure = new File("./obscure.txt");
            printMenu();

            //Call new Method
            newMethod();

    }
0 голосов
/ 18 января 2020

Поместите ваши параметры в бесконечное число l oop, то есть сделайте это следующим образом:

while (true) {
    try {
        int input = sc.nextInt();
        switch (input) {
        case 1:
            writeObscure(file);
            printMenu();
            input = sc.nextInt();
            break;

        case 2:
            translateObscure(readObscure);
            printMenu();
            input = sc.nextInt();
            break;

        case 3:
            printObscure();
            printMenu();
            input = sc.nextInt();
            break;

        case 4:
            printTranslated();
            printMenu();
            input = sc.nextInt();
            break;

        case 0:
            kill();
            break;

        default:
            System.out.println("Incorrect choice number");
        }
    } catch (InputMismatchException e) {
        System.out.println("You must use numbers.");
        sc.nextLine();
    }
}

Вы также должны использовать регистр default для недопустимых номеров выбора. Также обратите внимание, что внутри блока catch я изменил sc.nextInt() на sc.nextLine(), чтобы позволить пользователю ввести новый выбор.

...