Char to Int Conversion Java - java

public static void main (String[] args)
{
char x = 'x';
char w = x-1;
System.out.println(w);
}
Whenever I try to run the following code, I got a loss of precision. The compiler tells me that the line char w = x-1 doesn't seem to work. How can I make the char value equal w?

You need to re-cast to char as you converted to int
char x = 'x';
char w = (char)(x - 1);
System.out.println(w);
That will output w.

Because 1 is an int. You need a cast. Like,
char w = (char) (x - 1);

Related

Understanding char cast

Im not understanding casting in java, char casting in particural. I'm not able to predict the outcome of this code,since I don't understand what the casting of char will "reproduce".Some explanation would be great! Thanks
public class test {
public static void main(String[] args) {
int u = 10;
double v = 22.105;
byte w = 100;
char x = 'a';
float y = 20.5f;
short z = 50;
double d_Value = (float) ((char) (u/v) + y);
Out.print(d_Value);
}}
char is an integer-based data type, so you'd lose the precision from the double result on u/v, giving you a 0 number (or the \0 char). Then it adds 20.5F for the final result: 20.5.
Casting is a higher precedence than most operators in the language, so that cast is relevant before the + operation.

Averaging two characters based on their ASCII value

I am new to java programming. I am having a problem on how to use the method for char here. What do you return in the char method to get the average of the ASCII values in the main body? Thanks!
public static int average(int i,int j)
{
return (i + j) / 2;
}
public static double average(double a,double b)
{
return (a + b) / 2;
}
public static char average(char first,char second)
{
return ?;
}
public static void main(String[] args)
{
char first = 'a', second = 'b';
int i = 5, j = 12;
double a = 5.5, b = 8.5;
System.out.println("Average of (x,y) is : " + average(first,second));
System.out.println("Average of (a,b) is : " + average(a,b));
System.out.println("Average of (i,j) is : " + average(i,j));
}
Chars are at the end ints, so the average char makes no much sense since the result will be char again, i.e consider this case:
what is the average between 'a' and 'b'? a is represented with 97, b with 98, ave = 97.5 but there is no char value for 97.5, in fact, that will be rounded to int pointing to 97 again, so average for 'a' and 'b' is 'a', kind of weird isnt ?
Anyway you can do
public static char average(char first,char second)
{
return (char) ( (first + second) / 2);
}
note that since dividing by int literal 2 you will need to cast the result to char again..
In Java, char values are automatically typecasted to int type.
As you have already got average(int i,int j), you don't need to write any average(char first,char second).
So when you call average(first,second)), then the method which take int arguments i.e., average(int i,int j) will be invoked.

How to get sum of char values produced in a loop?

