java的输入 Scanner
由于java是强类型语言且所有操作都是关于对象的,所以java的输入相较于Python和c还有很大的区别
话不多说,上代码解析
public class Practice {
public static void main(String[] args) {
// 创建一个Scanner对象,其中的next方法和nextLine方法都可以接收输入
// 其中input为对象的对象名
Scanner input = new Scanner(System.in); // 可以使用alt+Enter快速填充
System.out.println("请输入内容:");
// 使用str来接收输入的字符串
String str = input.next();
// 输出字符串
System.out.println(str);
// 凡是属于IO流(输入输出流)的类如果不关闭会一直占用资源, 养成好习惯用完关闭
input.close();
}
}
这里我们输入hello world但是输出的是hello而不是hello world,原因是next遇到空格就会停止接收了
那这里怎么才能使用hello world完整输出呢,用.nextLine方法就可以了
public class Practice {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入内容:");
String str = input.nextLine();
System.out.println(str);
//记得关闭,养成好习惯
input.close();
}
}
-
整数类型的输入
其实整数类型的输入也就是把接受的类型换成int,对象名的方法改成nextInt就行了
public class Practice { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("请输入内容:"); // 如果输入的不是int类型的会报错哦, 当然也可以使用if(input.hasNextInt)来规避报错 int i = input.nextInt(); System.out.println(i); // 还是老样子,记得关闭,养成好习惯 input.close(); } } -
浮点数类型的输入
与上面类似,就是改成input.nextFloat就行
后记
可能有点啰嗦,但是希望大家能学到点东西,有出现问题欢迎找我说明,感激不尽!

浙公网安备 33010602011771号