我一直在读一本java书,其中我遇到了一段代码,其中提供了假输入以测试主类。假输入是一个 String,随后使用 Integer.parseInt() 方法转换为 int 原始类型。以下是两个类:
主类
public class SimpleDotCom{
int[] locationCells;
int numOfHits = 0;
public void setLocationCells(int[] locs){
locationCells = locs;
}
public String checkYourself(String stringGuess){
int guess = Integer.parseInt(stringGuess);
String result = "miss";
for(int cell : locationCells){
if(guess == cell){
result = "hit";
numOfHits++;
break;
}
}
if(numOfHits == locationCells.length){
result = "kill";
}
System.out.println(result);
return result;
}
}
测试类
public class SimpleDotComTestDrive{
public static void main(String[] args){
SimpleDotCom dot = new SimpleDotCom();
int[] locations = {2,3,4};
dot.setLocationCells(locations);
String userGuess = "4";
String result = dot.checkYourself(userGuess);
}
}
我用 int 变量尝试了相同的示例,它起作用了:
public class DotCom{
int[] locationCells;
int numOfHits = 0;
public void setLocationCells(int[] locs){
locationCells = locs;
}
public String checkYourself(int stringGuess){
//int guess = Integer.parseInt(stringGuess);
int guess = stringGuess;
String result = "miss";
for(int cell : locationCells){
if(guess == cell){
result = "hit";
numOfHits++;
break;
}
}
if(numOfHits == locationCells.length){
result = "kill";
}
System.out.println(result);
return result;
}
}
public class DotComTestDrive{
public static void main(String[] args){
DotCom dot = new DotCom();
int[] locations = {2,3,4};
dot.setLocationCells(locations);
int userGuess = 4;
String result = dot.checkYourself(userGuess);
//System.out.println("result2 = "+result);
}
}
我理解代码,但问题是为什么要输入字符串,而使用 int 变量可以获得相同的结果。
我不确定我是否遗漏了一些理解,或者我的问题可能是完全错误的,但是当我尝试使用 int 变量进行相同的示例并且它有效时,我一直想知道何时以及为什么将输入作为字符串?
最佳答案
在您的程序内部,建议使用最强的可能类型,在您的情况下使用 int。
但是你的程序有一个数据进出的外部边界,比如用户输入、控制台反馈、对文件或网络的 I/O 操作等。在很多情况下,你必须将涉及的数据转换为或来自接口(interface)规范定义的类型。 XML 或 json 结构将每个数据作为字符串传输,包括数字和日期。一旦它通过应用程序的边界,就应该立即转换为内部使用的类型(当然,还要检查转换是否有效)。
其背景是:使用字符串进行序列化和反序列化(网络流、文件)更容易(更好地互换)。但在进程内部(由 CPU)最好对数据的二进制表示进行操作。
关于java - 何时以及为何使用数字作为字符串输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45264358/