can't cast int to char with Java - java

I was given an assignment to generate a random number between 1 to 26 then convert that number to a letter from 'a' to 'z'.
the random generating part looks fine but when I try to cast the number to char, I would just get an empty square-like box!
why is that?
import java.util.Random;
public class NumbersToLetters
{
public static void main(String[] args)
{
Random n;
int num;
n=new Random();
//generating a random number from 1 to 26
num=Math.abs(((n.nextInt())%26)+1);
//cast from int to char
char myChar = (char) num;
System.out.println ("Number - " + num);
System.out.println ("Char - " + myChar);
//I'm sure that my answer is right but no matter what I do,
//it won't output a letter, all I get is a square-like box..
}
}

You're generating a number between 1 and 27 (inclusive). If you look at what those characters correspond to, you'll see that none of them are actually printable.
You should do your calculation as + 'a' instead of + 1
n.nextInt(26) + 'a';
This will give you the correct offset (which happens to be 97) to find the lower case letters.

The character 'a' is not encoded as 1, but as 97. You need to add 'a' to a value between 0 and 25 (inclusive) to get the expected result:
num = 'a'+n.nextInt(26);

I'm not a Java guru like others on here, but it might have something to do with not being encoded correctly? Look up UTF-8 encoding and just research type casting

Related

Converting a hexadecimal string to integer value without pre-made syntax

I'm taking a computer organization class in college. I was tasked with writing a java program that takes a user-inputted string, calls a function that converts said string into a hexadecimal integer, and then outputs the results.
The kicker is that I can't use any existing syntax to do this. for example, Integer.parseInt(__,16) or printf. It all neds to be hardcoded.
Now I'm not asking you to do my homework for me, just wanting to be put in the right direction.
So far, I've made this but can't seem to get the method created right:
import java.util.*;
public class Demo_Class
{
public static void main(String[] args)
{
Scanner AI = new Scanner(System.in);
String str;
System.out.println("Please input a hexadecimal number: ");
str = AI.nextLine();
converter(str);
}
public static int converter(String in)
{
String New = new String();
for(int i = 0; i<= in.length(); i++)
{
New += in.charAt(i);
System.out.println(New + 316);
}
return 0;
}
}
Consider this, lets says you have the hex value 1EC which in hex digits would be 1, E, C. In decimal they would be 1, 14, 12.
so set sum = 0.
sum = sum*16 + 1. sum is now 1
sum = sum*16 + 14 sum is now 30
sum = sum*16 + 12 sum is now 492
So 492 is the answer.
If you have a string of 1EC you need to convert to characters and then convert those characters to the decimal equivalent of hex values.
Try this on paper until you get the feel and then code it. You can check your results using the Integer method you mentioned.
#WJS gave a good hint, I'd just like to add that the charAt() returns the char, which is encoded in ASCII.
As you can see in the ASCII table, the characters A-F have decimal values from 65 to 70, while 0-9 go from 48 to 57 so you'll need to use them to convert the ASCII characters to their intended value.
To do so, you can either get the decimal value of a character by casting to short like short dec = (short)in.charAt(i);, or directly use the characters like char current = in.charAt(i) - 'A'.
With this in mind, all that's left is some calculation, I'll leave that as the homework. :)
Also:
you are looping one character more than needed, change the i <= in.length() to i < in.length(), since it's going from 0
I don't know what that 316 "magic number" is, if it does mean something, declare a variable with a meaningful name, like:
final int MEANINGFUL_NAME = 316;

trying to perform arithmetic operations on numbers expressed as a character string

