Java基本的输入
使用Scanner
Scanner S=new scanner(System.in);
一.字符串输入
s.hasNext()和s.hasNextLine:判断是否有内容输入
s.next()和s.nextLine:可以用来接收内容
next():
对输入的空白,会自动消去
不能得到带有空格的字符串
一定要读取有效字符后才可以结束输入
nextLine():
以enter作为结束符,输入的是enter前所有字符包括空白
public class Circle {
public static void main(String[] args) {
//创建一个扫描对象,用于接收键盘数据
Scanner s=new Scanner(System.in);
System.out.println("shjd");
//判断用户没有输入字符串
if(s.hasNextLine()){
//使用next方法接收
String str=s.nextLine();
System.out.println("输出的内容为"+str);
}
//凡是属于IO流的类如果不关闭会一直占用资源
s.close();
}
}
二.整数
s.hasNextInt():判断是否有内容输入
s.nextInt():可以用来接收内容
public class Circle {
public static void main(String[] args) {
//创建一个扫描对象,用于接收键盘数据
Scanner s=new Scanner(System.in);
System.out.println("shjd");
//判断用户没有输入整数
if(s.hasNextLine()){
int i=s.nextInt();
System.out.println(i);
}else{
System.out.println("输入错误");
}
s.close();
}
}
三.小数
s.hasNextFloat()和s.hasNextDouble():判断是否有内容输入
s.nextFloat()和s.nextDouble():可以用来接收内容
public class Circle {
public static void main(String[] args) {
//创建一个扫描对象,用于接收键盘数据
Scanner s=new Scanner(System.in);
System.out.println("shjd");
//判断用户没有输入小数
if(s.hasNextDouble()){
int i=s.nextDouble();
System.out.println(i);
}else{
System.out.println("输入错误");
}
s.close();
}
}