作业指导创建一个请求字符串输入的循环。如果字符串少于 20 个字符,则显示刚刚输入的内容。如果 if 超过 20 个字符,catch block 将显示一条消息,指出该字符串包含太多字符。结束程序的唯一方法是输入 DONE。否则,它会继续向用户询问字符串。
catch block 将显示来自另一个类的消息。
我尝试过执行 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 block 后,在 catch block 上开始出现错误之前,我能够输出长字符串,然后输出短字符串。但如果我尝试在短字符串后面写入长字符串,程序就会结束。
最佳答案
它会起作用的。看看我的代码并与你的进行比较。 第一:不要用==比较字符串,总是选择equals方法。 你不需要3个while block ,你只需要一个while和2个IF,一个用于字符串> 20,另一个用于字符串< 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!!!
关于java - 如何修复 do-while 循环中的逻辑,然后应用 try-catch block 来捕获并显示来自另一个类的错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56160881/