1 2 3 4 5 6 7 8 9 10 11 12 | import java.util.Scanner; // 导入java.util.Scanner public class User { public static void main(String[] args) { var sc = new Scanner(System.in); //生成scanner对象 System.out.print( "请输入你的姓名:" ); String name = sc.nextLine(); //输入字符串 System.out.print( "请输入你的年龄:" ); int age = sc.nextInt(); //输入整数 System.out.println( "姓名:" + name + "\n" + "年龄:" + age); } } |
运行结果
常用的next()方法
nextInt() 输入整数
nextLine() 输入字符串
nextDouble() 输入双精度数
next() 输入字符串(以空格作为分隔符
运行结果
这种输入方法为安全输入方法,只能在cmd控制台运行,不能在IDEA、eclipse等1工具运行
创建User.java文件
1 2 3 4 5 6 7 8 9 10 | import java.io.Console; //导入java.io.Console public class User { public static void main(String[] args) { Console con = System.console(); //建立安全输入 String name = con.readLine( "请输入账号:" ); String passworld = con.readLine( "请输入密码:" ); System.out.printf( "账号:%s" , name); System.out.printf( "%n密码:%s" , passworld); } } |
cmd进入文件所在目录,运行以下指令
1 | java -Dfile.encoding=UTF-8 User.java |
运行结果
System.out.print()不换行直接输出
1 2 3 4 5 6 7 8 | public class User { public static void main(String[] args) { int a = 1 ; int b = 2 ; System.out.print(a); //print()不换行输出a的值 System.out.print(b); //print()不换行输出b的值 } } |
运行结果
12
System.out.println()换行输出
1 2 3 4 5 6 7 8 | public class User { public static void main(String[] args) { int a = 1 ; int b = 2 ; System.out.println(a); //println()换行输出a的值 System.out.println(b); //println()换行输出b的值 } } |
运行结果
1
2
System.out.printf()格式化输出
1 2 3 4 5 6 7 8 | public class User { public static void main(String[] args) { int a = 1 ; int b = 2 ; System.out.printf( "a=%d%n" ,a); //printf()格式化输出 System.out.printf( "b=%d" ,b); //printf()格式化输出 } } |
运行结果
a=1
b=2
到此这篇关于Java中输入与输出的方法总结的文章就介绍到这了,更多相关Java输入输出内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
联系客服