mardi 12 mai 2020

My Math Method in Java only seems to work occasionally but in a repetitive pattern

I have this code that I'm trying to make work. For the most part, the numbers are coming out -127 below what they should be, However, occasionally the numbers are coming out correctly. The math works properly in a calculator.

I can't see any rhyme or reason for this because it is seemingly random. Does anyone see anything that could possibly cause this?

It seems to be happening during the decode phase.

It appears to be recreating the same results every time it is run. (Meaning the 'thirteenth' number will always be right every time I run it while the others are 127 lower then they should be)

Any help would be appreciated! Thank you!

public static String encode(long seed, String str) {
    Random r = new Random(seed);
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        int rr = r.nextInt(1000);

        int num = (c + rr) % 127;
        sb.append((char) num);
    }

    return sb.toString();
}

public static String decode(long seed, String str) {
    Random r = new Random(seed);
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        int rr = r.nextInt(1000);

        int num = (c - rr) % 127; //This is the line in question
        sb.append((char) num);
    }

    return sb.toString();
}

If any more info is needed lemme know!




Aucun commentaire:

Enregistrer un commentaire