I have an "algorithm" which has an integer k as input parameter. For example, I pass k = 54321 as argument. In this method I want:
Convert this integer to char array, so that instead of 54321 it would be [5,4,3,2,1] and so on
Sort this array ascending, add each char to ArrayList
return ArrayList
But when it comes to for loop, if I get item by char[position] it gives me random value. More practically,
public class Main {
public static void main(String[] args) {
System.out.println(sortMet(54321));
}
static ArrayList<Integer> sortMet(int k) {
ArrayList<Integer> tab_cyfr = new ArrayList<>();
char[] chars = String.valueOf(k).toCharArray();
int n = chars.length;
Arrays.sort(chars);
for (int i = 0; i < n; i++) {
tab_cyfr.add(chars[i]);
}
return tab_cyfr;
}
}
This should return me following [1,2,3,4,5] but returns [49, 50, 51, 52, 53], where those numbers came from?
Plus sorry for variables naming, I'm practicing random exercises on local variables.
String.valueOf(k).toCharArray() returns the characters in the String as their char representation. As per ASCII table 49 is the char value of 1, 50 of 2, and so on.
You should convert k to digits, not to chars. This can be done by using % operation:
int k = 8421753;
ArrayList<Integer> digits = new ArrayList<>();
while (k > 0) {
digits.add(k % 10);
k /= 10;
}
Collections.sort(digits);
System.out.println(digits); // [1, 2, 3, 4, 5, 7, 8]
The ASCII Problem
It gets converted to a string, so the numbers are stored as ASCII values in the char array.
The problem is this line:
char[] chars = String.valueOf(k).toCharArray();
If you were to look up the ASCII values of the digits 1,2,3,4,5, you would see they are equal to 49, 50, 51, 52, 53,respectively.
How to Solve the Issue
To fix this issue, run a loop through the int number, take it apart digit by digit, and store them as ints, not chars, and then just sort your int[].
Replacing your ArrayList<Integer> to ArrayList<Character> solve this problem because it store characters '1', '2', etc not their Integer values which are 49, 50...
So below code return what you expect: [1, 2, 3, 4, 5]
public static void main(String[] args) {
System.out.println(sortMet(54321));
}
static ArrayList<Character> sortMet(int k) {
ArrayList<Character> tab_cyfr = new ArrayList<>();
char[] chars = String.valueOf(k).toCharArray();
int n = chars.length;
Arrays.sort(chars);
for (int i = 0; i < n; i++) {
tab_cyfr.add(chars[i]);
}
return tab_cyfr;
}
These numbers are ASCII codes of characters in the array. For example, 48 for character 0, 49 for character 1, and so forth.
It seems that you are using an array list of Integers, so the list elements will print like standard int and long integers. To fix the issue, replace ArrayList<Integer> with ArrayList<Character>.
This line does not compile:
tab_cyfr.add(chars[i]);
so it is strange that you get [49, 50, 51, 52, 53].
Even if it compiled it would add the ascii value of chars[i],
but you want its numeric value.
One way to get it is:
tab_cyfr.add(Integer.parseInt("" + chars[i]));
toCharArray() method returns the character array and when you sort array is sorted by its ASCII value. So those random numbers are ASCII values.
To convert char into Integer:-
static ArrayList<Integer> sortMet(int k) {
ArrayList<Integer> tab_cyfr = new ArrayList<>();
char[] chars = String.valueOf(k).toCharArray();
int n = chars.length;
for (int i = 0; i < n; i++) {
tab_cyfr.add(Character.getNumericValue(chars[i]));
}
Collections.sort(tab_cyfr);
return tab_cyfr;
}
This code should work instead.
public static void main(String[] args) {
System.out.println(sortMet(54321));
}
static ArrayList<Integer> sortMet(int k) {
ArrayList<Integer> tab_cyfr = new ArrayList<>();
char[] chars = String.valueOf(k).toCharArray();
int n = chars.length;
Arrays.sort(chars);
for (int i = 0; i < n; i++) {
tab_cyfr.add(Character.getNumericValue(chars[i]));
}
return tab_cyfr;
}
Character.getNumericValue(chars[i]) ensures that you push the actual char value into tab_cyfr and not the ASCII value of it.
Related
I'm trying to get the N smallest numbers (given by the user) in an array without using methods like sort()... in the last step, I keep getting only the smallest values and 0 for the rest.. where's the problem?
//1- Scanner to take inputs
Scanner input = new Scanner(System.in);
//2- Take the array size as input and store it in "sizeOfArr" var
System.out.print("Enter the array size: ");
int sizeOfArr = input.nextInt();
//3- Assign the input as an array size
int array[] = new int[sizeOfArr];
//4- Looping on the array and update its values by inputs taken from the user
for(int i = 0; i < array.length; i++) {
System.out.print("Enter "+ (i+1) + "-st element: ");
array[i] = input.nextInt();
}
//5- Print out the array after convert it to String
System.out.println(Arrays.toString(array));
//6- Find the smallest element in the array and print it
int minVal = array[0];
for(int i = 0; i < array.length; i++) {
if (array[i] < minVal) {
minVal = array[i];
}
}
// System.out.println(minVal);
//7- Find the (n) smallest of number defined by the user
System.out.print("Enter the number of smallest numbers do you want: ");
int n = input.nextInt();
//8- new array to store n smallest numbers
int smallestNums[] = new int[n];
//9- trying to loop on the original array n times
int counter;
for(int i = 0; i < n ; i++) {
//10- trying to loop on the original array to store the smallest values in smallestNum[] array.
for(int j = 0; j < array.length; j++) {
smallestNums[i] = minVal;
}
if(smallestNums[i] == smallestNums[i]) {
break;
}
}
System.out.println(Arrays.toString(smallestNums));
Here is one way. Just do a partial sort with the outer loop limit equal to the number of items required. This is variant of the selection sort. This example, varies n in the outer list for demo purposes.
int[] array = { 10, 1, 5, 8, 7, 6, 3 };
for (int n = 1; n <= array.length; n++) {
int[] smallest = getNSmallest(n, array);
System.out.printf("smallest %2d = %s%n", n,
Arrays.toString(smallest));
}
prints
smallest 1 = [1]
smallest 2 = [1, 3]
smallest 3 = [1, 3, 5]
smallest 4 = [1, 3, 5, 6]
smallest 5 = [1, 3, 5, 6, 7]
smallest 6 = [1, 3, 5, 6, 7, 8]
smallest 7 = [1, 3, 5, 6, 7, 8, 10]
Here is the method. The first thing to do is copy the array so the
original is preserved. Then just do the sort and return array of smallest elements.
public static int[] getNSmallest(int n, int[] arr) {
int[] ar = Arrays.copyOf(arr, arr.length);
int[] smallest = new int[n];
for (int i = 0; i < n; i++) {
for (int k = i + 1; k < ar.length; k++) {
if (ar[i] > ar[k]) {
int t = ar[i];
ar[i] = ar[k];
ar[k] = t;
}
}
smallest[i] = ar[i];
}
return smallest;
}
For this task, you don't have to sort the whole array. Only a group of N elements has to be sorted. I.e. only a partial sorting is required.
Below, I've provided two implementations for this problem. The first utilizes only plane arrays and loops, the second makes use of the PriorytyQueue.
The first solution maintains a variable pos which denotes the position in the result array which isn't assigned yet. Note that the default value for an element of the int[] is 0. It's important to be able to distinguish between the default value and a zero-element from the given array. Hence we can't rely on the values and have to track the number of elements that are assigned.
Every element of the source array gets compared with all the elements of the result array that are already assigned. The new element will be added to the result array in two cases:
nested loop has reached an unoccupied position pos in the result array;
an element in the result array that is greater than the next element from the given array has been found.
In the first case, a new element gets assigned the position denoted by pos. In the second case, a new element has to be inserted
nested loop iterates over the given array at the current position i and all elements must be shifted to the right. That's what the method shiftElements() does.
The First solution - Arrays & Loops
public static int[] getSmallest(int[] arr, int limit) {
int[] result = new int[Math.min(limit, arr.length)];
int pos = 0;
for (int next: arr) {
for (int i = 0; i < Math.min(pos + 1, result.length); i++) {
if (i == pos) result[i] = next;
else if (result[i] > next) {
shiftElements(result, next, i, Math.min(pos + 1, result.length));
break;
}
}
pos++;
}
return result;
}
private static void shiftElements(int[] arr, int val, int start, int end) {
int move = arr[start];
arr[start] = val;
for (int i = start + 1; i < end; i++) {
int temp = arr[i];
arr[i] = move;
move = temp;
}
}
Maybe you'll be more comfortable with the first version, but if you are somehow familiar with the Collections framework, then it's a good time to get acquainted with PriorytyQueue. In the nutshell, this collection is backed by an array and maintains its element in the same order as they were added, but when an element is being deleted collection retrieves the smallest one according to the natural order or based on the Comparator, which can be provided while instantiating the PriorytyQueue. It uses a sorting algorithm that is called a heapsort which allows removing a single element in O(log N) time.
The Second solution - PriorytyQueue
public static int[] getSmallestWithPriorityQueue(int[] arr, int limit) {
Queue<Integer> queue = new PriorityQueue<>();
populateQueue(queue, arr);
int[] result = new int[Math.min(limit, arr.length)];
for (int i = 0; i < result.length; i++) {
result[i] = queue.remove();
}
return result;
}
private static void populateQueue(Queue<Integer> queue, int[] arr) {
for (int next: arr) {
queue.add(next);
}
}
main & utility-method to generate an array
public static void main(String[] args) {
int[] source = generateArr(100, 10);
System.out.println("source : " + Arrays.toString(source));
int[] result1 = getSmallest(source, 3);
System.out.println("result(Arrays & Loops) : " + Arrays.toString(result1));
int[] result2 = getSmallestWithPriorityQueue(source, 3);
System.out.println("result(PriorityQueue) : " + Arrays.toString(result2));
}
public static int[] generateArr(int maxVal, int limit) {
Random random = new Random();
return IntStream.generate(() -> random.nextInt(maxVal + 1))
.limit(limit)
.toArray();
}
output
source : [61, 67, 78, 53, 74, 51, 50, 83, 59, 21]
result(Arrays & Loops) : [21, 50, 51]
result(PriorityQueue) : [21, 50, 51]
Randomized select allows to find k-th ranked element in linear time on average.
It alters the input order, so practically, it makes sense to just sort and return k-th element of the sorted array. Especially if there are several such calls on the given input array.
Code written below is correct, but I want to shorten this code.
Write a program in java to enter 10 numbers in Single dimensional array and arrange them in such a way that all even numbers are followed by all odd numbers.
int a[] = new int[6];
int b[] = new int[6];
int i, j;
int k = 0;
System.out.println("enter array");
for (i = 0; i < 6; i++) {
a[i] = sc.nextInt();
}
for (j = 0; j < 6; j++) {
if (a[j] % 2 == 0) {
b[k] = a[j];
k++;
}
}
for (j = 0; j < 6; j++) {
if (a[j] % 2 != 0) {
b[k] = a[j];
k++;
}
}
System.out.println("out-put");
for (i = 0; i < 6; i++) {
System.out.println(b[i]);
}
Can I arrange the even numbers and the odd numbers in a single for loop instead of two for loop? I am using two for loop to transfer the even and the odd numbers into b[] array. Please shorten code. One for loop traverse for checking even number and second for odd numbers.
Here is a simple program for you.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
/**
*
* #author Momir Sarac
*/
public class GroupByEvenAndOddNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// create a collection
List<Integer> listOfNumbers = new ArrayList<>();
// do code within a loop for 10 times
for(int i=0;i<10;i++)
{
//print to screen this text
System.out.println("Input your number:");
//get next input integer
int number = scanner.nextInt();
// add it to collection
listOfNumbers.add(number);
}
// sort this collection, list of numbers
// convert all numbers(positive and negative ) within to 0 or 1 depending whether or not they are even or odd and sort them accordignaly.
Collections.sort(listOfNumbers, Comparator.comparingInt(n -> Math.floorMod(n, 2)));
//print sorted collection
System.out.println("Ordered list ..." + listOfNumbers);
}
}
In this version, it copies the even to the start, and the odd to the end.
static int[] sortEvenOdd(int... nums) {
int even = 0, odd = nums.length, ret[] = new int[nums.length];
for (int num : nums)
if (num % 2 == 0)
ret[even++] = num;
else
ret[--odd] = num;
return ret;
}
public static void main(String[] args) {
int[] arr = {1, 3, 2, 4, 7, 6, 9, 10};
int[] sorted = sortEvenOdd(arr);
System.out.println(Arrays.toString(sorted));
}
prints
[2, 4, 6, 10, 9, 7, 3, 1]
This Code will help you to segregate Even and Odd numbers.
// java code to segregate even odd
// numbers in an array
public class GFG {
// Function to segregate even
// odd numbers
static void arrayEvenAndOdd(
int arr[], int n)
{
int i = -1, j = 0;
while (j != n) {
if (arr[j] % 2 == 0)
{
i++;
// Swapping even and
// odd numbers
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
j++;
}
// Printing segregated array
for (int k = 0; k < n; k++)
System.out.print(arr[k] + " ");
}
// Driver code
public static void main(String args[])
{
int arr[] = { 1, 3, 2, 4, 7,
6, 9, 10 };
int n = arr.length;
arrayEvenAndOdd(arr, n);
}
}
As you don't have any requirements that the even and odd numbers itself have to be ordered in their respectively half of the array you can just assign them to their associated array part while entering them.
Therefore you just have to use two "counter" variables one for the left which starts at zero and is incremented and one for the right which starts at your array length minus one and is decremented. Then you can add your numbers, checking if one is even add assign it with your left counter post incremented and if one is odd assign it with your right counter post decremented. Do this within a loop, until your left counter is bigger than your right counter.
I created a simple example where I did not check for NumberFormatException when parsing the String to an int:
import java.util.Arrays;
import java.util.Scanner;
public class SortedArrayInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter length of array: ");
final int arrayLength = Integer.parseInt(scanner.nextLine());
int intArray[] = new int[arrayLength];
for (int l = 0, r = arrayLength - 1; l <= r; ) {
System.out.print("Enter new array value: ");
int v = Integer.parseInt(scanner.nextLine());
intArray[v % 2 == 0 ? l++ : r--] = v;
}
System.out.println("Output: " + Arrays.toString(intArray));
}
}
Sample input/output:
Enter length of array: 6
Enter new array value: 1
Enter new array value: 2
Enter new array value: 3
Enter new array value: 4
Enter new array value: 5
Enter new array value: 6
Output: [2, 4, 6, 5, 3, 1]
I recommend reading up on streams, they will make collection processing a lot easier for you
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
numbers.add(6);
numbers.add(7);
numbers.add(8);
numbers.add(9);
numbers.add(0);
//this way you simply traverse the numbers twice and output the needed ones
System.out.println(numbers.stream()
.filter(x->x%2==0)
.collect(Collectors.toList()));
System.out.println(numbers.stream()
.filter(x->x%2==1)
.collect(Collectors.toList()));
//this way you can have the numbers in two collections
numbers.forEach(x-> x%2==0? addItToEvenCollection : addItToOddCollection);
//this way you will have a map at the end. The boolean will tell you if the numbers are odd or even,
// and the list contains the numbers, in order of apparition in the initial list
numbers.stream().collect(Collectors.groupingBy(x->x%2==0));
A performant way to check if a number is even, is to use
if ( (x & 1) == 0 )
This program finds the count of duplicates in a string.
Example 1:
Input:
"abbdde"
Output:
2
Explanation:
"b" and "d" are the two duplicates.
Example 2:
Input:
"eefggghii22"
Output:
3
Explanation:
duplicates are "e", "g", and "2".
Help me with this code.
public class CountingDuplicates {
public static int duplicateCount(String str1) {
// Write your code here
int c = 0;
str1 = str1.toLowerCase();
final int MAX_CHARS = 256;
int ctr[] = new int[MAX_CHARS];
countCharacters(str1, ctr);
for (int i = 0; i < MAX_CHARS; i++) {
if(ctr[i] > 1) {
// System.out.printf("%c appears %d times\n", i, ctr[i]);
c = ctr[i];
}
}
return c;
}
static void countCharacters(String str1, int[] ctr)
{
for (int i = 0; i < str1.length(); i++)
ctr[str1.charAt(i)]++;
}
}
You need to maintain a count and if the value of that character exceeds 1, you need to increment the count.
Return that count to know the count of duplicates.
Added comments to understand the code better.
public class CountingDuplicates {
public static int duplicateCount(String str1) {
// Initialised integer to count the duplicates
int count = 0;
// Converting a string to lowercase to count lowerCase and Uppercase as duplicates
str1 = str1.toLowerCase();
// According to ASCII, the Maximum number of characters is 256,
// So, initialized an array of size 256 to maintain the count of those characters.
final int MAX_CHARS = 256;
int ctr[] = new int[MAX_CHARS];
countCharacters(str1, ctr);
for (int i = 0; i < MAX_CHARS; i++) {
if(ctr[i] > 1) {
// System.out.printf("%c appears %d times\n", i, ctr[i]);
count = count + 1;
}
}
return count;
}
static void countCharacters(String str1, int[] ctr)
{
for (int i = 0; i < str1.length(); i++)
ctr[str1.charAt(i)]++;
}
}
In short it is counting the number of characters appearing in the String str and saving it in ctr array.
How? ctr is the array that has a length of 256. So it can have 256 values (0-255 indexed). str1 is the string that contains the String. charAt(i) method returns the character at index i. Because String acts like an array where you can access each char a index values of an array.
Now assuming your input will always ASCII characters, each ASCII chars contain a value of 0-255 (i.e. ASCII value 'a' is 97). ++ after any variable means adding 1 to that. i.e.c++ means c = c+1
Now coming to the loop, ctr[str1.charAt(i)]++;, you can see the loops starts from 0 and ends at the length of the String str where 0 is the first value str. So if value of 0 indexed value (first value) of the String str is a, str.charAt(0) would return 97(well actually it will return 'a' but java takes the ASCII value). so the line actually is (for 0 th index) ctr[97]++; so it's incrementing the value of the 97th index (which is initially 0) by 1. So now the value is 1.
Like this way it will only increment the index values that matches with the ASCII values of the character in the String, thus counting the amount of time the characters occur.
I'm confusing how to transform values in 2D char array into number (integer).
Let's assume the array is: [[a, b],[c, d],[e, f]] or {{'a','b'},{'c','d'},{'e','f'}}
All values in that array will be converted to number, a=0, b=1, c=2, d=3, e=4, f=5.
I expect result like: [[0, 1], [2, 3], [4, 5]] or {{0, 1},{2, 3},{4, 5}}
If it's just a string of "abcdef", I can use charAt(), but I can' use it in an array, especially in char array. So, I use .replace.
package array_learning;
public class test {
public static void main(String[] args){
char [][] word= {{'a','b'},{'c','d'},{'e','f'}};
int strLength = word.length;
for(int i = 0; i<strLength; i++){
for(int j=0; j<2; j++){
String strWord = Character.toString(word[i][j]);
strWord = strWord.replace("a","0");
strWord = strWord.replace("b","1");
strWord = strWord.replace("c","2");
strWord = strWord.replace("d","3");
strWord = strWord.replace("e","4");
strWord = strWord.replace("f","5");
System.out.print(strWord+" ");
}
System.out.println();
}
}
}
But, the result is not what I've expected.
Result:
0 1
2 3
4 5
How to solve this in the right way?
Consider:
import java.util.Arrays;
public class Ctest {
public static void main(String[] args) {
char[][] word= { {'a', 'b'}, {'c', 'd'}, {'e', 'f'} };
println(word); // format with brackets e.g., [[a, b], [c, d]]
System.out.println(Arrays.deepToString(word)); // same format
for (int i = 0; i < word.length; i++) {
for (int j = 0; j < word[i].length; j++) {
if (word[i][j] >= 'a' && word[i][j] <= 'f') {
word[i][j] = (char) ((word[i][j] - 'a') + '0');
}
}
}
println(word); // formatted with brackets
printPlain(word); // formatted without brackets
}
public static void println(char[][] word) {
System.out.print("[");
for (int i = 0; i < word.length; i++) {
if (i > 0) System.out.print(", ");
System.out.print("[");
for (int j = 0; j < word[i].length; j++) {
if (j > 0) System.out.print(", ");
System.out.print(word[i][j]);
}
System.out.print("]");
}
System.out.println("]");
}
public static void printPlain(char[][] word) {
for (int i = 0; i < word.length; i++) {
if (i > 0) System.out.print(", ");
for (int j = 0; j < word[i].length; j++) {
if (j > 0) System.out.print(", ");
System.out.print(word[i][j]);
}
}
System.out.println();
}
}
The main changes I have made are that the values in the array are actually converted (I'm not sure if you want this; you weren't storing any new values back into the array before), the data is handled as char without being converted to String, the conversion is done with a calculation instead of a special case for each value, and converting the data and printing it have been separated from one another.
There are also a few minor changes. The data is now printed in the format you demonstrated, with brackets, there is no assumption that the inner arrays always have exactly two elements, and the class name has been changed to start with a capital letter.
One other minor note. On the line that converts the values from lower case letters to digits, the expression is in parentheses and is cast back to a char. This is because when you add and subtract chars Java performs a widening conversion to int, so to store the value back into the char[][] it is necessary to cast it to char again.
I had forgotten that there is already a method in Java in the java.util.Arrays class to format a multidimensional array with brackets: Arrays.deepToString(word) will give you the same format as the println method above. I had also shown a printPlain method which is similar, but lacks the brackets, if you prefer a cleaner output format. You could also easily modify this method so that it appends to a StringBuilder and returns a String, instead of printing the array directly.
Everything is matching up correctly. This is a 2d array so your arrays are printing one by one.
If you don't want them to go on seperate lines then get rid of the System.out.println(); statement at the end of the for loop.
Use Arrays.toString() to convert your array into string first. Then do the replacement. For example:
char [][] word= {{'a','b'},{'c','d'},{'e','f'}};
String strWord = "";
for(char []w : word){
// convert array int [x, y] format
strWord += Arrays.toString(w)+",";
}
// removing comma(,) from end.
strWord = strWord.replaceAll(",$", "");
// do your replacement.
strWord = strWord.replace("a","0");
// ... more
// output
System.out.println("["+strWord+"]");
I'm trying to convert a string to an array of integers so I could then perform math operations on them. I'm having trouble with the following bit of code:
String raw = "1233983543587325318";
char[] list = new char[raw.length()];
list = raw.toCharArray();
int[] num = new int[raw.length()];
for (int i = 0; i < raw.length(); i++){
num[i] = (int[])list[i];
}
System.out.println(num);
This is giving me an "inconvertible types" error, required: int[] found: char
I have also tried some other ways like Character.getNumericValue and just assigning it directly, without any modification. In those situations, it always outputs the same garbage "[I#41ed8741", no matter what method of conversion I use or (!) what the value of the string actually is. Does it have something to do with unicode conversion?
There are a number of issues with your solution. The first is the loop condition i > raw.length() is wrong - your loops is never executed - thecondition should be i < raw.length()
The second is the cast. You're attempting to cast to an integer array. In fact since the result is a char you don't have to cast to an int - a conversion will be done automatically. But the converted number isn't what you think it is. It's not the integer value you expect it to be but is in fact the ASCII value of the char. So you need to subtract the ASCII value of zero to get the integer value you're expecting.
The third is how you're trying to print the resultant integer array. You need to loop through each element of the array and print it out.
String raw = "1233983543587325318";
int[] num = new int[raw.length()];
for (int i = 0; i < raw.length(); i++){
num[i] = raw.charAt(i) - '0';
}
for (int i : num) {
System.out.println(i);
}
Two ways in Java 8:
String raw = "1233983543587325318";
final int[] ints1 = raw.chars()
.map(x -> x - '0')
.toArray();
System.out.println(Arrays.toString(ints1));
final int[] ints2 = Stream.of(raw.split(""))
.mapToInt(Integer::parseInt)
.toArray();
System.out.println(Arrays.toString(ints2));
The second solution is probably quite inefficient as it uses a regular expression and creates string instances for every digit.
Everyone have correctly identified the invalid cast in your code. You do not need that cast at all: Java will convert char to int implicitly:
String raw = "1233983543587325318";
char[] list = raw.toCharArray();
int[] num = new int[raw.length()];
for (int i = 0; i < raw.length(); i++) {
num[i] = Character.digit(list[i], 10);
}
System.out.println(Arrays.toString(num));
You shouldn't be casting each element to an integer array int[] but to an integer int:
for (int i = 0; i > raw.length(); i++)
{
num[i] = (int)list[i];
}
System.out.println(num);
this line:
num[i] = (int[])list[i];
should be:
num[i] = (int)list[i];
You can't cast list[i] to int[], but to int. Each index of the array is just an int, not an array of ints.
So it should be just
num[i] = (int)list[i];
For future references. char to int conversion is not implicitly, even with cast. You have to do something like that:
String raw = "1233983543587325318";
char[] list = raw.toCharArray();
int[] num = new int[list.length];
for (int i = 0; i < list.length; i++){
num[i] = list[i] - '0';
}
System.out.println(Arrays.toString(num));
This class here: http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html should hep you out. It can parse the integers from a string. It would be a bit easier than using arrays.
Everyone is right about the conversion problem. It looks like you actually tried a correct version but the output was garbeled. This is because system.out.println(num) doesn't do what you want it to in this case:) Use system.out.println(java.util.Arrays.toString(num)) instead, and see this thread for more details.
String raw = "1233983543587325318";
char[] c = raw.toCharArray();
int[] a = new int[raw.length()];
for (int i = 0; i < raw.length(); i++) {
a[i] = (int)c[i] - 48;
}
You can try like this,
String raw = "1233983543587325318";
char[] list = new char[raw.length()];
list = raw.toCharArray();
int[] num = new int[raw.length()];
for (int i = 0; i < raw.length(); i++) {
num[i] = Integer.parseInt(String.valueOf(list[i]));
}
for (int i: num) {
System.out.print(i);
}
Simple and modern solution
int[] result = new int[raw.length()];
Arrays.setAll(result, i -> Character.getNumericValue(raw.charAt(i)));
Line num[i] = (int[])list[i];
It should be num[i] = (int) list[i];
You are looping through the array so you are casting each individual item in the array.
The reason you got "garbage" is you were printing the int values in the num[] array.
char values are not a direct match for int values.
char values in java use UTF-16 Unicode.
For example the "3" char translates to 51 int
To print out the final int[] back to char use this loop
for(int i:num)
System.out.print((char) i);
I don't see anyone else mentioning the obvious:
We can skip the char array and go directly from String to int array.
Since java 8 we have CharSequence.chars which will return an IntStream so to get an int array, of the char to int values, from a string.
String raw = "1233983543587325318";
int[] num = raw.chars().toArray();
// num ==> int[19] { 49, 50, 51, 51, 57, 56, 51, 53, 52, 51, 53, 56, 55, 51, 50, 53, 51, 49, 56 }
There are also some math reduce functions on Intstream like sum, average, etc. if this is your end goal then we can skip the int array too.
String raw = "1233983543587325318";
int sum = raw.chars().sum();
// sum ==> 995
nJoy!