Java - charAt getting wrong character - java

I am trying to make an algorithm that will do the following:
64
797
7
===
79
that will take 7, multiply it by 7, and then write the last digit of the answer down and then multiply it by seven and add the first digit of 7 times 7, and so on - so if you do it three times (write it down), you get what I wrote up there as a multiplication.
I got a not good code, instead of showing (for example) whats above in this form:
7,9,4
9,7,6
and so on I get something like this:
7, 9, 52
9, 55, 54
My code:
for(int i = 0; i<3; i++){//Run the code three times
temp=upper*7%10+tens;//get the temp but keeping the upper because I am going to need it for the tens part
tens=(upper*7+"").charAt(0);//get the first character of upper*7
System.out.println(upper+", "+temp+", "+tens);
upper=temp;
}
As far as I can see the problem is in the charAt, because obviously the first character of 7*7 is not 52.
EDIT
Now that the code is working fine I have another problem. I tried my new working code (put tens as the int value of the string value of the char instead of just the char), I have another problem. Hooray!
Last tens: 0 Now's plain number:7, New:9, Tens:4
Last tens: 4 Now's plain number:9, New:7, Tens:6
Last tens: 6 Now's plain number:7, New:15, Tens:4
Last tens: 4 Now's plain number:15, New:9, Tens:1
Last tens: 1 Now's plain number:9, New:4, Tens:6
My code now is as the same as the old code just with the tens fixed. But now, I am getting 15 for a number. That is supposed to be a digit. Whats wrong? I honestly don't know if the code I wrote will fullfil my purpose. What code will?

I strongly suspect that the problem is the type of tens. You haven't shown this in your code, but I suspect it's int.
So this line:
tens = (upper*7+"").charAt(0);
takes the first character from a string, and then stores it in an int. So for example, the character '4' is Unicode 52 ('0') is 48. The conversion to int just converts the UTF-16 code unit from an unsigned 16-bit value to a signed 32-bit value.
You're then displaying the value of tens - but if tens is indeed an int, it's going to display that as a number.
As far as I can see the problem is in the charAt, because obviously the first character of 7*7 is not 52.
Well, the first character of the string representation of 7*7 will be '4'. When that's been converted to an int, you'll see that as 52.
If you just want tens as a char, you should declare it as type char. You shouldn't do arithmetic with that value of course - but then when you display it, you'll see 4 displayed, because the string conversion will still treat it just as a character instead of as a number.

Related

How is an Integer converted to ASCII in Java Behind the Scenes?

I'm not asking for a built-in class that accomplishes this, I'm just curious on how encoding works behind the scenes in java. For example, An integer in java can be stored in 4 bytes, between -2147483648 and 2147483647. Lets use 500 as the number for this demonstration. From what I understand, the computer initially stores this number in memory as 1F4 in hex, which is 00000000 00000000 00000001 11110100 in binary. When I looked up how ASCII works, it encodes each digit 0-9 to its corresponding ASCII value (0 translates to 048). However, how is the binary number stored in ram able to separate each digit so that each digit can be encoded to its corresponding ASCII value? We know that the number is 500, but this is just an abstraction. The computer just sees 1's and 0's. So how is the 5 mapped to 053, and both 0's mapped to 048 for this example. Does the jvm account for this automatically behind the scenes? Or am I misunderstanding how the entire process works. Thanks.
Well, IF I understand your question directly...
You could start by dividing your integer by 10 and getting the remainder -- the mod function in Java (%) is useful for this.
int digitInteger = originalNumber % 10;
The digitInteger variable now holds a number 0-9, the integer version of the ASCII (or Unicode, or whatever) of the last digit in the number. Unfortunately for your example, this will be a fairly boring 0.
Let us instead use the number 543 as our example, it will make things easier. If originalNumber was 543, then digitInteger will now be 3. Since 48 represents ASCII 0, then you can add that to digitInteger to get the ASCII equivalent. I'll leave it to you put that somewhere, since Java does not deal with ASCII as its default encoding. (Unicode, I believe, has the same values as ASCII for these digits).
Now you execute something like
originalNumber = originalNumber / 10;
This integer division will truncate the digit you just isolated, 3 in our case, and originalNumber is now 54.
You repeat this process - mod by 10 to isolate the last digit, convert to character, prepend to characters previously found, integer divide by 10 to truncate the last digit -- until originalNumber is 0 -- digitInteger, as you can probably see now, will be 4 on the next round and 5 on the round after that, and you prepend those to the 3 you got the first time to get your ASCII equivalent.

