Java 如何修复do while循环中的逻辑,然后应用try-catch块捕获并显示来自另一个类的错误消息?

Java 如何修复do while循环中的逻辑,然后应用try-catch块捕获并显示来自另一个类的错误消息?,java,inheritance,while-loop,try-catch,extends,Java,Inheritance,While Loop,Try Catch,Extends,作业指示创建一个循环,请求字符串输入。如果字符串少于20个字符,则显示刚刚输入的内容。如果包含的字符超过20个,catch块将显示一条消息,说明字符串包含的字符太多。结束程序的唯一方法是输入DONE。否则,它将继续要求用户输入字符串 catch块将显示来自另一个类的消息 我尝试了do while和while循环 do { System.out.println("Enter strings, enter DONE when finished:");

作业指示创建一个循环,请求字符串输入。如果字符串少于20个字符,则显示刚刚输入的内容。如果包含的字符超过20个,catch块将显示一条消息,说明字符串包含的字符太多。结束程序的唯一方法是输入DONE。否则,它将继续要求用户输入字符串

catch块将显示来自另一个类的消息

我尝试了do while和while循环

    do
    {
        System.out.println("Enter strings, enter DONE when finished:");
        userInputLength = input.nextLine();
        try {
        while(userInputLength.length() > 20)
        {
            System.out.println("Please try again:");
            userInputLength = input.nextLine();
        }
        }
        catch(StringTooLongException e) //Error here
        {
            //Not sure how to call the super() in StringTooLongException class.
        }
        while(userInputLength.length() <= 20)
        {
            String message = userInputLength;
            System.out.println("You entered: " + message);
            userInputLength = input.nextLine();
        }
        }
    while(userInputLength.toString() == "DONE");
    }
}

在添加两个try-catch块之后,我开始在catch块上获取错误之前,我能够输出长字符串,然后是短字符串。但是如果我尝试在短字符串之后写长字符串,程序就会结束。

它会工作的。查看我的代码并与您的代码进行比较。 第一:不要将字符串与==进行比较,始终选择equals方法。 您不需要3个whiles块,只需要一个while和2个IF'S,一个用于string>20,另一个用于string<20(看,如果string正好包含20的长度,程序将不输出任何内容) 您需要创建自己的异常,这非常简单

import java.util.Scanner;

public class ReadString {

public static void main(String[] args) {

    String userInputLength;
    Scanner input = new Scanner(System.in);

    /*
     * . If the String has less than 20 characters, it displays what was just
     * inputted. If if has more than 20 characters, the catch block will display a
     * message stating that the String has many characters. The only way to end the
     * program is to input DONE. Otherwise, it continues to ask the user for
     * Strings.
     */

    do {
        System.out.println("Enter strings, enter DONE when finished:");
        userInputLength = input.nextLine();
        try {
            if (userInputLength.length() > 20) {
                throw new StringTooLongException("String is too long");
            } else {
                System.out.println(userInputLength);
            }

        } catch (StringTooLongException e) // Error here
        {
            System.out.println(e.getMessage());
        }

    } while (!userInputLength.toString().equals("DONE"));

}
例外类

public class StringTooLongException extends RuntimeException{

public StringTooLongException(String message) {
    super(message);
 }
}
试着去理解它:D

public class StringTooLongException extends RuntimeException{

public StringTooLongException(String message) {
    super(message);
 }
}