[Java] Input an array from the keyboard

Supplementary knowledge

The Java Scanner class
java.util.Scanner is a new feature of Java5. We can get user input through the Scanner class.

The toString() method is used to return the value of the Number object represented by a string.

1. Get an array of unlimited length from the keyboard

import java.util.Scanner;

public class InputArrayNoLimitLength {
    
    
	public static void main(String[] args) {
    
    
	System.out.println("请输入几个数并用逗号隔开:");
	Scanner sc = new Scanner(System.in);//从键盘接收数据
	String str = sc.next().toString();//next()方式接收字符串
	System.out.println(str);
	String[] arr  = str.split(",");
	
	for(int j = 0; j<arr.length;j++) {
    
    
		System.out.print(arr[j]+" ");
	}
	}
}

Output result

Insert picture description here

2. Obtain a limited-length array from the keyboard

import java.util.Scanner;

public class InputArrayLimitLength {
    
    
	public static void main(String[] args) {
    
    
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		System.out.println("请输入"+n+"个数:");
		Scanner sc = new Scanner(System.in);
		int[] b=new int[n];
		for(int i=0;i<b.length;i++){
    
    
			b[i]=sc.nextInt();
			System.out.print(" " + b[i]);
		}
	}
}

Output result

Insert picture description here

Three, reference

Java Scanner class
Java toString() method

Guess you like

Origin blog.csdn.net/qq_16488989/article/details/109294032