Java 将空字符串转换为字符时出错
测试用户的输入,我的意思是应该确保用户输入的字符串不是空的。我认为您应该添加此测试,在进行计算之前检查字符串的长度。如果异常不符合您的要求,则引发异常Java 将空字符串转换为字符时出错,java,Java,测试用户的输入,我的意思是应该确保用户输入的字符串不是空的。我认为您应该添加此测试,在进行计算之前检查字符串的长度。如果异常不符合您的要求,则引发异常 Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.String.charAt(Unknown Source) at Shapes.area(Shapes.j
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String
index out of range: 0
at java.lang.String.charAt(Unknown Source)
at Shapes.area(Shapes.java:40)
at Shapes.main(Shapes.java:11)
嗨,欢迎来到Stackoverflow!我认为您可以通过添加运行时错误的输出来改进您的问题,这样查看的人就可以看到代码的哪个部分引发了哪个异常。提示:查看您的命名。名字应该说明它所命名的东西是关于什么的。名称,如h、b、h1。。。你真是太可怕了。@bitstrider我很感激你的反馈!我为我做错的任何事情道歉,如重复的帖子等。我对编程非常陌生,仍在努力学习它的工作原理。@GhostCat我会接受你的建议,取一些更好的名字
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String
index out of range: 0
at java.lang.String.charAt(Unknown Source)
at Shapes.area(Shapes.java:40)
at Shapes.main(Shapes.java:11)
import javax.swing.JOptionPane;
public class F {
public static void main(String[] args) throws Exception {
try {
String b = JOptionPane.showInputDialog(null, "Enter base");
// Check that the String has at least 1 character
if (b.length() < 1 ) {
// If it doesnt, throw an error
throw new Exception("Base cannot be null value");
}
// Otherwise we continue
JOptionPane.showMessageDialog(null, "Base is " + b);
// Catch the exception
} catch (Exception exception) {
// Notify the use about the issues
JOptionPane.showMessageDialog(null, exception.getMessage());
// TODO - implement more logic, like asking user for input again
}
}
}