Is shifting an Ascii value by a random number between 3 and 7 digits even possible?

I am curious if it's even possible due to Ascii characters only having 3 digit integer codes. A random number between 3 and 7 digits just sounds outrageously large. Please let me know if I'm thinking about this all wrong.
You must first take in the person’s first name.
Then, you must take in the person’s last name.
Then, you must convert the first and last letter of the person’s first name and last name into their ASCII values.
Then, you must shift their ASCII value over by a random number between 3 and 7 digits.
If your number goes past z, then, you must wrap around to a. You cannot use if statements
The requirements don't say that the shifted value will fall into the ASCII range. Actually, the behaviour for the overflow is explicitly stated in the last point.
I think your teacher is trying to make you use the modulus operator. I won't give you a full solution but you should look into this direction.

why do we need to input strings and then parse them into integer when one can input integers? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This might be a very basic question but i really i did not understand the purpose of doing so . guessing rather wildly that can be a efficiency or performance, security strength ( I really do not understand the purpose though)
Okay, technically speaking, from a technical and literal point of view, you are putting in numerical values. But, these numerical values are defined as characters - letters, numbers, symbols, and even some non-printing symbols as well.
For a computer, it's all numbers. But, they have a special way to represent numerical constructs, such as an integer, or a rational/real number, and so forth.
The primary reason that you can't just directly put numbers in is because the numbers you're putting in mean something else in another way. You have to convert your number from whatever encoding it is (either ASCII or UTF-8 or some other encoding), and give it value inside of an appropriate numerical construct.
Take for instance, the character '0'. It has a code point value (in UTF-8 and likely ASCII) of 48. If we were to take '0' at its literal code point value, we would get wonky* results for our math.
There's also the case that you're not just putting numbers in - you're also putting in other letters, symbols, and (God help you if you don't have UTF-8) s̈́̊̄̂ͯ̍ͤo̓̃̈̈́-c̑̋a̅ll̑̓̒ͪͦ̚e̓ͭ̔̋́̚d ͛̄ͧͯ"ͬͭ̎͆Z̋̓̈̈́a͗̇̑l͑̒ͣ̌̈́̚g̋ͦ͑o͆̉̍ͮiͩ̽̎̌̾͆͛z͂̾̓ͯͭe̋ͪ̀͆̇ͪ͂d̄ͫ"̾ͮ̎̽ ̔̿̽ͬC̑͂ͬ͒J̇̔ͤK̇ͩ̂̇͑ c͒̈̾ȟ͌͒ͪ̂ͪa̽ͣ̃̑r͂̓͛͑̐ác̉ͨ̉͆͆ͦ̄t̃ͮ̋̓̚eͧ̽͋ͬ̀ͮr͋͋͑ͩͦ̐̅sͯͬ͋͛ͬ́!̓ͤ̌ͯ̃ͫ̀!̐̇ͫ́!͒ ͂̏͆̌誠̃ͦ̓͛̉̚
Again, these are all numbers to the computer, but these numbers mean something different to the computer than they do you.
To keep things simple, the chief interaction that the user will have with the computer will be to input strings, since numbers don't entirely convey words or phrases, unless one exclusively spoke and read binary (which would, again, have to be translated into words that others could read).
*: For addition and subtraction, your results would be off by 48, but this would make multiplication and division really exciting.
So, with the above said, let's take a simple example: We need to convert the input "012817" to a number of some kind. Let's assume base 10 (0 through 9).
As a computer, I see this come across as:
48, 49, 50, 56, 49, 55
Since 48 is going to be our zero, we can safely say that, whenever we encounter a character that we wish to convert to an actual numeral, we subtract 48 from it. Simple!
48 - 48, 49 - 48, 50 - 48, 56 - 48, 49 - 48, 55 - 48
0, 1, 2, 8, 1, 7
Since leading zeroes are meaningless in base 10, it is discarded, and we can store this in a numerical construct now:
12817
So what happens if you enter in a non-numeral? Well, given that the numbers are contiguous*, we can add ten to 48 and know that 58 is the highest base 10 number we will come across. That gives us a convenient property - if the difference between our character and 48 is greater than 58, we can't place it into a numerical construct**. And we should blow up, complain, and whine, and give the user this friendly exception:
Exception in thread "main" java.lang.NumberFormatException: For input string: "A"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at com.stackoverflow.sandbox.Formatting.main(Formatting.java:19)
If you were using base 16 (0 through 9, and A through F, case insensitive), you could have a little bit more leeway into what you allowed. If you knew where 'A' and 'a' started (65 and 97, respectively), you could expand your conversion algorithm to respect a value that included either case of the letter A, up to and including a value that included either case of the letter F.
*: At least in ASCII and UTF-8, they are. Other encodings with other numeral systems may differ.
**: Again, we're speaking about base 10. Higher bases may allow you to add more characters, but that depends on your conversion algorithm. I've deliberately kept it simple to illustrate the basics.
If you're reading user input, say with a Scanner object. If the input is a number only, you can certainly read it with the nextInt() method of the Scanner class. If, however, the number is imbedded within a string of other nonnumerical characters, it has to be parsed. Anything from the command line is considered a string of characters and it is passed into the main method via the String[] args parameter. Those must be parsed because they are considered embedded within a string. Also, keep in mind that a string is not a primitive data type. It is a String with a capital "S" because it is an object level data structure in Java. So, number characters embedded within it cannot be processed as a primitive integers.

