Storing digits of numbers in array - java

Hello fellow programmers !
I am a beginner with Java and i am looking for a method or a way maybe to store the digits of a 6 digit number entered by the user , in an int array.
For example :-
if the number is 675421.
then i want to store the digits in an array like :-
int[] array = new int[6];
int number = 675421
array[0] = 6;
array[1] = 7;
array[2] = 5;
array[3] = 4;
array[4] = 2;
array[5] = 1;
I want to do so so that i can work with the array to maybe sort or change the order or numbers in array. Thanks!

Here you go,
String temp = Integer.toString(number);
int[] num = new int[temp.length()];
for (int i = 0; i < temp.length(); i++){
num[i] = temp.charAt(i) - '0';
}
for (int i = 0; i < temp.length(); i++) {
System.out.println(num[i]);
}
Edit, after comment
Here, First, you are converting to your number to a string.
Then, take each char out of it(in the loop), subtract the ASCII value of 0 from each char to get the digit [ie, ASCII of 0 is 48, 1 is 49, ... ] (see ASCII table)

Do something like this:
String number = "123123";
int[] intArray = new int[number.length()];
for (int i = 0; i < number.length(); i++)
{
intArray[i] = Integer.parseInt(Character.toString(number.charAt(i)));
}
Hope this helps,
Jason.

Below is the recursive solution
public static void main(String[] args) {
int testNum = 675421;
List<Integer> digitList = new ArrayList<Integer>();
collectDigits(testNum, digitList);
Object[] resultArr = digitList.toArray();
int listSize = resultArr.length;
for (int listCount = 0; listCount < listSize; listCount++) {
System.out.println("result["+listCount+"] = "+resultArr[listCount]);
}
}
private static void collectDigits(int num, List<Integer> digits) {
if (num / 10 > 0) {
collectDigits(num / 10, digits);
}
digits.add(num % 10);
}

One way to do this would be to turn the original integer into a string.
Loop over the string, parsing each character back to an int, and place into the array. Here is an example:
int number = 123456;
String strNumber = number+"";
int[] array = new int[strNumber.length()];
int index = 0;
for(char c : strNumber.toCharArray()){
array[index++] = Integer.parseInt(c+"");
}
System.out.println(Arrays.toString(array));

Math solution, you can split the int number using this:
int[] array = new int[6];
int number = 675421;
array[0] = ((number/100000)%10);
array[1] = ((number/10000)%10);
array[2] = ((number/1000)%10);
array[3] = ((number/100)%10);
array[4] = ((number/10)%10);
array[5] = ((number/1)%10);
If the "number" has a variable length you can automate this, write a coment if you need help

Related

Pre increment on arrays

Can anyone explain the output of this code? I have been hitting my head really hard to understand, but I just don't get it.
public static void main(String ars[]) {
int responses[] = {1,2,4,4};
int freq[] = new int[5];
for(int answer = 1; answer < responses.length; answer++) {
++freq[responses[answer]];
}
for (int rating = 1; rating < freq.length; rating++)
System.out.printf("%6d%10d\n", rating, freq[rating]);
}
Output
1 0
2 1
3 0
4 2
In first loop ++freq[responses[answer]]; means :
responses[answer] get the value from response array index.
Freq[value] check & get the value from Filter array index.
++Freq[value] add value 1 to Freq[value].
I've tried to simply things a bit so you can see what is going on:
int responses[] = new int[4];
responses[0] = 1;
responses[1] = 2;
responses[2] = 4;
responses[3] = 4;
int freq[] = new int[5];
for(int answer = 1; answer < 4; answer++)
{
int x = responses[answer];
freq[x] = freq[x] + 1;
}
for (int rating = 1; rating < 5; rating++)
{
//Print 6 spaces and then the rating variable
//Print 10 spaces then the integer at freq[rating]
System.out.printf("%6d%10d\n", rating, freq[rating]);
}
I would look up the ++ prefix & postfix.

How do I fill an array with consecutive numbers

I would like to fill an array using consecutive integers. I have created an array that contains as much indexes as the user enters:
Scanner in = new Scanner(System.in);
int numOfValues = in.nextInt();
int [] array = new int[numOfValues];
How do i fill this array with consecutive numbers starting from 1?
All help is appreciated!!!
Since Java 8
// v end, exclusive
int[] array = IntStream.range(1, numOfValues + 1).toArray();
// ^ start, inclusive
The range is in increments of 1. The javadoc is here.
Or use rangeClosed
// v end, inclusive
int[] array = IntStream.rangeClosed(1, numOfValues).toArray();
// ^ start, inclusive
The simple way is:
int[] array = new int[NumOfValues];
for(int k = 0; k < array.length; k++)
array[k] = k + 1;
for(int i=0; i<array.length; i++)
{
array[i] = i+1;
}
You now have an empty array
So you need to iterate over each position (0 to size-1) placing the next number into the array.
for(int x=0; x<NumOfValues; x++){ // this will iterate over each position
array[x] = x+1; // this will put each integer value into the array starting with 1
}
One more thing. If I want to do the same with reverse:
int[] array = new int[5];
for(int i = 5; i>0;i--) {
array[i-1]= i;
}
System.out.println(Arrays.toString(array));
}
I got the normal order again..
Scanner in = new Scanner(System.in);
int numOfValues = in.nextInt();
int[] array = new int[numOfValues];
int add = 0;
for (int i = 0; i < array.length; i++) {
array[i] = 1 + add;
add++;
System.out.println(array[i]);
}

