so basically user enters a sequence from an scanner input.
12, 3, 4
, etc.
It can be of any length long and it has to be integers.
I want to convert the string input to an integer array.
so int[0]
would be 12
, int[1]
would be 3
, etc.
Any tips and ideas? I was thinking of implementing if charat(i) == ','
get the previous number(s) and parse them together and apply it to the current available slot in the array. But I'm not quite sure how to code that.
This question is related to
java
string
integer
user-input
data-manipulation
Line by line
int [] v = Stream.of(line.split(",\\s+"))
.mapToInt(Integer::parseInt)
.toArray();
Java has a method for this, "convertStringArrayToIntArray".
String numbers = sc.nextLine();
int[] intArray = convertStringArrayToIntArray(numbers.split(", "));
Stream.of().mapToInt().toArray()
seems to be the best options.
int[] arr = Stream.of(new String[]{"1", "2", "3"})
.mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(arr));
Converting String array into stream and mapping to int is the best option available in java 8.
String[] stringArray = new String[] { "0", "1", "2" };
int[] intArray = Stream.of(stringArray).mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(intArray));
For Java 8 and higher:
String[] test = {"1", "2", "3", "4", "5"};
int[] ints = Arrays.stream(test).mapToInt(Integer::parseInt).toArray();
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class MultiArg {
Scanner sc;
int n;
String as;
List<Integer> numList = new ArrayList<Integer>();
public void fun() {
sc = new Scanner(System.in);
System.out.println("enter value");
while (sc.hasNextInt())
as = sc.nextLine();
}
public void diplay() {
System.out.println("x");
Integer[] num = numList.toArray(new Integer[numList.size()]);
System.out.println("show value " + as);
for (Integer m : num) {
System.out.println("\t" + m);
}
}
}
but to terminate the while loop you have to put any charecter at the end of input.
ex. input:
12 34 56 78 45 67 .
output:
12 34 56 78 45 67
Source: Stackoverflow.com