java - 我想获得下一个递增值 9(当然是 10),但它返回一个 ASCII 代码

标签 java ascii property-files

我正在处理一个属性文件。在它上面,我有一个键“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

最佳答案

您混淆了 charString。 char 是单个字符,永远无法表示'10',因为这个数字是用两个字符写成的:10。只有 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/

相关文章:

java - 如何从 Hashmap<String String> 获取 ArrayList

c# - 如何将 'end of text' (ETX, ASCII 3) 放入字符串中?

javascript - Facebook javascript SDK 从属性文件到 jsp 的共享版本不起作用 [webapp]

c - 使用 C 将二进制文件写入 ASCII 代码

java - 在运行时更改属性文件内的值

java - 如何刷新选项卡框项目点击上的数据?

java - 如何在 java 中将用户输入的整数转换为 char ASCII 值?

java - 如何从 Android 中的下载文件夹获取 PDF 真实路径?

整数表示的字符数组