Aryan - 1 year ago 48

Java Question

I am trying to create an app where the user has to memorise a random number (17 digits long) and then enter what s/he remembers. After generating the number, how do I check how similar they are i.e. 10 of the digits match so it is 58% similar.

Answer Source

Lets say you compare this two strings:

```
String number1; // users number
String number2; // your number
```

Since you said both will be 17 digit long, no need to take in account different sizes (then you should go from the end):

```
int matches = 0;
for (int i = 0; i < number1.length(); i++) {
if (number1.substring(i, i + 1).equals(number2.substring(i, i + 1))) matches++;
}
```

Another approach would be with char arrays:

```
char[] charArray1 = number1.toCharArray();
char[] charArray2 = number2.toCharArray();
for (int i = 0; i < charArray1.length; i++) {
if (charArray1[i] == charArray2[i]) matches++;
}
```

Or by using Strings own array of chars (thanks @David Wallace):

```
for (int i = 0; i < charArray1.length; i++) {
if (number1.charAt(i) == number2.charAt(i)) matches++;
}
```

Now, you calculate procent:

```
double procent = matches / (number1.length() * 1d) * 100;
```

You must multiply with double value of `1`

, so it doesn't calculates with `int`

, this will force it to deal with doubles.