Scanner类输入字符串和整形数字
一、通过Scanner类输入字符串(可以含空格,空格作为字符)
1 package test01; 2 3 import java.util.Scanner; 4 5 public class ScannerDemo02 { 6 7 public static void main(String[] args) { 8 Scanner scan = new Scanner(System.in); 9 scan.useDelimiter("\n"); 10 String str = scan.next(); 11 12 System.out.println(str); 13 } 14 }
另外,可以使用nextLine()达到相同的效果:
此种情况用于,输入一组数,不知道有多少个,占一行,空白分割;
1 package test01; 2 3 import java.util.Scanner; 4 5 public class ScannerDemo02 { 6 7 public static void main(String[] args) { 8 Scanner scan = new Scanner(System.in); 9 //scan.useDelimiter("\n"); 10 String str = scan.nextLine(); 11 12 System.out.println(str); 13 } 14 }
二、连续输入多个字符串,空格作为字符串间的分割符
1 package test01; 2 3 import java.util.Scanner; 4 5 public class ScannerDemo { 6 7 public static void main(String[] args) { 8 9 Scanner scan = new Scanner(System.in); 10 int num = scan.nextInt(); 11 String str[] = new String[num]; 12 for(int i=0;i<num;i++){ 13 str[i] = scan.next(); 14 } 15 for(int i=0;i<num;i++){ 16 System.out.print(str[i] + " "); 17 } 18 } 19 }
三、输入多个整形数字
1 package test01; 2 3 import java.util.Scanner; 4 5 public class ScannerDemo01 { 6 7 public static void main(String[] args) { 8 Scanner in = new Scanner(System.in); 9 int num = in.nextInt(); 10 //循环接收整型 11 int arr[] = new int[num]; 12 for(int i=0;i<num;i++){ 13 arr[i] = in.nextInt(); 14 } 15 for(int i=0;i<num;i++){ 16 System.out.println(arr[i]); 17 } 18 } 19 20 }