【问题标题】:How to use if else for an array in java如何在java中使用if else作为数组
【发布时间】:2020-04-06 11:43:50
【问题描述】:

我想在我的数组上使用if 条件。
这是我的代码:

String[] result = value_got.split(" ");    
String fabric = result[5];

我想先检查result[5]是否有值。
因为当它有值时,应用程序正常工作,但当它没有值时,我的应用程序一直停止。

【问题讨论】:

  • if ((result != null) && (result[5] != null) { fabric = result[5] } else { ... }

标签: java arrays if-statement


【解决方案1】:

您可以先检查拆分后的数组长度:

String[] result = valueGot.split(" ");
String fabric = result.length >= 6 ? result[5] : "";

请注意,Java 命名约定通常不赞成在变量名中添加下划线。不要使用value_got,而是使用valueGot,在骆驼的情况下。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 2015-02-14
    • 1970-01-01
    • 2019-04-25
    相关资源
    最近更新 更多