I am obviously new to java. I have this assignment where I am supposed to write a program which performs arithmetic operations on numbers expressed as a character string.
I don't know where to start. I have tried googling, looking through my book, big java, in the relevant sections but can't seem to find helpful information.
I found a program that have completed the same assignment but I want to learn write my own and understand how to go about.
I can show you one of the methods that he used.
I have bolded a few comments where I get confused.
public static String add(String num1, String num2) {
while (num1.length() > num2.length()) {
num2 = "0" + num2;
}
while (num1.length() < num2.length()) {
num1 = "0" + num1;
}
int carry = 0; // whats the point of this?
String result = "";
// look at the for loop bellow. I don't understand why he is converting the strings to ints this
// way? this doesn't even return the correct inputed numbers?
for (int i = 1; i <= num1.length(); i++) {
int digit1 = Character.getNumericValue(num1.charAt(num1.length() - i));
int digit2 = Character.getNumericValue(num2.charAt(num2.length() - i));
int sum = digit1 + digit2 + carry;
carry = sum / 10;
result = (sum % 10) + result;
// why is he dividing the sum with 10? If the user inputs a 5, would't the result become 0.5
// which isn't a valid int value? this line is also confusing
}
if (carry > 0) {
result = carry + result;
}
return result;
}
Any explanation or even guidance to a page where I am trying to do is explained would be very appreciated.
I found a program that have completed the same assignment but I want to learn write my own and understand how to go about.
That is the right idea. I suggest that you stop looking at the code that you found. (I'm sure that your teachers don't want you to look up the answers on the internet, and you will learn more from your homework if you don't do it.)
So how to proceed?
(I am assuming that you are supposed to code the methods to do the arithmetic, and not just convert the entire string to a primitive number or BigInteger and use them to do the arithmetic.)
Here's my suggested approach:
What you are trying to program is the equivalent of doing long addition with a pencil and paper. Like you were taught in primary school. So I suggest that you think of that pencil-and-paper procedure as an algorithm and work out how to express it as Java code. The first step is to make sure that you have the steps of this algorithm clearly in your head.
Try to break the larger problem into smaller sub-problems. One sub-problem could be how to convert a character representing a decimal digit into an integer; e.g. how to convert '1' to 1. Next sub-problem is adding two numbers in the range 0 to 9 and dealing with the "carry". A final sub-problem is converting an integer in the range 0 to 9 into the corresponding character.
Write sample Java code fragments for each sub-problem. If you have been taught about writing methods, some of the code fragments could be expressed as Java methods.
Then you assemble the solutions to the sub-problems into a solution for the entire problem. For example, adding two (positive!) numbers represented as strings involves looping over the digits, starting at the "right hand" end.
As part of your program, write a collection of test cases that you can use to automate the checking. For example:
String test1 = add("8", "3");
if (!test1.equals("11")) {
System.out.println("test1 incorrect: expected '11' go '" +
test1 + "'");
}
Hints:
You can "explode" a String to a char[] using the toCharArray method. Or you could use charAt to get characters individually.
You can convert between a char representing a digit and an int using Character methods or with some simple arithmetic.
You can use + to concatenate a string and a character, or a character and a string. Or you can use a StringBuilder.
If you need to deal with signed numbers, strip off and remember the sign, do the appropriate computation, and put it back; e.g. "-123 + -456" is "- (123 + 456)".
If you need to do long multiplication and long division, you can build them up from long addition and long subtraction.
You can convert a number in String format to a number in numeric format by “long n = Long. parseLong(String)” or “Long n = Long.valueOf(String)”. Then just add 2 long variables using a + sign. It will throw NumberFormatException if the String is not a number but a character. Throw that exception back to the caller.
The first part of the code pads both numbers to equal lengths.
e.g. "45" + "789" will be padded to "045" + "789"
The for loop evaluates one character at a time, starting from the right hand most.
iteration 1 -> (right most)
5 + 9 -> 14
when you divide an integer with another integer, you will always get an integer.
hence carry = 14/10 = 1 (note: not 1.4, but 1, because an int cannot have decimal places)
and the remainder is 14 % 10 = 4 (mod operation)
we now concatenate this remainder into "result" (which is "" empty)
result = (14%10)+ result; // value of result is now "4"
iteration 2 -> (second right most)
4+8 + (carry) = 4 + 8 + 1 = 13
same thing, there is a carry of 13/10 = 1
and the remainder is 13%10 = 3
we concatenate the remainder into result ("4")
result = (13%10) + result = 3 +"4" = "34"
iteration 3->
0 + 7 + 1 = 8
this time 8/10 will give you 0 (hence carry = 0)
and 8%10 will give a remainder of 8.
result = 8 + "34" = "834"
after all the numbers have been evaluated, the code checks if there are anymore carry. if the value is more than 0, then that value is added to the front of the result.

Java int value type to Character

I am new to java and and working on a crud calculator that takes input and holds it in an ArrayList to perform the calculations.
I am trying to add two values in an ArrayList<Character> and then replace the "+" with the sum.
if(listEqu.contains('+')) {
while(listEqu.indexOf('+') > -1) {
int plus = listEqu.indexOf('+');
int prev = listEqu.get(plus-1);
int nxt = listEqu.get(plus+1);
Character sum = (char) (nxt + prev);
listEqu.set(plus, sum);
System.out.println(listEqu);
}
}
When the input is 1+1, this returns [1, b, 1].
What I want is to return [1, 2, 1] .
Any advice? Thanks!
The problem is actually that adding two characters doesn't do what you expect.
The value of '1' + '1' is 'b'. If you want the next digit after '1' you add the integer 1 to it; i.e. '1' + 1 is '2'.
For a deeper understanding, you need to understand how character data is represented in Java.
Each char value in Java is an unsigned 16 bit integer that corresponds to a code point (or character code) in the Unicode basic plane. The first 128 of these code points (0 to 127) correspond to a characters in the old ASCII character set. In ASCII the codes that represent digits are 48 (for '0') through to 39 (for '9'). And the lowercase letters are 97 (for 'a') through to 122 (for 'z').
So as you can see, '1' + '1' -> 49 + 49 -> 98 -> 'b'.
(In fact there is a lot more to it than this. Not all char values represent real characters, and some Unicode code-points require two char values. But this is way beyond the scope of your question.)
How could I specify addition of numbers instead of addition of the characters?
You convert the character (digit) to a number, perform the arithmetic, and convert the result back to a character.
Read the javadoc for the Character class; e.g. the methods Character.digit and Character.forDigit.
Note that this only works while the numbers remain in the range 0 through 9. For a number outside of that range, the character representation consists of two or more characters. For those you should be using String rather than char. (A String also copes with the 1 digit case too ...)
Few things that can be improved with your code :
Converting the characters 1 into equivalent integer value:
int prev = Integer.parseInt(String.valueOf(listEqu.get(plus-1)));
int nxt = Integer.parseInt(String.valueOf(listEqu.get(plus+1)));
// Note : int prev = listEqu.get(plus-1) would store an ascii value of `1` to prev value i.e 49
And then converting the sum of those two values into Character back to be added to the list using Character.forDigit as:
Character sum = Character.forDigit(nxt+prev,10);
// Note Character sum = (char) (nxt + prev); is inconvertible
// and char sum = (char) (nxt + prev); would store character with ascii value 98(49+49) in your case 'b' to sum
you should first convert your prevand nxt to int value and then add them together like follow:
if(listEqu.contains('+')) {
while(listEqu.indexOf('+') > -1) {
int plus = listEqu.indexOf('+');
int prev = Integer.parseInt(listEqu.get(plus-1));
int nxt = Integer.parseInt(listEqu.get(plus+1));
Character sum = (char) (nxt + prev);
listEqu.set(plus, sum);
System.out.println(listEqu);
}
}
nxt and prev are char values. Tey take their value in the ASCII table, where '1' is 61 and 'b' is 142 (thus, '1' + '1' = 'b')
You need to substract '0' to get the number they represent. ('1' - '0' = 61 - 60 = 1)
The sum is not necessarily writable with one character, so you shouldn't put it back into a char array.
If you want to convert an integer to a string, use Integer.toString(i).
(And, if you want to, get the first character of the string and put it in the array, if that's what you want)
You need to parse the characters to their corresponding decimal value before you perform the addition, and then back to a character after. The methods Character.digit(char, int) and Character.forDigit(int, int) can do that (and I would use char since that is the type of prev and nxt). Like,
char prev = listEqu.get(plus - 1);
char nxt = listEqu.get(plus + 1);
Character sum = Character.forDigit(Character.digit(nxt, 10)
+ Character.digit(prev, 10), 10);

Treat octal numbers as decimals

I'm learning JAVA and recently I had the same problem with a few training tasks.
I have a some numbers and some of them are starting with 0. I found out that these numbers are octal which means it won't be the number I wanted or it gives me an error (because of the "8" or the "9" because they are not octal digits) after I read it as an int or long...
Until now I only had to work with two digit numbers like 14 or 05.
I treated them as Strings and converted them into numbers with a function that checks all of the String numbers and convert them to numbers like this
String numStr = "02";
if(numStr.startsWith("0")) {
int num = getNumericValue(numStr.charAt(1));
} else {
int num = Integer.parseInt(numStr);
}
Now I have an unkown lot of number with an unknown number of digits (so maybe more than 2). I know that if I want I can use a loop and .substring(), but there must be an easier way.
Is there any way to simply ignore the zeros somehow?
Edit:
Until now I always edited the numbers I had to work with to be Strings because I couldn't find an easier way to solve the problem. When I had 0010 27 09 I had to declare it like:
String[] numbers = {"0010", "27", "09"};
Because if I declare it like this:
int[] numbers = {0010, 27, 09};
numbers[0] will be 8 instead of 10 and numbers[2] will give me an error
Actually I don't want to work with Strings. What I actually want is to read numbers starting with zero as numbers (eg.: int or long) but I want them to be decimal. The problem is that I have a lot of number from a source. I copied them into the code and edited it to be a declaration of an array. But I don't want to edit them to be Strings just to delete the zeros and make them numbers again.
I'm not quite sure what you want to achieve. Do you want to be able to read an Integer, given as String in a 8-based format (Case 1)? Or do you want to read such a String and interpret it as 10-based though it is 8-based (Case 2)?
Or do you simply want to know how to create such an Integer without manually converting it (Case 3)?
Case 1:
String input = "0235";
// Cut the indicator 0
input = input.substring(1);
// Interpret the string as 8-based integer.
Integer number = Integer.parseInt(input, 8);
Case 2:
String input = "0235";
// Cut the indicator 0
input = input.substring(1);
// Interpret the string as 10-based integer (default).
Integer number = Integer.parseInt(input);
Case 3:
// Java interprets this as octal number
int octal = 0235;
// Java interprets this as hexadecimal number
int hexa = 0x235
// Java interprets this as decimal number
int decimal = 235
You can expand Case 1 to a intelligent method by reacting to the indicator:
public Integer convert(final String input) {
String hexaIndicator = input.substring(0, 2);
if (hexaIndicator.equals("0x")) {
return Integer.parseInt(input.substring(2), 16);
} else {
String octaIndicator = input.substring(0, 1);
if (octaIndicator.equals("0")) {
return Integer.parseInt(input.substring(1), 8);
} else {
return Integer.parseInt(input);
}
}
}

Java CASE why do i get a complete differet int back with and without using ' '

As a Java beginner I'm playing around with a case statement at this point.
I have set: int d = '1'; And with: System.out.println("number is: " + d);, this returns 51.
Now I found out that if I set it as: int d = 1;, it does return 1.
Now my question is why does it return 49 when I set it as '3'? What difference do the ' ' make?
My code that returns 49:
int a = '1';
switch(a)
{
case '1' :
System.out.println("Good");
break;
case '2' :
case '3' :
System.out.println("great");
break;
default :
System.out.println("invalid");
}
System.out.println("value: " + a);
'1' is the character '1', whose integer value is 49. Each character has a numeric value in the range from 0 to 2^16-1. Therefore 1 and '1' are different integer values.
With ' (single quotes) around a character you tell the compiler that the value in between is a character (variable type char in Java). Generally, computers only understand numbers so characters get represented as numbers in memory as well. The value of the character '1' is 49. You want to actually save the value 1 in memory and use that to calculate things. So, you have to tell the compiler that you want this to be interpreted as an actual number and not as a character.
To summarize:
'1' is the character that prints the number 1
1 is the actual number 1
This means 1 and '1' have different integer values.
You can look at the integer value of the most commonly used characters in coding here: ASCII Table
In Java the character values are stored as int internally. That means when you assign a char value using 'A' to an int type, the compiler casts the char value into int and thus the UTF-16 Code unit value is stored into the int variable.
Try this one as well:
int yourInt = 33;
char ch = (char) yourInt;
System.out.println(yourInt);
System.out.println(ch);
1 is interpreted as a character whose value is 49.
Do:
int a = 1;
switch(a) {
case 1:
...
Or, if you go with your current code:
System.out.println("value: " + Integer.parseInt((char)a+'');
It is happens because for some weird reason java treat char type as short.
Your '1' expression is constant expression of type char. It is stored internally as some numeric value. Usually all goes fine with this approach for example System.out.println('1') will print exactly what you expect.
But when you write int a = '1'; you char value is converted to int value because char behave like short int there.
PS: if there was no implicit conversion between char and int (which anyway have no sense) you just got compilation error.
When you declare int d='1'; then 1 is not treated as integer it is a character. It is converted to 49 according its unicode value. similarly character '3' will coverted to 51. Jvm do implicit type casting from character to integer.
you should try this code
char c = '3';
int a ='1';
System.out.println(c);
System.out.println((int)c);
You will get output as
3
51
49

Categories