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

问题描述

作业指示创建一个请求字符串输入的循环。如果字符串少于 20 个字符,则显示刚刚输入的内容。如果 if 有超过 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");
    }
}

public StringTooLongException()
{
    super("String has too many characters!");
}

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

标签: javainheritancewhile-looptry-catchextends

解决方案


它会工作的。查看我的代码并与您的代码进行比较。第一:不要用==比较字符串,总是选择equals方法。你不需要 3 个 while 块,你只需要一个 while 和 2 个 IF'S 一个用于 string > 20 和另一个用于 string < 20 (看,如果字符串包含正好 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 !!!


推荐阅读