Given the task in which you need to enter numbers into the array, at the same time, you must enter them through the space.
Closed due to the fact that the essence of the question is not clear to the participants 0xdb , Let's say Pie , aleksandr barakin , Sergey Glazirin , Dmitry Kozlov 29 Oct '18 at 10:51 .
Try to write more detailed questions. To get an answer, explain what exactly you see the problem, how to reproduce it, what you want to get as a result, etc. Give an example that clearly demonstrates the problem. If the question can be reformulated according to the rules set out in the certificate , edit it .
- 6If you have not finished editing the question, but have already sent, do not worry - there is a button to edit . - 0xdb
2 answers
For example, like this:
import java.util.Scanner; public class TestClass { public static void main(String[] args) { System.out.println("Введите 5 чисел через запятую:"); Scanner scanner = new Scanner(System.in); int[] array = new int[5]; for (int i=0;i<array.length;i++){ array[i]=scanner.nextInt(); } System.out.println("Ваш массив:"); for (int i=0;i<array.length;i++){ System.out.println(array[i]); } } } The result will be:
If you do not want to bind to the size of the array, then play with ArrayList instead of an array.
Do you want to use a scanner? Most likely your task is to split the string. If this is the case, then the String class has a split method that returns an array of the "pieces" of the source string, which are separated by an expression from the parameter.
// считываем строку из консоли System.out.println("Введите несколько чисел через пробел (или не пробел)"); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String str = reader.readLine(); reader.close(); // применяем метод split и получаем массив из строк // что такое "\\D+" ? это параметр метода split, // регулярное выражение, описывающее любое ненулевое количество не цифр // в частности пробел, попробуйте подставить " ", тоже сработает // но "\\D+" сработает независимо от того какие вообще символы между цифрами String[] splitStr = str.split("\\D+"); // создаем массив из чисел, равный по длине массиву из строк // после разделения через "\\D+" в splitStr будут гарантированно цифры // попробуйте ввести "1 2 3 коза 4" int [] arr = new int[splitStr.length]; // преобразуем каждую строку в число и записываем в ячейку с тем же номером for (int i = 0; i < arr.length; i++){ arr[i] = Integer.parseInt(splitStr[i]); } // проверяем результат, воспользовавшись методом Arrays.toString System.out.println(Arrays.toString(arr)); 