我正在处理一个属性文件。在它上面,我有一个键“user_email”和值,我将其设置为 [email protected] 。
现在,在我的代码中,我希望每当程序运行时都会迭代电子邮件值,因此 [email protected]将是[email protected]依此类推,从那里,我读取属性文件中的电子邮件值并在我的程序中调用它。
public String getEmailFromProperty(){
String new_email = "";
try{
new ConfigReader();
FileOutputStream fos = new FileOutputStream(property_file);
StringBuilder str = new StringBuilder(property.getProperty("user_email"));
char charWithNumber = str.charAt(9); // get the number character of the email (starts with 0)
int toInteger = (int) charWithNumber; // convert that character number to an Integer value
int numericValue = Character.getNumericValue(toInteger+1); // the number character in email is converted to int then incremented by 1 on each run
int toAscii = numericValue + 48; // the number character (which is now an Int) is added by 48
char toChar = (char) toAscii; // it is converted back to a character in order for it to be passed as a parameter to setCharAt() method
str.setCharAt(9, toChar); // attached the newly incremented number character to the email @ 9th index
new_email = str.toString(); // converted the StringBuilder variable str to an ordinary String in order to call toString() method
property.setProperty("user_email", new_email); // now, I wrote the new email to the property file using the "user_email" key
property.store(fos, null);
fos.close();
}
catch(Exception e){
System.out.println("Error is " + e.getMessage());
}
return new_email;
}
我知道这对你来说有点困惑。但是,当电子邮件号码字符达到值 9 然后递增时,我预计它是 10。但是,它返回“/”字符。运行后我想要的是 [email protected] 不是toomeuser/@gmail.com
最佳答案
您混淆了 char
和 String
。 char 是单个字符,永远无法表示'10'
,因为这个数字是用两个字符写成的
:1
和 0
。只有 String
才能正确表示数字 10,如下所示:"10"
所以这些行应该改变:
int numericValue = Character.getNumericValue(toInteger+1); // <-- This breaks at '9'
int toAscii = numericValue + 48; // <-- This breaks after '9'
char toChar = (char) toAscii; // <-- this should be a String
str.setCharAt(9, toChar); // This cannote be used because we may need more than 1 char
像这样的东西(未经测试):
int numericValue = Character.getNumericValue(toInteger) + 1; // Note the parenthesis
String asString = String.valueOf(numericValue);
String prefix = str.subString(9);
String suffix = str.subString(10, str.length());
str = prefix + asString + suffix;
关于java - 我想获得下一个递增值 9(当然是 10),但它返回一个 ASCII 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40861490/