开发者

Java comparing two letters

开发者 https://www.devze.com 2023-04-13 06:12 出处:网络
I ran in to a small problem while working on my assignment. Basically I\'m making a small program that asks the user for 3 letters and compares them to 3 letters that are coded in. Then the program is

I ran in to a small problem while working on my assignment. Basically I'm making a small program that asks the user for 3 letters and compares them to 3 letters that are coded in. Then the program is supposed to compare the 3 letters and if they're the same then print true. Thus far I've been able to make it without problems using compareTo, but now the tricky part is that I need to add a "tolerance" to the program (which I have) but the tolerance is supposed to loop back from Z to A. So if tolerance is 3 and the user inputs X Y Z (when it really is A B C) it should still print out true.

NOTE: the Tolerance will not go above 3. ALSO, We shouldn't use Arrays.

Any i开发者_Go百科deas how I can accomplish this? If it's complicated to understand what I'm asking please post and I'll try to clarify it :)

Thanks

EDIT: basically this is the code that compares the tolerances

        if ((a1.compareTo(d1) <= tolerance) && (a1.compareTo(d1) >= negTolerance) 
        && (b1.compareTo(e1) <= tolerance) && (b1.compareTo(e1) >= negTolerance) 
        && (c1.compareTo(f1) <= tolerance) && (c1.compareTo(f1) >= negTolerance))
    {
        open = true;
    } else open = false;

where a1 - c1 are pre inputed characters and d1-f1 are user entered. tolerance is also user entered as an integer between 1 and 3


Since it's a homework assignment, I won't give you the full answer, but I'll give you a hint. You want to look at the character codes (ASCII) for the letters. This will let you solve the tolerance problem. You might also have to do some magic with % (modulus) to handle the looping back of Z to A.

EDIT

If you cannot use the ASCII values, the return value of compareTo will help you, but keep in mind that that comparing A to Z and Z to A will give you -25 and 25 respectively. This is where the % operator will help you.


I would recommend using the ASCII value of the char.

char[] expecteds = ...;
int tolerance = 3;
char input = ...;
int inputValue = char;

for (int i=0; i<expecteds.length; i++){ 
  int delta = expected[0] - 'a' - input - 'a' % 'a';
  if (i < tolerance)
      result = true;
}


Use the Modulus (%) operator to cycle back around to the beginning:

int index = 0;
for (i in 1 .. 26) {
  int index = (i+tolerance) % 26;
}


1) Map each character to a Number
2) Grab the tolerance
3) Add/subtract the tolerance from the number
4) Compare the letters in the tolerance range to the letter
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号