Java: Adding two numeric character arrays - java

My question seems very simple, but I've tried searching for a specific answer and have found none. I've found answers similar to what I've been looking for, but they've only managed to confuse me further:
All I want to do is add two character arrays and print the resulting array. The project deals with binary numbers, but I'll deal with base-2 arithmetic later, so just pretend they're base-10 numbers.
char[] array = {'1', '0', '0', '1'};
char[] array2 = {'1', '1', '0', '0'};
char[] sum = new char[4];
for(i=0; i < 4; i++){
sum[i] = char(array[i] + array2[i]);
System.out.print(sum[i] + " ");
}
My answer is "b''b" when I run it, so it seems some ASCII conversion is happening I guess? My expected answer should be "2101" and I realize the problem is in my casts, I just don't know how to proceed. Sum must remain a character array as part of the program's parameters.
EDIT: I KNOW using an int array for sum would solve this problem. As I stated in my original post, sum MUST remain a character array as part of the parameters of this project.

You can use Character.toString() to conver a char to String. Second, use Integer.parseInt() to convert a char to int. Then add those integers. Finally, use Character.forDigit(digit, 10) to convert the int (digit) to char.
char[] array = { '1', '0', '0', '1' };
char[] array2 = { '1', '1', '0', '0' };
char[] sum = new char[4];
for (int i = 0; i < 4; i++) {
sum[i] = Character.forDigit(
Integer.parseInt(Character.toString(array[i])) + Integer.parseInt(Character.toString(array2[i])),
10);
System.out.println(sum[i]);
}
Output:
2
1
0
1
Of course you can avoid this, if you use an array of integers:
int[] array = {1, 0, 0, 1};

Your assumption that ASCII math is coming into play is correct. char variables are glorified int variables under the hood. Adding char variables basically takes the ASCII decimal value, adds those values and then gives you the ASCII character representation. This is a bit over-simplified, but I wanted to give you an idea of why this is happening.
For example, if '1' is decimal 49 in ASCII, '1' + '1' = 49 + 49 = 98. 98 in ASCII is 'b'.
I'd suggest just switching the type of arrays you are using to be int:
int[] array = {1, 0, 0, 1};
int[] array2 = {1, 1, 0, 0};
int[] sum = new int[4];
for(int i = 0; i < 4; i++) {
sum[i] = array[i] + array2[i];
System.out.print(sum[i] + " ");
}

try to cast the character into int . something like
int i = Integer.parseInt(array[0] + "");
Similarly you can proceed for rest and then perform addition

If you want to add 1+1 and get 2 then don't use char array. Use int array, or cast it into int using
int i = Integer.parseInt(array[0] + "");

The problem is in your adding.
Basically, what you'll need to do is sum the first character, array[i] + (array2[i] - '0').
This is because with the first character, you're getting a correct ASCII-0-indexed value, but the second one should just be a number of steps from the ASCII 0-index, so "- '0'", will give you just the difference.

Try this. It works. Change this sum variable from char[] array to int[] array
public static void main(String[] args) {
char[] array = {'1', '0', '0', '1'};
char[] array2 = {'1', '1', '0', '0'};
int[] sum = new int[4];
for (int i = 0; i < 4; i++) {
sum[i] = Integer.parseInt(array[i] + "") + Integer.parseInt(array2[i] + "");
System.out.print(sum[i] + " ");
}
}
Output
run:
2 1 0 1 BUILD SUCCESSFUL (total time: 0 seconds)

Use int array instead of char array and store the result into your sum char array. But use int array as we'll for storing result. This will help you in dealing with numerical operation

I think this sounds like a question asked in interviews. The intention of the question is to add Integer characters from two arrays and output the result as an array of characters.
char[] a = { '4', '5', '6' };
char[] b = { '7', '8', '9' };
Integer c = Integer.parseInt(String.valueOf(a)) + Integer.parseInt(String.valueOf(b)); //456 + 789 = 1245
final char[] d = c.toString().toCharArray(); // d = {'1',2,'4','5'}
This solution handles all the cases where the sum can end up with a carry.

Related

Setting each of the alphabet to a number

