简体   繁体   English

从IF语句返回值

[英]Returning value from an IF statement

I would like to return a string from an IF statement. 我想从IF语句返回一个字符串。 Below is the code. 下面是代码。 I am parsing a JSON object and need to insert the data into a sql lite table. 我正在解析JSON对象,需要将数据插入sql lite表中。

if (object.has("message")) {
    JSONObject message = object.getJSONObject("message");
    String newtype_mod = object.getJSONObject("message").getString("type");
    String newcontent_mod = object.getJSONObject("message").getString("content");
    objSample = new GetSetMethod();
    objSample.setnewcontent_mod(newcontent_mod);
    objSample.setnewtype_mod(newtype_mod);
    Log.v("##" + newcontent_mod, "V " + newtype_mod);
}

objSample = new GetSetMethod();
objSample.setNewreportid(newreportid);
objSample.setnewcontent_mod(newcontent_mod);
objSample.setnewtype_mod(newtype_mod);
Log.v("" + newcontent_mod, "" + newtype_mod);

As you would have understood newcontent_mod and newtype_mod will not be accessible from the IF statement. 如您所知,将无法从IF语句访问newcontent_mod和newtype_mod。 And I need the IF statement compulsorily. 我需要IF语句。

I understand the question is basic. 我了解这个问题是基本的。 Please help a fellow newbie ! 请帮助一个新手!

Thanks! 谢谢!

Can you not simply declare them outside the if? 您不能简单地在if之外声明它们吗?

String newtype_mod = "";
String newcontent_mode = "";
if ((object.has("message"))) {
    //
    // do stuff here
    //
}
// continue as before...

You can declare it outside the if statement and just assign the value to these variables 您可以在if语句之外声明它,只需将值分配给这些变量

for example: 例如:

String newtype_mod="";
String newcontent_mod="";

if ((object.has("message"))) 
{
     JSONObject message = object.getJSONObject("message");
     newtype_mod = object.getJSONObject("message")
                        .getString("type");
     newcontent_mod = object.getJSONObject("message")
                     .getString("content");
     objSample = new GetSetMethod();
     objSample.setnewcontent_mod(newcontent_mod);        
     objSample.setnewtype_mod(newtype_mod);
     Log.v("##"+newcontent_mod,"V "+newtype_mod);
}

otherwise 除此以外

You can declare both at Global level ie class level variables 您可以在全局级别(即类级别变量)中声明两者

Declare the 2 string outside the if statement like 在if语句外声明2字符串,例如

String newcontent_mod,newtype_mod;
if ((object.has("message"))) {
    JSONObject message = object.getJSONObject("message");
    newtype_mod = object.getJSONObject("message")
                        .getString("type");
    newcontent_mod = object.getJSONObject("message")
                        .getString("content");
    objSample = new GetSetMethod();
    objSample.setnewcontent_mod(newcontent_mod);        
    objSample.setnewtype_mod(newtype_mod);
    Log.v("##"+newcontent_mod,"V "+newtype_mod);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM