I have made research for a couple hours trying to figure out how to convert a String array to a Int array but no luck.
I am making a program where you can encrypt a message by using three rotors. I am able to type a message and get the index number for the first rotor (inner rotor) to encrypt into the third rotor (outer rotor). The problem is the index number is in a string array which I want it to become a int array.
Yes, I have tried
int[] array == Arrays.asList(strings).stream()
.mapToInt(Integer::parseInt).toArray();
or any form of that. I'm not unsure if I have java 8 since it doesn't work, but it gives me an error.
Can someone help me how to convert a String array to a Int array?
public void outerRotorEncrypt() {
String[] indexNumberSpilt = indexNumber.split(" ");
System.out.println("indexNumber length: " + indexNumber.length()); //test
System.out.println("indexNumberSpilt length: " + indexNumberSpilt.length); //test
System.out.println("Index Number Spilt: " + indexNumberSpilt[3]); //test
System.out.println("");
System.out.println("");
System.out.println("testing from outerRotorEncrypt");
System.out.println("");
for(int i = 1; i < indexNumberSpilt.length; i++){
secretMessage = secretMessage + defaultOuterRotorCharacterArray[indexNumberSpilt[i]];
}
System.out.println("Secret Message from outerRotorEncrypt: " + secretMessage);
}
If you are using Java8 than this is simple way to solve this issue.
List<?> list = Arrays.asList(indexNumber.split(" "));
list = list.stream().mapToInt(n -> Integer.parseInt((String) n)).boxed().collect(Collectors.toList());
In first Line you are taking a generic List Object and convert your array into list and than using stream api same list will be filled with equivalent Integer value.
static int[] parseIntArray(String[] arr) {
return Stream.of(arr).mapToInt(Integer::parseInt).toArray();
}
So take a Stream of the String[]. Use mapToInt to call Integer.parseInt for each element and convert to an int. Then simply call toArray on the resultant IntStream to return the array.
Have you tried:
int[] array = new int[indexNumberSpilt.lenght()];
for ( int i=0;i<indexNumberSpilt.lenght();i++ ){
array[i] = Integer.valueOf(indexNumberSpilt[i]);
}
int[] array == Arrays.asList(strings).stream()
.mapToInt(Integer::parseInt).toArray();
The reason why it's giving an error is because of ==, changing that to = (assignment operator) should work, e.g.:
String[] input = new String[]{"1", "2"};
int[] array = Arrays.asList(input).stream()
.mapToInt(Integer::parseInt).toArray();
for(int a : array){
System.out.println(a);
}
Small Demo
String[] string = { "0", "1", "11", "0", "0", "1", "11", "0", "0", "1",
"11", "0" };
List<String> temp = Arrays.asList(string);
List<Integer> temp1 = new ArrayList<Integer>();
for (String s : temp) {
temp1.add(Integer.parseInt(s));
}
int[] ret = new int[temp1.size()];
for (int i = 0; i < ret.length; i++) {
ret[i] = temp1.get(i).intValue();
}
System.out.println(Arrays.toString(ret));
}
int[]
If you want an int[] array:
String indexNumber = "1 2 3 4";
String[] indexNumberSpilt = indexNumber.split(" ");
int[] result = Stream.of(indexNumberSpilt).mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(result));
Integer[]
String indexNumber = "1 2 3 4";
String[] indexNumberSpilt = indexNumber.split(" ");
Integer[] result = Stream.of(indexNumberSpilt).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);
System.out.println(Arrays.toString(result));
Both examples will print:
[1, 2, 3, 4]
Related
Does the .split() function even exist?
When I type:
public class Main {
public static void main(String[] args) {
String numbers = "1, 2, 3, 4, 5";
int[] numbers2 = (int[]) numbers.split(", ");
System.out.println(numbers2);
}
}
It says:
Main.java:4: error: incompatible types: String[] cannot be converted to int[]
int[] numbers2 = (int[]) numbers.split(", ");
^
1 error
numbers.split(", ") returns a String array. You can use the following to map a String array to an int array.
int[] numbers2 = Arrays.stream(numbers.split(", ")).mapToInt(Integer::parseInt).toArray();
yes the method String[] split​(String regex) for reference type String exists, here is the reference https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#split(java.lang.String) for Java SE 11.
But you are trying to cast a variable of reference type String to an array of primitive int-type, which cannot be achieved directly in Java without parsing.
Split your String variable into a String-Array
String numbers = "1, 2, 3, 4, 5";
String[] numbersSplitted = numbers.split(", ");
Parse your String-Array to an int-Array
int [] numbersParsed = new int[numbersSplitted.length];
for(int i = 0; i < numbersSplitted.length; i++){
numbersParsed[i] = Integer.parseInt(numbersSplitted[i]);
}
Print the parsed array or each element of the parsed array out to the console
System.out.println(Arrays.toString(numbersParsed));
// or print each element of the parsed array
for (int val : numbersParsed) {
System.out.println(val);
}
Hopefully, this will help out!
I want to built in ten arrays of size n and place in the first stings of length one, in the second strings of length two and so forth where the tenth array has strings of length ten.
Array String = { a, b, the , c , no, yes, and, or, ...}
Array length_string = [ 1 , 1, 3, 1 , 2, 3, 3 , 2 , ....}
I don't understand how to do this, place string with same length into block:
[a,b,c] //every string length =1
[no,or] // every string length =2
[the,yes,and] // every string length =3
and so on
Edit:
I found hash Map work with my code
`final Map<Integer, List> lengthToWords = new TreeMap<>(
Arrays.stream(words).collect(Collectors.groupingBy(String::length)));
But how can control block size
I meaning want each block = 256
1 [ a , b ,c ,...] number element =256 , not more that
2 [ aa, bb, cc ,..] number element =256
and so on until ten block
I have ten block by using loop , Now i need limit number element inside block
Hi if your solution doesn't need to be efficient or your array size is limit you can do it with nested loops.
for(int i =1;i<=n;i++){
for(int j = 0;j<stringArray.length;j++){
if(i == stringArray[j].length){
resultArray[i-1] = stringArray[j];
break;
}
else
continue;
}
}
Be careful to check arrayIndexOutOfBound exception
String[] arr= { "a", "b", "the" , "c" , "no", "yes", "and", "or"};
String length1="[";
String length2="[";
String length3 ="[";
for (int i = 0; i < arr.length; i++)
{
switch(arr[i].length())
{
case 1:
length1=length1+ arr[i]+",";
break;
case 2:
length2=length2+ arr[i]+",";
break;
case 3:
length3=length3+ arr[i]+",";
break;
}
}
if (length1.endsWith(",")) {
length1 = length1.substring(0, length1.length()-1);
}
if (length2.endsWith(",")) {
length2 = length2.substring(0, length2.length()-1);
}
if (length3.endsWith(",")) {
length3 = length3.substring(0, length3.length()-1);
}
length1=length1+"]";
length2=length2+"]";
length3=length3+"]";
System.out.println(length1);
System.out.println(length2);
System.out.println(length3);
output :
[a,b,c]
[no,or]
[the,yes,and]
Below is the complete Java code with example input. The createBlockList does the following: 1) Create a list of lists to store the result. 2)Iterate through the string array and place the string in the right lists.
import java.util.*;
public class MyClass {
public static void createBlockList(String[] strArr, int[] strLenArr) {
List<List<String>>resList = new ArrayList<>();
for(int i=0; i<3; i++) {
resList.add(new ArrayList());
}
for(int i=0; i<strArr.length; i++) {
int strLen = strLenArr[i];
resList.get(strLen-1).add(strArr[i]);
}
}
public static void main(String []args){
String str[] = {"a","b","in","on","the","and"};
int len[] = {1,1,2,2,3,3};
createBlockList(str, len);
}
}
I want to append a and b string arrays to arrayList. But "1.0" have to be "1" using with split. Split method returns String[] so arrayList add method does not work like this.
Can you suggest any other way to doing this ?
String[] a = {"1.0", "2", "3"};
String[] b = {"2.3", "1.0","1"};
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add(a[0].split("."));
arrayList.add(a[0].split("\\.")[0]);
Should be as below
arrayList.add(a[0].split("\\.")[0]);
Split method returns an array. You have to access to his position to get the number.
arrayList.add(a[0].split("\\.")[0]);
You can also use substring method:
arrayList.add(a[0].substring(0, 1));
Access first element of that array like this :
for (int i = 0; i < a.length; i++) {
if (a[i].contains("."))
arrayList.add(a[i].split("\\.")[0]);
else
arrayList.add(a[i]);
}
Why split it?. Just use a replaceAll(), it will be more efficient as it won't create an array of Strings.
public static void main(String[] args) {
String[] a = { "1.7", "2", "3" };
List<String> arrayList = new ArrayList<String>();
for (int i = 0; i < a.length; i++) {
arrayList.add(a[i].replaceFirst("\\..*", "")); // escape the . (match it as a literal), then followed by anything any number of times.
}
System.out.println(arrayList);
}
O/P :
[1, 2, 3]
If you use Java 8,
String[] a = {"1.0", "2", "3"};
List<String> list = Arrays.stream(a).map(s -> s.split("\\.")[0]).collect(Collectors.toList());
// OR
List<String> list2 = Arrays.stream(a).map(s -> {
int dotIndex = s.indexOf(".");
return dotIndex < 0 ? s : s.substring(0, dotIndex);
}).collect(Collectors.toList());
This is working properly for me: arrayList.add(a[0].split("\\.")[0]);
this is what i have so far, i need to convert this string array into just an array of integers, the string array looks something like this
wholef[0] = "2 3 4";
wholef[1] = "1 3 4";
wholef[2] = "5 3 5";
wholef[3] = "4 5 6";
wholef[4] = "3 10 2";
these values come from a text file that i read from but now i need to convert this into one big array of integers, im trying to use the split method but im not sure if it will work on this kind of setup. if anyone can give me a better way it would be nice but i just need to convert this into an array of integers, thats really all i need.
for(int k = 0; k < fline; k++)
{
String[] items = wholef[k].replaceAll(" ", "").split(",");
int[] parsed = new int[wholef[k].length];
for (int i = 0; i < wholef[k].length; i++)
{
try
{
parsed[i] = Integer.parseInt(wholef[i]);
} catch (NumberFormatException nfe) {};
}
}
This is the new code im using now, its very close cause i only get one error
int q = 0;
for (String crtLine : wholef)
{
int[] parsed = new int[wholef.length];
String[] items = crtLine.split(" ");
for (String crtItem: items)
{
parsed[q++] = Integer.parse(crtItem);
}
}
the error is this
java:97: error: cannot find symbol parsed[q++} = Integer.parse(crtItem);
^
symbol: method parse(String)
location: class Integer
1 error
Try this:
int i = 0;
for (String crtLine : wholef) {
String[] items = crtLine.split(" ");
for (String crtItem: items) {
parsed[i++] = Integer.parseInt(crtItem);
}
}
This take your string array and dumps it into intwholef[n..total];
If you want it into a 2D array or an object array you have to do some additional. Then you can do an array of objects, and have each set of values as an attribute.
String[] parts = wholef[0].split(" ");
int[] intwholef= new int[parts.length];
for(int n = 0; n < parts.length; n++) {
intwholef[n] = Integer.parseInt(parts[n]);
}
I have a String[] with numbers like {"12", "3", "5"}.
I want to put these numbers in a int[], like {12, 3, 5}.
How can I do this?
for loop is your friend here.
It will be done using a for loop and string to integer conversion by Integer.parseInt(str).
I will not give any code here but as an algorithm, it will be:
1. Loop over string array.
2. For each string do
a. Convert string to integer
b. store it in integer array
You could write a method that will do the conversion using the parseInt method on each element:
public int[] convert(String[] stringArray) throws NumberFormatException {
if (stringArray == null) {
return null;
}
int intArray[] = new int[stringArray.length];
for (int i = 0; i < stringArray.length; i++) {
intArray[i] = Integer.parseInt(stringArray[i]);
}
return intArray;
}