I want to input a String
like this "5 4 34" from keyboard. How can I export the numbers between spaces? Also a want to export them into an int[]
array, and print them on the screen.
You can use String.split("\\\\s")
to split the String
to String[]
and then use Integer.parseInt()
on each element to get the number as an int
.
Alternatively, you can use a Scanner
, and its nextInt()
method
Since the others have already showed you how it can be done with split()
, here is an example how to do it with Scanner
, directly from System.in
(I am assuming that what you want, because you say you read it from keyboard, of course you can use any Readable
or a String
to build your Scanner
):
Code:
Scanner inputScanner = new Scanner(System.in);
Scanner scanner = new Scanner(inputScanner.nextLine());
List<Integer> list = new ArrayList<Integer>();
while (scanner.hasNextInt()) {
list.add(scanner.nextInt());
}
Integer[] arr = list.toArray(new Integer[0]);
or if you want an int[]
and not an Integer[]
instead of the last line, use:
int[] arr = new int[list.size()];
int i = 0;
for (Integer x : list) {
arr[i++] = x;
}
To print the array just print the result of Arrays.toString()
:
System.out.println(Arrays.toString(arr));
Add an exception handler and you're in good shape:
String values = "5 4 34";
String [] tokens = values.split("\\s+");
List<Integer> numbers = new ArrayList<Integer>();
for (String number : tokens) {
numbers.add(Integer.valueOf(number);
}
Or like this:
String values = "5 4 34";
String [] tokens = values.split("\\s+");
int [] numbers = new int[tokens.length];
for (int i = 0; i < tokens.length; ++i) {
numbers[i] = Integer.valueOf(tokens[i]);
}
String[] stringArray = "5 4 34".split( " " );
int[] intArray = new int[ stringArray.length ];
for ( int i = 0 ; i < stringArray.length ; i++ )
{
intArray[ i ] = Integer.parseInt( stringArray[ i ] );
}
String string = "5 4 34";
String[] components = string.split(" "); // [5, 4, 34]
Without much boilerplate:
List <Integer> numbers = new ArrayList <Integer> ();
for (String number : "5 4 34";.split ("\\s+")) {
int v = Integer.parseInt (number);
System.out.println (v);
numbers.add (v);
}
Or using Scanner:
Scanner scanner = new Scanner ("5 4 34");
List <Integer> list = new ArrayList <Integer> ();
while (scanner.hasNextInt()) {
int v = scanner.nextInt ();
list.add (v);
System.out.println (v);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.