Extracting indivdual digits from a number.

I am trying to extracting a individual number from a given integer. example from 1234, I want to store 1 , 2 ,3 ,4 in an array.The number of digits might not be same every time. I don't know how to initialize the array for the same.
int number = 1234;
int [] a = new int[];
for(int i =0;i<lengthOfNum;i++){
a[i] = digitReturn();
}
You can try the following:
int number = 1234;
int length = Integer.toString(number).length();
int[] a = new int[length];
int index = length - 1;
for (int i = 0; i < length; i++){
a[i] = number % 10;
number = number / 10;
index--;
}
Convert the number to String to get the size and use that value to declare the length of the array and then just loop through it, extracting the last number using modulus and then dividing to get rid of the last digit in the integer.
Convert the number into a string, then split the string into an array. After that, convert the characters into integers, like this:
int number = 1234;
List<Integer> digits = ArrayList<Integer>();
String digitsAsString = ("" + number).split("");
for(String digitAsString:digitsAsString){
digits.add(new Integer(Integer.parseInt(digitAsString));
}
Your array of digits is the list of digits
int number = 4567;
String number_string = String.valueOf(number);
char[] chars = number_string.toCharArray();
int[] digits = new int[chars.length];
int i = 0;
for (char c : chars) {
digits[i] = c - '0';
i++;
}
int number = 1234;
String num = Integer.toString(number);
int [] a = new int[num.length()];
for(int i = 0; i < num.length(); i++){
a[i] = Character.getNumericValue(num.charAt(i));
}
First convert number to a String, loop through each char and convert them into an int then storing the value into a.

How to multiplay an array of Integers in Java

I have two arrays of integers and I want to multiply them together like the following:
int[] arr1 = {6, 1}; // This represents the number 16
int[] arr2 = {4, 2}; // This represents the number 24
I want to store them in a new array so that the product appears as:
int[] productArray = {4, 8, 3};
I get how to do it with multiplying numbers like 2 x 24 since I can just push those into values into the product array. But when it comes to expanding beyond a single digit I am lost.
Why do you need to do this? Regardless, here is an example:
int total1; // to find what the array represents in #
for (int c = 0; c < arr1.length() - 1; c++) {
total1 += arr1[c] * Math.pow(10, (c+1)); // takes the number and adds it to the decimal number it should be
}
int total2;
for (int c = 0; c < arr2.length() - 1; c++) {
total1 += arr2[c] * Math.pow(10, (c+1));
}
String s = Integer.toString(total2*total1);
for (int c = s.length()-1; c >= 0; c--) { // adds int to array backwards
productArray.add(Integer.parseInt(s.atIndex(c)));
}
Notes: I have not bug tested this or run it through the JVM. Java isn't my usual programming language so I may have made a few mistakes. the "productArray" needs to be an ArrayList<> instead. I suspect that Integer.parseInt() is only for strings, so you may have to search for the char version of the function. Also, you need include Math...
int arr1num, arr2num, product;
multiplier = 1;
for (i = arr1.size();i>0;i--){
arr1num = arr1num + (arr1[i] * multiplier);
multiplier = multiplier * 10;
}
--do this also for the second array
-- now we have arr1num and arr2num as the numbers of both arrays and
just get the product
product = arr1num * arr2num;
-- now store it in an array
int divisor = 10;
int number;
for(i=0;i<int.length();i++){
number = product % divisor;
productArray.add(number);
divisor = divisor * 10;
}
You could use this (although it's not the best algorithm you could use to do this):
public static int[] multiplyArrays(int[] a, int[] b){
//turns arrays into integers
String num1 = "";
for (int i = a.length - 1; i > -1; i--){
num1 += a[i];
}
String num2 = "";
for (int i = b.length - 1; i > -1; i--){
num2 += b[i];
}
//does calculation
char[] answer = Integer.toString(Integer.parseInt(num1) * Integer.parseInt(num2)).toCharArray();
//converts char array into int array
int[] answer2 = new int[answer.length];
for (int i = 0; i < answer.length; i++){
answer2[answer.length - i - 1] = Integer.parseInt(String.valueOf(answer[i]));
}
return answer2;
}

Is there a better (faster) way to divide a number to digits?

I wrote this:
void blah(int num)
{
int numOfDigits = Math.log10(num);
int arr[] = new int[numOfDigits + 1];
for(int i = numOfDigits; i>0; i--)
{
arr[i] = num%10;
num = num/10;
}
}
But I thought there must be a more elegant way of doing this. Is there?
If you're happy with Strings, you could do this:
String[] arr = Integer.toString(num).split("(?<=\\d)");
If you want to go from this to int[]:
int[] arrint = new int[arr.length];
for (int i = 0; i < arr.length; i++)
arrint[i] = Integer.parseInt(arr[i]);
Consider converting the integer to a string using Integer.toString and then using string.toCharArray() and converting back. This may or may not be more 'elegant' depending on your worldview.
This might be one way (i am not super proud about this :))
Integer number = 1234567890; // input number
String temp = number.toString(); // convert to string
int [] output = new int[temp.length()];
for (int i=0 ; i< temp.length(); i++) // get character at index i from string
output[i] = temp.charAt(i) - '0'; // convert it to number by removing '0'

Categories