I have an app with an EditText
and a button named "forward". All I want is just when I type "a" in the EditText
and click the button, the word "b" to be typed in the EditText
, "c" if pressed again and so on. I have tried:
value = edt.getText();
edt.setText(value + 1);
But that of course will print the initial string followed by the number "1". Any ideas? Thanks a lot
Because your compiler defaults char to signed char . So the range of values for it is -128 to 127, and incrementing 127 is triggering wraparound. If you want to avoid this, be explicit, and declare your variable as unsigned char .
Software Engineering C C uses char type to store characters and letters. However, the char type is integer type because underneath C stores integer numbers instead of characters.In C, char values are stored in 1 byte in memory,and value range from -128 to 127 or 0 to 255.
Tested and works
All letters can be represented by their ASCII values.
If you cast the letters to an int
, add 1, and then cast back to a char
, the letter will increase by 1 ASCII value (the next letter).
For example:
'a'
is 97
'b'
is 98
So if the input was 'a'
and you casted that to an int
, you would get 97
. Then add 1 and get 98
, and then finally cast it back to a char
again and get 'b'
.
Here is an example of casting:
System.out.println( (int)('a') ); // 97
System.out.println( (int)('b') ); // 98
System.out.println( (char)(97) ); // a
System.out.println( (char)(98) ); // b
So, your final code might be this:
// get first char in the input string
char value = et.getText().toString().charAt(0);
int nextValue = (int)value + 1; // find the int value plus 1
char c = (char)nextValue; // convert that to back to a char
et.setText( String.valueOf(c) ); // print the char as a string
Of course this will only work properly if there is one single character as an input.
A simpler way would be:
char value = edt.getText().toString().charAt(0);
edt.setText(Character.toString ((char) value+1));
Here the value + 1
adds the decimal equivalent of the character and increments it by one.. Here is a small chart:
Whats happens after 'z'? ... it wont crash.. see here for the full chart..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With