From random integers to an actual String - java

This is a code that takes in an array of all the printing characters of the ASCII table. I am trying to make it so that any String message in the form of integers (e.g. String "aba" that is converted 97098097 can be put back into its original String form. 100101101 can be taken and made back into "dee". I've really tried hard with this method but it does not seem to be working, especially when it comes to numbers and such please help me. It is in Java by the way and I am using Eclipse.
public static String IntToString (){
int n = 0;
String message = "";
String message2 = null;
String [] ASCII = {" ","!","\"","#","$","%","&","\'","(",")","*","+",",","-",".","/","0","1","2","3","4","5","6","7","8","9",":",";","<","=",">","?","#","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","[","\\","]","^","_","`","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","{","|","}","~"};
String IntMessage = result.toString();
String firstChar = IntMessage.substring(0,2);
if (IntMessage.substring(0,1)=="1" && IntMessage.length()%3==0)
{
for (int x = (IntMessage.length() % 3 - 3) % 3; x < IntMessage.length()-2; x += 3)
n = Integer.parseInt(IntMessage.substring(Math.max(x, 0), x + 3));
message=message.concat(ASCII[n-31]);
return message;
}
else if (IntMessage.length()%3==2)
message2=ASCII[(Integer.parseInt(firstChar))-31];
for (int x = 2; x < IntMessage.length()-2; x += 3)
n = Integer.parseInt(IntMessage.substring(x, x + 3));
message=message2+=ASCII [n - 31];
return message;

It would seem that your encoding scheme is, er, crazy.
First, you take the ASCII value of a string, then take the character representation of that ASCII value, then store it as a string.
So "abc" => {97, 98, 99} => "979899".
But since you are using ASCII, which can have values of 100 or more, you are padding your ints with 0 if they are under 100:
"abc" => {97, 98, 99} => {"097", "098", "099"} => "097098099"
But you decide to do this only sometimes, because somehow
"aba" => "97098097"
That is, the first "a" is turned into "97", but the last "a" is turned into "097".
I'd say you should fix your encoding scheme first.
Also, these are hopefully not "random integers" because you are trying to turn them into sensible strings. Otherwise a simple mapping such as base64 would easily map any integers to strings, they just might not make much sense.
In fact, they aren't even really integers. You're storing your encoded strings as strings.

public static void main(String[] srgs){
String aaa = "100101101";
String[] a = split(aaa, 3);
String s = "";
for(int i=0;i<a.length;i++){
char c = (char)Integer.parseInt(a[i]);
s += Character.toString(c);
}
System.out.println(s);
}
public static String[] split(String str, int groupIndex){
int strLength = str.length();
int arrayLength = strLength/groupIndex;
String[] splitedArray = new String[strLength/groupIndex];
for(int i=0;i<arrayLength;i++){
String splitedStr = str.substring(0, groupIndex);
str = str.substring(groupIndex, str.length());
arrayLength = str.length();
splitedArray[i] = splitedStr;
}
return splitedArray;
}
The most important is that ASCII string covert to Char value, than turn it to real Character value in the string. The ASCII code length need be fix by 3 can be helpful in this case.

Related

Adding two numbers stored as arrays of chars

I'm trying to write an algorithm which adds two numbers that are stored as chars in two arrays. Unfortunately, it doesn't work. When I try to debug it, I see that the variables a and b get the value -1 which makes no sense. Any idea what might be the problem?
public class rechner2 {
public static void main(String[] args) {
final char[] zahl1 = {1, 2, 3};
final char[] zahl2 = {7, 8, 9};
//Add arrays zahl1 and zahl2.
char [] zwischenarray = add(zahl1, zahl2);
for (int i = 0; i < zwischenarray.length; i++) {
System.out.println(zwischenarray[i]);
}
}
private static char[] add(char[] zahl1, char[] zahl2) {
int len;
if (zahl1.length < zahl2.length) {
len = zahl2.length;
} else {
len = zahl1.length;
}
char[] finalresult = new char [len + 1];
int carryover = 0;
for (int i = 0; i < len; i++) {
int a = Character.getNumericValue(zahl1[i]);
int b = Character.getNumericValue(zahl2[i]);
int c = a + b + carryover;
if (c > 9) {
carryover = 1;
c = c - 10;
} else {
carryover = 0;
}
finalresult[i] = (char)c;
}
if (carryover == 1) {
finalresult[len + 1] = 1;
}
return finalresult;
}
}
in this code I believe 2 bug
instead of char , i guess better to us int
length of the array
here is the code:
public class rechner2 {
public static void main(String[] args) {
int[] zahl1 = {1,2,3};
int[] zahl2 = {7,8,9};
//Add arrays zahl1 and zahl2.
int [] zwischenarray = add(zahl1, zahl2);
for (int i = 0; i < zwischenarray.length; i++) {
System.out.println(zwischenarray[i]);
}
}
private static int[] add(int[] zahl1, int[] zahl2) {
int len;
if (zahl1.length < zahl2.length) {
len = zahl2.length;
} else {
len = zahl1.length;
}
int[] finalresult = new int [len + 1];
int carryover = 0;
for (int i = 0; i <= len-1; i++) {
int a = (zahl1[i]);
int b = (zahl2[i]);
int c = a + b + carryover;
if (c > 9) {
carryover = 1;
c = c - 10;
} else {
carryover = 0;
}
finalresult[i] = c;
}
if (carryover == 1) {
finalresult[len] = 1;
}
return finalresult;
}
}
Your code is conflicted: The numbers / characters in your array are actually integers, not "printable" or "human readable" characters. But, parts of your code are treating them as if they are "printable".
Let's go back decades, and use ASCII for the beginning of this explanation. ASCII has "Printable" and "Nonprintable" characters. The "Nonprintable" characters are known as "Control codes."
Control codes include codes that move the cursor on a display terminal or print head on a printing terminal. They include thing like CR (Carriage Return), LF (Line Feed), HT (Horizontal tab), and BS (Backspace). Others are used by data communications hardware to control the flow of data, or to report status.
Printable characters correspond to what you see on a terminal screen or printout. They include uppercase alphabetic, lower case alphabetic, digits, punctuation, and the space character. They are "human readable."
Look at the list of printable characters in the Wikipedia article. Take 5 as an example. It's represented as '53' in base ten, which corresponds to '35' in base sixteen, or '011 0101' in binary. Note that it is not the same as the binary number five, which would be '0000 0101'.
Java uses 16 bit Unicode, not ASCII, for its char type. The Java compiler allows arithmetic to be done on char data, as if it was the same as short.
These lines in your code expect your char variables and constants are printable characters:
int a = Character.getNumericValue(zahl1[i]);
int b = Character.getNumericValue(zahl2[i]);
In addition, that you specified zwischenarray as char tells the compiler to handle the contents as printable characters in this line:
System.out.println(zwischenarray[i]);
But, the rest of your code treats your char data as integer data types.
You have a bug in this line: finalresult[len + 1] = 1;. After that bug is fixed, how do you fix the rest of your code? There are different ways, and which is best depends on your intention.
For demonstration purpose, try this: Replace the following
int a = Character.getNumericValue(zahl1[i]);
int b = Character.getNumericValue(zahl2[i]);
int c = a + b + carryover;
with
int c = zahl1[i] + zahl2 [i] + carryover;
Also, put a cast in your output line:
System.out.println((short)zwischenarray[i]);
And run it. That will demonstrate you can do arithmetic on Java char data.
Now, remove the (short) cast in output line, and change all occurrences of char to short (or int). Your program still works.
This is because of the way you entered the values for zahl1 and zahl2. Your source code consists of printable characters and white space. By omitting the single quotes, you told the compiler to convert the values to binary integers. For example, your source code 9 became binary 0000 1001 in the runtime code. If you wanted your 9 to remain as a printable character, you needed to enclose it in single quote marks: '9' .
By enclosing all the values in zahl1 and zahl2 in single quote marks, the use of Character.getNumericValue is appropriate. But, you would still need the (short) or (int) cast in your System.out. line to see your output.
Character.getNumericValue is returning -1 because the values passed are outside of the range it was designed to work with.
Here are two ways to convert a base 10 digit represented as a binary integer to the equivalent printable character:
finalresult[i] = (char) (c + '0');
But, my preference is for this:
final String digit = "0123456789";
finalresult[i] = digit.charAt (c);

Trouble with finding odd and even index values for characters

I'm creating simple encryption/decryption software as a fun project. I am able to encrypt. It gives me the encrypted password and the key. The problem I'm having is in the decryption. For an example, here is an encrypted message: eUwG:Q_vul=u^CMiojpnif and here is the key: 103141109141719141119050117050318040907010912. The way it works is by first adding a random salt to the beginning or end of the message which is defined by the first number in the key. So since the first number is 1 then the salt is at the beginning (the salts are 14 characters long), so it removes that text, leaving Miojpnif. In the key after the salt number, there are 2 numbers per letter in the text. which is where I'm stuck. A number 1 means that the character was shifted forward, and 0 means backwards. So for the 'M' in the key for that character it's 0 so it was shifted backwards and the next number is 3 meaning that it was shifted backwards by 3. So to reverse this I need to shift that character forward 3. The thing is, I can't figure out how to make this work properly. My idea is that it removes the first number (salt) from the key, and then if the number is odd, then it records if the character will go forward or back, and if it's even then it'll move that character forward or back (which is stored as an int like the rest) by that number. So where I'm stuck is that figuring out if it's even or odd isn't working properly and I can't quite figure out how to shift that character.
I already looked up how to figure out if it's even or odd, but it still doesn't work. Actually shifting the character I made up my own code for. I don't know if you guys understand what I need help with because I didn't really know how to express it in words. So here is the code that I have, I hope that y'all can help.
for(int i= 0; i < keyNew.length(); i++){
if(i % 2 == 1){
/*odd*/
if(keyNew.charAt(i) == '1') {
forward = 1;
backward = 0;
} else {
forward = 0;
backward = 1;
}
}else{
/*even*/
if(forward == 1 && backward == 0) {
/*forward*/
System.out.println("forward");
String encryptedNewer = encryptedNew.charAt(i / 2) += keyNew.charAt(i);
} else if(forward == 0 && backward == 1) {
*backward*/
System.out.println("backward");
String encryptedNewer = encryptedNew.charAt(i / 2) += keyNew.charAt(i);
}
}
}
encrypted is the encrypted text, key is the key, encryptedNew is the text without the salt and keyNew is the key without the first digit.
This is a great example of the long method smell. I recommend the following:
Work with String and use the substring(...) function. It is easier, because you need less variables and don't have to convert from char to int and back.
Create a function encrypt(...) and decrypt(...) which calls some "subfunctions"
One subfunction is addSalt(...) and removeSalt(...)
One subfunction is splitKeyToPairs(...) which returns a List of strings with 2 Digits per Item.
One subfunction is shiftForward(...) and shiftBackwards(...)
Then I would implement it as follow:
public String decrypt(String key, String cipher) {
String cipherModified = removeSalt(key, cipher);
List<String> keyPairs = splitKeyToPairs(key.substring(1, key.length()));
String message = "";
for(int position = 0; position < keyPairs.size();++position) {
String keyTmp = keyPairs.get(position);
String cipherLetter = cipherModified.substring(position, position + 1);
message += "0".equals(keyTmp.substring(0, 1)) ? shiftBackwards(cipherLetter, keyTmp.substring(1, 2)) : shiftForward(cipherLetter, keyTmp.substring(1, 2));
}
return message;
}
public List<String> splitKeyToPairs(String key) {
List<String> result = new ArrayList<String>();
for(int i = 0; i < key.length(); i += 2) {
//i += 2 because we jump 2 characters per iteration.
result.add(key.substring(i, i+2));
}
return result;
}
Here a little test function for the split but not for the decrypt:
public static void main(String[] args) {
List<String> result = splitKeyToPairs("1234567890");
List<String> test = new ArrayList<>(Arrays.asList("12", "34", "56", "78", "90"));
for(int i = 0; i < result.size();++i) {
if(!result.get(i).equals(test.get(i))) {
System.out.println("error on position " + i);
}
}
}
Ok, here is another approach to decrypting the message. Establishing methods and tucking them away in a library would be advisable. In the following example I omitted the salt digit from the key. The logic to accommodate that is trivial.
String key = "03141109141719141119050117050318040907010912";
String code = "eUwG:Q_vul=u^CMiojpnif";
int i = 0;
StringBuilder sb = new StringBuilder();
for (int pos = 0; pos < code.length(); pos++) {
// get codeLetter
char codeLetter = code.charAt(pos);
// set direction
int direction = key.charAt(i++) == '0' ? 1
: -1;
// set count
int count = key.charAt(i++) - '0';
// modify codeLetter based on direction and count
char c = (char) (codeLetter + (count * direction));
// save it.
sb.append(c);
}
System.out.println(sb.toString().substring(14));

Convert a given decimal string into a binary string(even number of binary digits) in Java [duplicate]

for example, for 1, 2, 128, 256 the output can be (16 digits):
0000000000000001
0000000000000010
0000000010000000
0000000100000000
I tried
String.format("%16s", Integer.toBinaryString(1));
it puts spaces for left-padding:
` 1'
How to put 0s for padding. I couldn't find it in Formatter. Is there another way to do it?
P.S. this post describes how to format integers with left 0-padding, but it is not for the binary representation.
I think this is a suboptimal solution, but you could do
String.format("%16s", Integer.toBinaryString(1)).replace(' ', '0')
There is no binary conversion built into the java.util.Formatter, I would advise you to either use String.replace to replace space character with zeros, as in:
String.format("%16s", Integer.toBinaryString(1)).replace(" ", "0")
Or implement your own logic to convert integers to binary representation with added left padding somewhere along the lines given in this so.
Or if you really need to pass numbers to format, you can convert your binary representation to BigInteger and then format that with leading zeros, but this is very costly at runtime, as in:
String.format("%016d", new BigInteger(Integer.toBinaryString(1)))
Here a new answer for an old post.
To pad a binary value with leading zeros to a specific length, try this:
Integer.toBinaryString( (1 << len) | val ).substring( 1 )
If len = 4 and val = 1,
Integer.toBinaryString( (1 << len) | val )
returns the string "10001", then
"10001".substring( 1 )
discards the very first character. So we obtain what we want:
"0001"
If val is likely to be negative, rather try:
Integer.toBinaryString( (1 << len) | (val & ((1 << len) - 1)) ).substring( 1 )
You can use Apache Commons StringUtils. It offers methods for padding strings:
StringUtils.leftPad(Integer.toBinaryString(1), 16, '0');
I was trying all sorts of method calls that I haven't really used before to make this work, they worked with moderate success, until I thought of something that is so simple it just might work, and it did!
I'm sure it's been thought of before, not sure if it's any good for long string of binary codes but it works fine for 16Bit strings. Hope it helps!! (Note second piece of code is improved)
String binString = Integer.toBinaryString(256);
while (binString.length() < 16) { //pad with 16 0's
binString = "0" + binString;
}
Thanks to Will on helping improve this answer to make it work with out a loop.
This maybe a little clumsy but it works, please improve and comment back if you can....
binString = Integer.toBinaryString(256);
int length = 16 - binString.length();
char[] padArray = new char[length];
Arrays.fill(padArray, '0');
String padString = new String(padArray);
binString = padString + binString;
A simpler version of user3608934's idea "This is an old trick, create a string with 16 0's then append the trimmed binary string you got ":
private String toBinaryString32(int i) {
String binaryWithOutLeading0 = Integer.toBinaryString(i);
return "00000000000000000000000000000000"
.substring(binaryWithOutLeading0.length())
+ binaryWithOutLeading0;
}
I do not know "right" solution but I can suggest you a fast patch.
String.format("%16s", Integer.toBinaryString(1)).replace(" ", "0");
I have just tried it and saw that it works fine.
Starting with Java 11, you can use the repeat(...) method:
"0".repeat(Integer.numberOfLeadingZeros(i) - 16) + Integer.toBinaryString(i)
Or, if you need 32-bit representation of any integer:
"0".repeat(Integer.numberOfLeadingZeros(i != 0 ? i : 1)) + Integer.toBinaryString(i)
try...
String.format("%016d\n", Integer.parseInt(Integer.toBinaryString(256)));
I dont think this is the "correct" way to doing this... but it works :)
I would write my own util class with the method like below
public class NumberFormatUtils {
public static String longToBinString(long val) {
char[] buffer = new char[64];
Arrays.fill(buffer, '0');
for (int i = 0; i < 64; ++i) {
long mask = 1L << i;
if ((val & mask) == mask) {
buffer[63 - i] = '1';
}
}
return new String(buffer);
}
public static void main(String... args) {
long value = 0b0000000000000000000000000000000000000000000000000000000000000101L;
System.out.println(value);
System.out.println(Long.toBinaryString(value));
System.out.println(NumberFormatUtils.longToBinString(value));
}
}
Output:
5
101
0000000000000000000000000000000000000000000000000000000000000101
The same approach could be applied to any integral types. Pay attention to the type of mask
long mask = 1L << i;
A naive solution that work would be
String temp = Integer.toBinaryString(5);
while (temp.length() < Integer.SIZE) temp = "0"+temp; //pad leading zeros
temp = temp.substring(Integer.SIZE - Short.SIZE); //remove excess
One other method would be
String temp = Integer.toBinaryString((m | 0x80000000));
temp = temp.substring(Integer.SIZE - Short.SIZE);
This will produce a 16 bit string of the integer 5
// Below will handle proper sizes
public static String binaryString(int i) {
return String.format("%" + Integer.SIZE + "s", Integer.toBinaryString(i)).replace(' ', '0');
}
public static String binaryString(long i) {
return String.format("%" + Long.SIZE + "s", Long.toBinaryString(i)).replace(' ', '0');
}
This is an old trick, create a string with 16 0's then append the trimmed binary string you got from String.format("%s", Integer.toBinaryString(1)) and use the right-most 16 characters, lopping off any leading 0's. Better yet, make a function that lets you specify how long of a binary string you want. Of course there are probably a bazillion other ways to accomplish this including libraries, but I'm adding this post to help out a friend :)
public class BinaryPrinter {
public static void main(String[] args) {
System.out.format("%d in binary is %s\n", 1, binaryString(1, 4));
System.out.format("%d in binary is %s\n", 128, binaryString(128, 8));
System.out.format("%d in binary is %s\n", 256, binaryString(256, 16));
}
public static String binaryString( final int number, final int binaryDigits ) {
final String pattern = String.format( "%%0%dd", binaryDigits );
final String padding = String.format( pattern, 0 );
final String response = String.format( "%s%s", padding, Integer.toBinaryString(number) );
System.out.format( "\npattern = '%s'\npadding = '%s'\nresponse = '%s'\n\n", pattern, padding, response );
return response.substring( response.length() - binaryDigits );
}
}
This method converts an int to a String, length=bits. Either padded with 0s or with the most significant bits truncated.
static String toBitString( int x, int bits ){
String bitString = Integer.toBinaryString(x);
int size = bitString.length();
StringBuilder sb = new StringBuilder( bits );
if( bits > size ){
for( int i=0; i<bits-size; i++ )
sb.append('0');
sb.append( bitString );
}else
sb = sb.append( bitString.substring(size-bits, size) );
return sb.toString();
}
You can use lib https://github.com/kssource/BitSequence. It accept a number and return bynary string, padded and/or grouped.
String s = new BitSequence(2, 16).toBynaryString(ALIGN.RIGHT, GROUP.CONTINOUSLY));
return
0000000000000010
another examples:
[10, -20, 30]->00001010 11101100 00011110
i=-10->00000000000000000000000000001010
bi=10->1010
sh=10->00 0000 0000 1010
l=10->00000001 010
by=-10->1010
i=-10->bc->11111111 11111111 11111111 11110110
for(int i=0;i<n;i++)
{
for(int j=str[i].length();j<4;j++)
str[i]="0".concat(str[i]);
}
str[i].length() is length of number say 2 in binary is 01 which is length 2
change 4 to desired max length of number. This can be optimized to O(n).
by using continue.
import java.util.Scanner;
public class Q3{
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
System.out.println("Enter a number:");
int num=scn.nextInt();
int numB=Integer.parseInt(Integer.toBinaryString(num));
String strB=String.format("%08d",numB);//makes a 8 character code
if(num>=1 && num<=255){
System.out.println(strB);
}else{
System.out.println("Number should be in range between 1 and 255");
}
}
}

Bitwise not operation on a string of bits

I have a string with the value 0111000000. How can I perform a bitwise not operation on this string?
If I convert it to an integer, use the ~ operator and convert it back to a binary string, the resulting string has extra bits. I want the output to be exactly 1000111111.
The following code works fine, but it's not a good method. Is there another better way of doing this?
String bstr="";
while(m!=str.length())
{
char a=str.charAt(m);
if(a=='1')
{
a='0';
bstr=bstr+a;
m++;
}
else
{
a='1';
bstr=bstr+a;
m++;
}
}
try this
char[] a = s.toCharArray();
for(int i = 0; i < a.length; i++) {
a[i] = a[i]=='0' ? '1' : '0';
}
s = new String(a);
this also works fine
int i = ~Integer.parseInt(s, 2);
String tmp = Integer.toBinaryString(i);
s = tmp.substring(tmp.length()- s.length());
Keep track of how many bits there are in your bit-string. After converting to an integer and using a ~value operation to flip the bits, use a bit-mask to remove the unwanted 1 high-end bits.
Say for example your bit-string has a fixed 10 bits. Then you can mask off the unwanted high-end bits with: value & 0x2ff.
If the number of bits in the bit-string is variable:
value & ((1 << nBits) - 1)
StringUtils.replaceChars from common-lang might help here:
StringUtils.replaceChars("0111000000", "01", "10");
You should use string builder so you are able to change individual bits without creating many many garbage strings. Also you can flip single bits using XOR:
b ^= 1;
Which works on both binary and ASCII values of digits.
maybe this will work:
String result = Integer.toBinaryString(~(Integer.parseInt("0111000000",2)));
converts binary String to int, use bitwise not operator to invert, then convert back to binary string.
You can do this using XOR operation
public String xorOperation(String value) {
String str1 = value;
long l = Long.parseLong(str1, 2);
String str2 = "";
for (int i = 0; i < str1.length(); i++) {
str2 = str2 + "1";
}
long n = Long.parseLong(str2, 2);
long num = l ^ n;
String bininaryString = Long.toBinaryString(num);
System.out.println(bininaryString);
return bininaryString;
}

Array How would you add a digit to the same location as its value?

The input comes as a String "543210".
The code extracts each character using the charAt method and place them one after the other in a specific array location that corresponds to the value of the number.
charAt(0) = 5 means that 5 should go intoarrayLocation 5.
It doesnt seem to work. I even tried with arrayLists.
public class HugeInteger {
private String digits;
int[] arrayToStoreTheDigits = new int[6];
public HugeInteger(String digits) {
this.digits = digits;
add();
}
public void add() {
for (int i = 0; i < 5; i++) {
arrayToStoreTheDigits[digits.charAt(i)] = digits.charAt(i);
System.out.println(digits.charAt(i));
}
}
public String toString() {
return "" + arrayToStoreTheDigits + "/ " + digits.charAt(2);
}
}
package Exercise8_17_HugeIntegers;
public class HugeIntegertester {
// static HugeInteger huge;
public static void main(String[] args) {
HugeInteger huge = new HugeInteger("543210");
System.out.println(huge.toString());
}
}
Your question is unclear, but I suspect the problem is here:
arrayToStoreTheDigits[digits.charAt(i)] = digits.charAt(i);
If digits.charAt(i) is '5' that has an integer value of 53, as that's the UTF-16 code unit for the character '5'. If you're trying to extract its value when viewed as a digit, you need to use Character.digit. Alternatively you could just subtract '0' if you really only care about 0-9, and are confident there will be no other characters.
So you could write your code like this:
char c = digits.charAt(i);
arrayToStoreTheDigits[c - '0'] = c;
Note that due to this initialization:
int[] arrayToStoreTheDigits = new int[6];
... your code will fail if it ever sees a value of '6' or greater.
Additionally, if you want to use all the characters in digits, your loop should be:
for (int i = 0; i < digits.length(); i++)
Overall this is a very odd thing to want to do - because the only values valid for array element 1 (for example) will be '1' (if the digit is present) or 0 (the default, if it's not). In particular, this loses all information about the position in which the digits occurred. If the class is meant to be similar to BigInteger, you should be writing something much more like this:
arrayToStoreTheDigits = new int[digits.length()];
for (int i = 0; i < arrayToStoreTheDigits.length; i++)
{
// TODO: Digit validation
arrayToStoreTheDigits[i] = digits.charAt(i) - '0';
}
So that after passing in "543210" you'd have an array of { 5, 4, 3, 2, 1, 0 }. That's now useful information.
Problem exists with your loop :
for (int i = 0; i < 5; i++) { // condition shoule be i < 6
// arrayToStoreTheDigits[digits.charAt(i)] = digits.charAt(i); // convert String to integer
// shoule be
arrayToStoreTheDigits[Integer.parseInt(digits.charAt(i))] = Integer.parseInt(digits.charAt(i));
System.out.println(digits.charAt(i));
}

Categories

Resources