Hamming Code: Number of parity bits

I'm trying to write a method in java that will take an input of any number of 0 or 1 digits and output that line after being encoded with Hamming Code.
I have managed to write the code when knowing the number of digits the input will have (in this case 16) because knowing the number of digits in the input, I immediately know the number of parity bits there have to be added (5 in this case) to a total of 21 digits in the final output. I am working with int arrays so I need to declare a size in the beginning and my code works based on those exact sizes.
Can you guys think of any way/algorithm that can give me the number of digits the output will have (after adding the relevant parity digits to the number of input digits) based solely on the number of input digits?
Or do I have to tackle this problem in a totally different way? Any suggestions? Thank you in advance!
Cheers!
From my understanding, you get your 6th parity bit at 32 bits of input, 7th at 64, etc. so what you need is floor(lg(n)) + 1, which in java you can get by using 32 - Integer.numberOfLeadingZeros(n).
Assuming your input is made up entirely of 0s and 1s, you would do
int parityDigits = 32 - Integer.numberOfLeadingZeros(input.length());
Is your input a String or individual bits? If you input as a String, you can convert each character to a bit, and the length of the String gives you the length of the array.
If you need to input the bits one at a time, store them in an ArrayList. When all bits have been entered, you can convert your list to an array easily, or use the size of the list etc.

need help with parseInt

how can i get for example the integer codeInt=082 from String code='A082'
i have tried this:
int codeInt = Integer.parseInt(code.substring(1,4));
and i get codeInt=82 ,it leaves the first 0 but i want the full code '082'.
i thought of parseInt(String s, int radix) but i don't know how .
any help will be appreciated .
thanks.
An integer just stores a number. The numbers 82 and 082 (and 0082 and 000000082 for that matter) are exactly the same (unless you put them into source code in some languages in that manner, then you'll get a compiler error)1.
If you desperately need the leading zero, then you should either leave it as a string, or format the number appropriately for output later.
1 Due to the C designers having the ingenious idea that writing octal constants with a preceding zero would be cool. As if something like 0o123 would have been that hard to implement once you already got 0xf00 ...
The number 82 and 082 and 0082 is mathematically the same number, and is represented by the same sequence of bits. You can't encode the number of leading zeroes in an int (although you can certainly print it with whatever format you choose).
Note also that the number 082 is different from the Java literal 082, which is an (invalid) octal literal.
int i = 010;
System.out.println(i); // this prints 8
082 is not an integer. It's a string representing the integer 82. If you require leading zeros to be left untouched, you will need to work with strings. If you only need it to print 082, you can use java.text.MessageFormat or System.out.format() or other, similar solutions to print it that way.
If you want 0000123 then you need to threat a variable as a String instead of Integer. Simply: 123 is equal to 000123 and 0123 and 0000...1 billion zeros here...000123.
But if you just want to display a number with fixed length then use System.out.format().

Categories