Java array input and output

To perform input operations on the console in Java, you need to call the Scanner class to define a scanned object, for example:

//To import java.util.Scanner; Scanner scanner = new Scanner(System.in); 12

This opens the input stream, and then defines the array:

int[] n = new int[4];//Use square brackets, use parentheses will report an error 1

Next, you can enter the input obtained by the console into the array, and you need to call the nextInt() method of the Scanner object:

for(int i=0;i<4;i++) { 
         n[i] = scanner.nextInt(); 
     } 
     scanner.close();//When you end the input, don’t forget to close the input stream and call the close of the Scanner object Method can be 1234

Finally, to print the input array, you need to call the Arrays.toString("parameter") method, the parameter is the name of the array declaration, without []:

System.out.println("You input is:" + Arrays.toString(n));//需要导入java.util.Arrays;12

Complete source code:

package com.linhualuo;
import java.util.Arrays;
import java.util.Scanner;public class mainTest { public static void main(String[] args) {
     Scanner scanner = new Scanner(System.in);
     System.out.println("Your first number:");     int[] n = new int[4];     for(int i=0;i<4;i++) {
         n[i] = scanner.nextInt();
     }
     scanner.close();
     System.out.println("You input is:" + Arrays.toString(n));
}
}123456789101112131415161718

operation result:
Write picture description here

Guess you like

Origin blog.csdn.net/benli8541/article/details/112798863