so I am trying to set each of the letter in the alphabet to a number like a = 1
b = 2 c =3 and so on.
int char = "a";
int[] num = new int{26};
for (int i = 0; i <num.length; i++){
System.out.print(i);
But after this i got Stuck so if you possible help me out. So when the users input a word like cat it would out put 3-1-20.
You can subtract 'a' from each char and add 1. E.g.
String input = "cat";
for (char c : input.toCharArray()) {
System.out.print(c - 'a' + 1);
}
The code you posted doesn't compile as you can't assign a String to an int and char is a reserved word (name of a primitive type)
int char = "a";
You also mention that you want the output formatted like this "3-1-20". This is one way to achieve that :
String input = "cat";
String[] out = new String[input.length()];
for (int i = 0; i < input.length(); ++i) {
out[i] = Integer.toString(input.charAt(i) - 'a' + 1);
}
System.out.println(String.join("-", out));
Both versions work only for lowercase English letters (a to z)
Assigning a number to a character is called an "encoding". As computers can only handle numbers internally, this happens all the time. Even this text here is encoded (probably into an encoding called "UTF-8") and then the resulting number is stored somewhere.
One very basic encoding is the so called ASCII (American Standard Code for Information Interchange). ASCII already does what you want, it assigns a number to each character, only that the number for "A" is 65 instead 1.
So, how does that help? We can assume that for the character A-z, the numeric value of a char is equal to the ASCII code (it's not true for every character, but for the most basic ones, it's good enough).
And this is why everyone here tells you to subtract 'A' or 'a': Your character is a char, which is a character, but also the numeric value of that character, so you can subtract 'A' (again, a char) and add 1:
'B' - 'A' + 1 = 2
because...
66 (numeric value of 'B') - 65 (numeric value of 'A') + 1 = 2
Actually, char is not ASCII, but UTF-8, but there it starts to get slightly bit more complex, so ASCII will suffice for the moment.
the best way of doing this is to convert the String to a byte[], like this:
char[] buffer = str.toCharArray();
Then each of the characters can be converted to their byte-value (which are constants for a certain encoding), like this:
byte[] b = new byte[buffer.length];
for (int i = 0; i < b.length; i++) {
b[i] = (byte) buffer[i];
}
Now look at the resulting values and subtract/add some value to get the desired results!

How do I shift the value of my char array in java?

What I'm trying to do is create an encryption method that shifts a char array taken from an input file by a determined amount of letters. I'm having trouble figuring out how to change the chars into ints and back.
THis is what I've got so far:
char [] sChar = new char[line.length()];
for(int i = 0; i < sChar.length; i++){
String s = reader.next();
sChar = s.toCharArray();
if(Character.isLetter(sChar[i])) {
char c = 'a';
int b = c;
sChar[i] += key;
Not sure what you are thinking.
I thought conversion int to character and back would be easy.
Just to freshen up the idea I checked
char xdrf = 'a';
System.out.println((int)xdrf); // output is 97
int idrf= 99;
xdrf = (char)idrf;
System.out.println(xdrf); // output is c
also if you key is a character you can directly sum it therefore statement
schar[i] += key;
should be good
more to it
idrf = idrf + 'd';
System.out.println(idrf); //output is 199
further using
System.out.println(Character.getNumericValue(idrf-20)); //output is 3
this all is working by ascii value. I am unsure if you would like ascii values to be used.

Convert int to array char in Java

I'm trying to convert a integer number to an array of chars without using String operations.
My attempt was:
int number = 12;
char[] test = Character.toChars(number);
for (char c : test)
System.out.println(c);
There is no output, and should give me:
'1'
'2'
How can I fix this? Thank you!
Try something like this:
int number = 12345;
char[] arr = new char[(int) (Math.log10(number) + 1)];
for (int i = arr.length - 1; i >= 0; i--) {
arr[i] = (char) ('0' + (number % 10));
number /= 10;
}
System.out.println(Arrays.toString(arr));
[1, 2, 3, 4, 5]
Note that floor(log10(n) + 1) returns the number of digits in n. Also, if you want to preserve your original number, create a copy and use that in the for-loop instead.
Also note that you might have to adapt the code above if you plan on also handling non-positive integers. The overall idea, however, should remain the same.
char[] test = Integer.toString(number).toCharArray();
Extract each digit of the number, convert it into a character(by adding '0') and store them into a char array. Let us know what you have tried.
+1 for #arshajii's code log10(n) + 1 is something new for me as well. If you intend to use Vectors instead of arrays you can also follow this procedure(But the Vector has elements in reverse order) in which you never need to calculate the size of number itself
public static Vector<Character> convert(int i) {
Vector<Character> temp = new Vector<Character>();
while (i > 0) {
Character tempi = (char) ('0' + i % 10);
i = i / 10;
temp.add(tempi);
}
return temp;
}

Double int conversion messup

I have no idea of why this code snippet produces the following output when I try to multiply 2 int values. This might be too dumb but I just dont get it. I have pasted the code and the output here
public static void main(String[] args) {
// TODO code application logic here
String numstring = "12122";
char[] numArray = numstring.toCharArray();
int num =0;
int index = 10;
int count = 0;
for(int i=numArray.length-1;i>=0;i--){
int ind = (int)(Math.pow(index,count));
System.out.print(numArray[i]+"*"+ind);
System.out.println(" prints as ----->"+numArray[i]*ind);
count++;
}
}
output:
2*1 prints as ----->50
2*10 prints as ----->500
1*100 prints as ----->4900
2*1000 prints as ----->50000
1*10000 prints as ----->490000
You're not multiplying two ints. Your multiply an int, ind, with a char, '2', whose ASCII value is 50 (at least in the first case). You could use an int[], or if you want to stick with the char[], you could do the following:
System.out.println(" prints as ----->"+ Character.getNumericValue(numArray[i]) * ind);
Characters are really integers under the hood, so for example, the character '2' has int value 50.
To see which integer corresponds to which character, check out the ascii table.
To do what you want, you should use Character.getNumericValue() method:
System.out.println(" prints as ----->"+Character.getNumericValue(numArray[i])*ind);

Java - Find High and Low Number in an Array

I'm trying to find the high and low number in an array, but I'm not sure why my codes not working correctly. It's giving me the output of 0 and 56. I understand why it's giving the 0, but where did the 56 come from?
package test;
public class Test {
public static void main(String[] args) {
int[] numbs = { '2', '4', '2', '8', '4', '2', '5'};
int count = 0;
int low = 0;
int high = 0;
while(count < numbs.length)
{
if(numbs[count]< low) {
low = numbs[count];
}
if(numbs[count]> high) {
high = numbs[count];
}
count++;
}
System.out.println(low);
System.out.println(high);
}
}
You need to start the low low enough; currently, you start it at zero - too low to "catch" the lowest element of the array.
There are two ways to deal with this:
Use Integer.MAX_VALUE and Integer.MIN_VALUE to start the high and low, or
Use the initial element of the array to start both high and low, then process the array starting with the second element.
int low = Integer.MAX_VALUE;
int high = Integer.MIN_VALUE;
P.S. You would find strange numbers printed, because you used characters instead of integers:
int[] numbs = { 2, 4, 2, 8, 4, 2, 5};
Also.. It is probably printing the ASCII representation... use actual integers (I'm not sure if your usage of chars was intentional).
You use chars instead of ints at the array init block, this is immediately converted to ints to fit in the int[] array, but don't use its actual value, but the unicode value, where: 2 = 52 and 8 = 56.
'8' is char literal, not an int. The Java Language Specification defines char as follows:
The integral types are byte, short, int, and long [...] and char, whose values are 16-bit unsigned integers representing UTF-16 code units.
If you use a char where an int is expected, the char is implicitly converted to int. Since char is a numeric type, this will preserve its numeric value, i.e. its UTF-16 code point. The utf-16 code point of 8 is 56.
Treating char as a numeric type can be useful. For instance, we can compute the n-th letter of the alphabet by
char nthLetter = (char) `A` + n;
or find the numeric value of a digit by
if ('0' <= digit && digit <= '9')
return value = digit - '0';
else
throw new IllegalArgumentException(digit);
You should set both the low and high to the value in the first position of the array.
int low = numbs[0];
int high = numbs[0];
If the first position is indeed the lowest value it will never be swapped, otherwise it will be swapped with a lower number, the same happen to the highest number.
You want an array of ints that you should declared like such:
int[] numbs = {2, 4, 2, 8, 4, 2, 5};
You are getting 56 as the highest value because the decimal representation of the char '8' according to the ASCII table is 56.

Categories

Resources