有关读取用户输入的问题

首先导入包import java.util.Scanner;这里面有处理用户输入的方法。

输入数字情况

1
2
3
4
5
6
7
8
9
10
11
12
public static void main(String[] args) {

//创建输入对象
Scanner sc=new Scanner(System.in);

//获取用户输入的数字
System.out.print("请输入任意数字:");
int str=sc.nextInt(); //用来获取数字

System.out.println("你输入的数字为:"+str);

}

输入字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
public static void main(String[] args) {

//创建输入对象
Scanner sc=new Scanner(System.in);

//获取用户输入的字符串
String str=null;
System.out.print("请输入任意字符:");
str=sc.nextLine(); //用来获取字符串

System.out.println("你输入的字符为:"+str);

}

若要输入字符数组

思路:先用输入字符串的方法读入字符串,然后再将其转换为字符数组

mark

经过测试,一个输入对象只能接受一种数据类型,要想输入不同的数据对象,就得现创建不同的输入对象

1
2
3
4
5
6
7
Scanner in1=new Scanner(System.in);	//接受数字输入
int x1=in1.nextInt();
int x2=in1.nextInt(); //同种类型不必再new输入对象

Scanner sc2=new Scanner(System.in); //接受字符串输入,不同类型得创新new输入对象,而且不同名
String str=sc2.nextLine();
String str=sc2.nextLine();