Sorry if the title is misleading or is confusing, but here is my dilemma.
I am inputting a string, and want to assign a value to each capitalized letter in the alphabet (A=1, .. Z=26) and then add the values of each letter in that string.
Example: ABCD = 10 (since 1 + 2 + 3 + 4)
But I don't know how to add all the values in the string
NOTE: This is only for capitalized letters and strings
public class Test {
public static void main(String[] args) {
Scanner scannerTest = new Scanner(System.in);
System.out.println("Enter a name here: ");
String str = scannerTest.nextLine();
char[] ch = str.toCharArray();
int temp_integer = 64;
for (char c : ch) {
int temp = (int) c;
if (temp <= 90 & temp >= 65){
int sum = (temp - temp_integer);
System.out.println(sum);
}
}
}
}
So, as you can see I print out the sum for each time its looped,
meaning: if I input "AB", the output will be 1 and 2.
However, I want to go a step further, and add these two values together, but I'm stumped, any suggestions or help? (NOTE: this is not a assignment or anything, just practising problem sets)
I would prefer to use the character literals. You know that the range is A to Z (1 to 26), so you can subtract 'A' from each char (but you need to add 1 because it doesn't start at 0). I would also call toUpperCase on the input line. Something like,
Scanner scannerTest = new Scanner(System.in);
System.out.println("Enter a name here: ");
String str = scannerTest.nextLine().toUpperCase();
int sum = 0;
for (char ch : str.toCharArray()) {
if (ch >= 'A' && ch <= 'Z') {
sum += 1 + ch - 'A';
}
}
System.out.printf("The sum of %s is %d%n", str, sum);
Which I tested with your example
Enter a name here:
ABCD
The sum of ABCD is 10
Using 64 to represent the character before 'A' in the ascii table is difficult to understand, you can perform substration between characters in Java directly.
So if 'A' represent 1, then just do c - 'A' + 1 will give you the corresponding integer value for each capitalized letter.
To get the sum, just sum up: initialize the sum as 0, and in the for loop, add increment sum by the value you calculated. You can use the incremental assignment operation: +=
Scanner scannerTest = new Scanner(System.in);
System.out.println("Enter a name here: ");
String str = scannerTest.nextLine();
char[] ch = str.toCharArray();
int sum = 0;
for (char c : ch) {
sum += c - 'A' + 1;
}
System.out.println(sum);
Change only your for to these:
int sum = 0;
for(int i = 0; i < ch.length; i++){
sum += (int) ch[i] - 96;
System.out.println(sum);
}
The sum += (int) ch[i] - 96; is because the char a is the value 97, as your say, you want char a corresponde to 1, note that a is different than A
Check the char value here: https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html
This was tested and worked fine! Good Luck
It would look something like this (in C programming language) which you can easily modify for other programming languages:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int i;
char word[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
unsigned int sum = 0;
unsigned int charVal;
for (i=0; i < strlen(word); ++i) {
charVal = word[i] - 'A' + 1;
printf("Value of %c is %d\n", word[i], charVal);
sum += charVal;
}
printf("Sum of %s = %d\n", word, sum);
return(0);
}
The trick is to take the character value, subtract the baseline 'A' value and add 1 to arrive at your calculation range:
charVal = word[i] - 'A' + 1;
Achieve the same in a concise way by employing Java 8's lambda functions
String str = "ABCD";
int sum = str.chars()
.filter(c -> c >= 'A' && c <= 'Z')
.map(c -> 1 + c - 'A')
.reduce(0, Integer::sum);

Casting issue in JAVA

I am having trouble casting from a string to a char then to a double. I'm trying to calculate a simple expression 1+2 but when I pop it from a stack its 50.0 and 49.0 respectively. Then adds to 99.0. My code is below.
The expression is '1+2'
public static double calculate (String expression){
Stack<Character> calc = new Stack();
expression.replaceAll("\\s+","") ;
double result = 0;
for(int i = 0; i < expression.length(); i++){
calc.push((char) expression.charAt(i));
}
double one = (double) calc.pop();
char expr = calc.pop();
double two = (double) calc.pop();
if(expr == '-'){
result = one - (1*two);
} else if (expr == '+'){
result = one + (1*two);
}
System.out.println(result);
return result;
}
The problem is that when you do a direct cast to a number like this
(double) calc.pop();
...you are actually getting the ascii values of the characters '1' (ascii 49) and '2' (ascii 50).
You need to parse the character. Something like this will work:
Double.parseDouble(calc.pop().toString());

Bitwise operations - get the next char in ASCII table

How can I write a program that will use bitwise operation to take the next value in the ASCII table?
Input: char from ASCII table
Output: the next char from the ASCII table.
For example, if I get 'a' as input, the program should return 'b'.
If I get '7' as input, the program should return '8'. and so on...
Just add 1 (character can be treated as being int16):
char value = 'a';
char next = (char) (value + 1); // <- next == 'b'
Just Increment by 1.
Input = 'a';
Output = ++Input;
Very simple. Just cast your char as an int.
char character = 'a';
int ascii = (int) character;
and then you need to add 1 in ascii
++ascii;
and convert it back...
char c=(char)ascii ;
System.out.println(c);
Here's a method that will add 1 to its argument using only bit-wise functions.
public void test() {
String s = "Hello";
StringBuilder t = new StringBuilder(s.length());
for (int i = 0; i < s.length(); i++) {
t.append((char) inc(s.charAt(i)));
}
System.out.println(s);
System.out.println(t.toString());
}
private int inc(int x) {
// Check each bit
for (int i = 0; i < Integer.SIZE; i++) {
// Examine that bit
int bit = 1 << i;
// If it is zero
if ((x & bit) == 0) {
// Set it to 1
x |= bit;
// And stop the loop - we have added one.
break;
} else {
// Clear it.
x &= ~bit;
}
}
return x;
}
prints
Hello
Ifmmp

Categories