简体   繁体   中英

Representing letters as numbers in java

I was wondering how you would represent letters as integers in java. I am working on a problem where I have to find the mid letter between a two lettered word. For example, I would choose the word 'go' and provide each letter with an assigned integer value to find the midpoint letter. Can anyone help me out with this or just point me in the right direction to go about solving on how to get the midpoint letter between a two letter word?

That is simple

    int a = 'a';
    int c = 'c';
    char mid = (char) ((a + c) / 2);
    System.out.println(mid);

prints

b

(int)str.charAt(i) will get you an integer value (the ASCII value). For "regular" letters, this should allow you to do what you want.

str = "GO";
midLetter = Character.toChars(((int)str.charAt(0) + (int)str.charAt(1))/2);

I think I got the brackets to match...

If by "letters" you're referring to the char primitive type, then they are already represented by integers behind the scenes. From the Java Tutorials :

The char data type is a single 16-bit Unicode character. It has a minimum value of '\' (or 0) and a maximum value of '\￿' (or 65,535 inclusive).

So you can assign a char literal to an int variable for example:

int g = 'g';
int o = 'o';

That should be enough to get you started.

In java (and most other language) characters are actually represented as numbers. Google for 'ascii table', and you'll find out lowercase a is actually 97.

Assuming you want to index lowercase a as 0, then given arbitrary character from a string, you can subtract it with the 'a' chacater, and you will get the index

String str = ...;
for(int i=0; i<str.length(); i++) {
   char c = str.charAt(i);
   int cIndex = c - 'a';

   // do something with cIndex...
}

If the given letter is of char then convert the type (int)yourword. Then find the midpoint

Character.getNumericValue returns a numeric value for each character. So, each letter has a unique numeric value via the Character class.

This could be the starting point for your ordering, although you might need to consider case, etc.

You should be able to go back and forth from int to char and perform arithmetic on your char values:

char median = 0;
for(char ch=65; ch<91; ch++) {
    System.out.println(ch);
    median += ch;
}
median = (char)(median/26);
System.out.println("=====");
System.out.println("Median leter in the alphabet: "+median);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM