将空字符串转换为char时发生错误

时间:2017-11-11 18:27:52

标签: java

String b, h;
char b1, h1;
    do
    {
        b = JOptionPane.showInputDialog(null, "Enter the base of the triangle.");
        h = JOptionPane.showInputDialog(null, "Enter the height of the triangle.");
        b1 = b.charAt(0);
        h1 = h.charAt(0);
        if (b1 >= '0' && b1 <= '9' && h1 >= '0' && h1 <= '9') //This if statement will only execute the program if a number is entered
        {
        double base = Double.parseDouble(b);
        double height = Double.parseDouble(h);
        double area = (base*height)/2;
        JOptionPane.showMessageDialog(null, "The area of a triangle with a base of " + base + " inches and a height of " 
        + height + " inches is " + area + " inches.");
        }
        else
        {
            JOptionPane.showMessageDialog(null, "One or more of the values you entered is not a number. Please enter a number.");
        }
        }
        while (!(b1 >= '0' && b1 <= '9' && h1 >= '0' && h1 <= '9')); /*Causes the statement to keep asking for a value until a number
                                                                        is entered*/
        break;

我必须编写一个程序,根据输入/选择的内容为用户提供形状的面积或体积。以上部分是针对三角形的区域。程序将继续询问基数和高度的值,直到输入的两个值都是数字。错误发生的唯一时间是用户点击&#34; OK&#34;在对话框中,不输入任何值。当程序试图将字符串转换为char时,错误的来源似乎是。如何点击&#34; OK&#34;不输入值不会导致错误?

这是错误本身

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)

2 个答案:

答案 0 :(得分:0)

您测试用户的输入,我的意思是应该确保用户输入的字符串不为空。我认为你应该添加这个测试

答案 1 :(得分:0)

在进行计算之前检查String的长度。如果不符合您的要求,请抛出异常。

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
    }
  }
}