I have a project that has three requirements:
Prompt user to enter 5 uppercase characters and save as variable.
Randomly generate a 5 character string and save as variable.
Compute the distance between the two strings.
I thought I had it and it looked like it worked, but then I noticed that the computed distance between the two strings is always 5.
I am guessing that my stringLength
is somehow being used for stringDist
.
If you could look it over and lead me in the right direction as to what I'm missing, I would greatly appreciate it.
import java.util.Random;
import java.util.Scanner;
public class StringDiff {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println ("Please enter 5 Uppercase letters.");
String userString = scan.nextLine();
int leftLimit = 48; // numeral '0'
int rightLimit = 122; // letter 'z'
int stringLength = 5;
Random random = new Random();
String randString = random.ints(leftLimit, rightLimit + 1)
.filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97))
.limit(stringLength)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
{
int i = 0, stringDist = 0;
while (i < userString.length())
{
if (userString.charAt(i) != randString.charAt(i))
stringDist++;
i++;
}
System.out.println ("The user string is: " + userString);
System.out.println ("The random string is: " + randString);
System.out.println ("The distance between " + userString + " and " + randString + " is " + stringDist);
}
Since you're comparing a five character user-entered string with a randomly generated string, there's a good chance that there no positions where the corresponding characters are the same, which would make the distance equal to five. So in that sense, there's nothing wrong with your code. If you repeatedly run the program, you'll eventually get a distance less than five.