gpt4 book ai didi

java - 异常处理 try-catch 语句字符串长度

转载 作者:行者123 更新时间:2023-12-02 07:04:01 26 4
gpt4 key购买 nike

大家好,我有一个关于异常 try-catch 语句的问题。在我做的一个练习题中,用户输入一个一定长度的字符串。如果用户输入的字符串长度大于20,则会抛出异常。现在我似乎已经按顺序设置了所有内容,但真正让我困惑的是在 try block 中放入什么。任何人都可以用伪代码或通过解释来解释我需要输入什么才能让它运行吗?

另外,我有一个关于 catch(StringTooLongException e) 的 catch 语句的问题。我已经制作了另外两个程序来处理继承的类和一个使用我创建的名称来解决相同问题的类,而无需使用 try-catch 语句。这就是StringTooLongException的地方来自。我的问题是,你怎么知道要使用什么异常名称?我知道 java 中内置了一般异常,但我只是有点困惑。

谢谢

这是我的代码:

import java.util.Scanner;

public class StringTooLongExceptionModified{

public static void main(String[] args){
String input;


Scanner myScan = new Scanner(System.in);
System.out.println("Enter a string(DONE to quit): ");
input = myScan.nextLine();

while(!input.equals("DONE")){

try{




}
catch(StringTooLongException e){
System.out.println ("Exceeds string length: " + input);
}

System.out.println("Enter a string(DONE to quit): ");
input = myScan.nextLine();


}
}
}

最佳答案

您似乎正在寻找:

try{
if (input.length() <= 20) {
// do stuff with your input
} else {
throw new StringTooLongException("'" + input + "' is longer than 20");
}
} catch(StringTooLongException e){
System.out.println ("Exceeds string length: " + input);
}

关于java - 异常处理 try-catch 语句字符串长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16311293/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com