在Java中,从键盘输入一维数组可以通过以下方法实现:
1. 使用`Scanner`类:
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("Enter the size of the array: ");int size = scanner.nextInt();int[] array = new int[size];System.out.println("Enter the elements of the array:");for (int i = 0; i < size; i++) {array[i] = scanner.nextInt();}System.out.println("The input array is:");for (int i = 0; i < size; i++) {System.out.print(array[i] + " ");}scanner.close();}}
2. 使用Java 8的`Stream API`:
import java.util.Scanner;import java.util.stream.IntStream;public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("Enter the size of the array: ");int size = scanner.nextInt();int[] array = IntStream.range(0, size).mapToObj(i -> scanner.nextInt()).toArray();System.out.println("The input array is:");IntStream.of(array).forEach(System.out::print);scanner.close();}}
以上两种方法都可以实现从键盘输入一维数组并输出。请选择适合您需求的方法进行操作
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/63698.html