15,791,934 members
1.00/5 (1 vote)
See more:
I have got a question to do in which i need to find distance between letters.
eg: If the input letters are A and E
On trying to reach E from A we need to cross B C D. Hence the number of letters in between E and A is 3. The distance is number of letters in between E and A + 1, which is equal to 4.
I wrote the code as follows:
I got the answer for some of the inputs. But i got a wrong answer for W A

What I have tried:

Java
```import java.lang.Character;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)throws Exception
{
Scanner in=new Scanner(System.in);
char a=in.next().charAt(0);
char d=in.next().charAt(0);
System.out.println(Math.abs(Character.toLowerCase(a)-Character.toLowerCase(d)));
}
}```
Posted
Updated 7-Oct-16 10:57am
v3
[no name] 7-Oct-16 9:59am
Do you have a question for us that we could help you with concerning your homework assignment?
Member 12781602 7-Oct-16 11:38am
For the input W A, I need to get 4 as the output,not 22. How should I edit to get it so?
[no name] 7-Oct-16 11:47am
Use your debugger to figure out why you are getting 4 but CPallini is getting 22.
[no name] 7-Oct-16 14:01pm
Wait a minute, I just re-read your statement. Why is it that you think that the distance between W and A is only 4 and not 22? Either you are not telling us something or you misread your homework assignment.
Richard MacCutchan 7-Oct-16 10:35am
As I understand the alphabet W has a higher value than A, so your algorithm will come up with a negative number. Go on from there.

## Solution 1

If you need to consider wrap araound, then the code becomes a little bit more complex.
I hope you are able to simplify it, though.

Java
```import java.util.Scanner;
public class Main
{
public static void main(String[] args) throws Exception
{
Scanner in = new Scanner(System.in);
char a = in.next().charAt(0);
char b = in.next().charAt(0);
a = Character.toLowerCase(a);
b = Character.toLowerCase(b);
int d1, d2;

if ( a <= b )
{
d1 = b - a; // direct distance
d2 = 26 - b + a; // distance considering wrap around
}
else
{
d1 = a - b; // direct distance
d2 = 26 - a + b; // distance considering wrap around
}
int  d; // now the distance is the smallest between 'direct' and 'wrapped around'
if ( d1 <= d2)
d = d1;
else
d = d2;

System.out.println(d);
}
}```

Richard Deeming 7-Oct-16 16:36pm
That looks over-complicated to me. Assuming the inputs are valid letters, why not simply do:

```int d = Math.abs(a - b);
if (d > 13) { d = 26 - d; }```
CPallini 7-Oct-16 16:50pm
Nice.
Richard MacCutchan 8-Oct-16 12:29pm
'A' to 'W' comes out as 4 instead of 22.
It should be
`if (a > b) { d = 26 - d; }`
Richard Deeming 8-Oct-16 12:31pm
If you read the comments to the question, that's what the OP wanted. :)
Richard MacCutchan 8-Oct-16 12:33pm
No he wants W to A to be 4, not A to W.