[英]How to fix the logic in my do-while loop, and then applying the try-catch block to catch and display an error message from another class?
作业指示创建一个循环,请求输入字符串。 如果字符串少于20个字符,则显示刚刚输入的内容。 如果字符数超过20个,则catch块将显示一条消息,指出String的字符过多。 结束程序的唯一方法是输入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块上获取错误之前,我能够先输出长字符串,然后输出短字符串。 但是,如果我尝试在短字符串之后写长字符串,则程序结束。
它会工作的。 查看我的代码,并与您的代码进行比较。 第一:不要将字符串与==进行比较,请始终选择equals方法。 您不需要3个whiles块,只需要一个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 !!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.