我有一个小方法,除其他外,还将字符串转换为整数.由于字符串是方法的参数,我想确保该字符串是可转换的.所以我只是想知道什么是最安全和/或最快的方式.
版本A:保持原样并承担风险(我试图避免)
public static int stringToInt(String param) {
return Integer.valueOf(param);
}
Run Code Online (Sandbox Code Playgroud)
(就速度而言,它会对版本B和C产生什么样的差异?)
版本B:抓住异常
public static int stringToInt(String param) {
try {
return Integer.valueOf(param);
} catch(NumberFormatException e) {
return -1;
}
}
Run Code Online (Sandbox Code Playgroud)
版本C:检查字符串的每个字母,看它是不是数字
public static int stringToInt(String param) {
for(char c : param.toCharArray()) {
if(!Character.isDigit(c))
return -1;
}
return Integer.valueOf(param);
}
Run Code Online (Sandbox Code Playgroud)
请注意,参数必须是一个正数,-1应该是我的小程序中的"错误值",换句话说,所有三个版本的方法在我的程序中都可以正常工作.
我对你可以给我的任何其他建议持开放态度,所以如果你认为自己的版本更好,请随意创建自己的版本.
非常感谢您的支持.
所以,举一个例子,假设我们有一个abstract class
被调用的Question
,该问题包含很多字符串,一个用于问题本身,一个用于答案,两个响应发布给用户,如果他的问题是对/错.
public abstract class Question {
private final String question;
private final String answer;
private final String answerCorrect;
private final String answerWrong;
}
Run Code Online (Sandbox Code Playgroud)
我的问题基本上是,初始化所有字符串的常用方法是什么?到目前为止,我已经编写了2个关于如何做的版本,它们有它们的上下限,我想知道,如果有这种"最佳编码实践".
版本A
初始化构造函数中的所有内容.
public abstract class Question {
//...
public Question(String question, String answer, String answerCorrect, String answerWrong) {
this.question = question;
this.answer = answer;
this.answerCorrect = answerCorrect;
this.answerWrong = answerWrong;
}
}
Run Code Online (Sandbox Code Playgroud)
这看起来非常方便,我遇到的唯一问题是用户不确定字符串必须按顺序排列.
public class ExampleClass extends Question {
public ExampleClass() {
super("I think, that's the answer", "and that's the question", …
Run Code Online (Sandbox Code Playgroud) 我刚刚在一本教科书中读过这篇文章,所以我想知道这是不是真的.
比方说,我们有一个数组,其中包含一些我们想要迭代的值:
for(int x = 0; x < array.length; x++) {
//some code
}
Run Code Online (Sandbox Code Playgroud)
现在每次跳回到循环的开头,它都必须重新计算数组的长度.因此,本书建议,最好创建一个该长度的整数,并将x与该整数而不是数组长度进行比较.
for(int x = 0, int length = array.length; x < length; x++) {
//some code
}
Run Code Online (Sandbox Code Playgroud)
因此,根据我的理解,第一个版本显然较慢但节省了内存,而在第二个版本中,我们使用更多的空间来使其更快.但是我在实践中从未见过第二个版本,所以我想知道哪些代码会更好用.
提前致谢!
我厌倦了在我的代码中添加看似无穷无尽的if-else语句,所以我想知道如果我只是抓住异常,如果有些事情不对,那么更好的做法.例如.而不是说:
public static boolean firstStringOfArrayIsTheSameAsTheWord(String word, String[] array) {
if(word != null) {
if(array.length > 0) {
return word.equalsIgnoreCase(array[0]);
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
我只想:
public static boolean firstStringOfArrayIsTheSameAsTheWord(String word, String[] array) {
try {
return word.equals(array[0]);
} catch(/*NullPointerException or an ArrayIndexOutOfBoundsException*/ Exception e) {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我确实知道我可以在if语句中使用多个参数,但我只是对在实践中使用哪种方法更好以及为什么感兴趣.
提前致谢!