如何在Java中使用if-else处理数组。

huangapple 未分类评论55阅读模式
英文:

How to use if else for an array in java

问题

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

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

我想首先检查一下 result[5] 是否有值。
因为当它有值时,应用程序可以正常运行,但当它没有值时,我的应用程序会停止。

英文:

I want to use an if condition on my array.
Here is my code:

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

I want to check first to see if result[5] has a value or not.
Because when it has a value, the app works correctly, but when it has no value, my app keeps stopping.

答案1

得分: 0

你可以首先检查从分割中得到的数组的长度:

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

请注意,Java的命名约定通常不鼓励在变量名中使用下划线。请使用驼峰式命名法,不要使用value_got,而是使用valueGot

英文:

You may first check the length of the array resulting from the split:

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

Note that Java naming conventions generally frowns upon putting underscores in variable names. Instead of using value_got, use valueGot, in camel case.

huangapple
  • 本文由 发表于 2020年4月6日 19:43:50
  • 转载请务必保留本文链接:https://java.coder-hub.com/61059019.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定