1

全部-我已经查看了很多与此类似的问题,但似乎无法解决我的问题。我的问题是,在 if 语句之外声明但在 if 语句内部初始化的变量没有被定义在同一范围内的变量识别。这是我的代码:

  String lastP1Boa; //Declared here

if (ownersBoa == message) {
    Spinner houseBoa = (Spinner) findViewById(R.id.houseBoa);
    String housesBoa = houseBoa.getSelectedItem().toString();
    Integer lastIntHouseBoa = Integer.parseInt(housesBoa.replaceAll("[\\D]", ""));

    Spinner hotelBoa = (Spinner) findViewById(R.id.hotelBoa);
    String hotelsBoa = hotelBoa.getSelectedItem().toString();
    Integer lastIntHotelBoa = Integer.parseInt(hotelsBoa.replaceAll("[\\D]", ""));


    int intLastP1Boa = lastIntHotelBoa * 1500 + lastIntHouseBoa * 100;
    lastP1Boa = String.valueOf(intLastP1Boa);  } //Initialized here



String p1Total = lastP1Boa; //Error saying that lastP1Boa needs it be initialized  

谢谢大家的时间,希望我已经说清楚了!

4

2 回答 2

0

编译器报告的问题是有可能if (ownersBoa == message)会评估false并且lastP1Boa不会被初始化。将其设置为等于null(或更合适的默认值)您声明它的位置。

String lastP1Boa = null; //Declared here
于 2012-07-09T01:17:23.577 回答
0

如果您将第一行更改为String lastP1Boa = null;,它应该会修复您的编译错误,但您应该确保处理该变量为null.

于 2012-07-09T01:18:01.753 回答