Reading an array to find the middle char from two given chars
I am trying to refresh my java memory from when I was in college so i decided to do over some practice exercises i had. I am stuck one this question.
Implement a method named letter that will ask the user to enter a word of 2 letters. The first letter should be lower than the second (alphabetical order) The method will print to the screen the letter (of the alphabet) that is midway between the first and the last letters.
If the word is ‘am’ then the output should be: g
so far i have this but I'm not sure if an array should be used at all or should i use a switch statement to go through the whole alphabet. but then if i use a switch statement i need 26 cases.
What i want to do with the array is sort through it find the letters that match char at 0 and 1 find the length divide by 2 and then print the letter that in the middle.
[/CODE] public void letter(){
String word;
char firstLetter;
char secLetter;
do{
System.out.println("Enter a two letter word (word must be in alphabetical order).");
word = scan.nextLine();
word.toLowerCase();
firstLetter = word.charAt(0);
secLetter = word.charAt(1);
}while(firstLetter > secLetter);
char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
Re: Reading an array to find the middle char from two given chars
Quote:
Originally Posted by
rcheeks23
I'm not sure if an array should be used at all
You could do this,
Code:
char firstLetter = 'a';
char secLetter = 'm';
char midLetter = (char) ((firstLetter + secLetter)/2);
System.out.println(midLetter);
This works because characters in Java have an integral number encoding where the order of the Latin letters 'a' to 'z' corresponds to the order these letters have in the English alphabet. You're in fact already making use of this ordering in your posted code when you do "while (firstLetter > secLetter)". The capital letters 'A' to 'Z' are ordered the same but the encoding is different. For example if the user enters "AM it will work but with "Am" or "aM" it won't.
In the midLetter expression above the chars are implicitly cast to ints, the middle int is calculated and then explicitly cast back to char. Note that the order of the chars doesn't matter that is "am" will yield the same result as "ma".
Re: Reading an array to find the middle char from two given chars
wow i really over thought that, its that simple. Thank you!