本文共 2952 字,大约阅读时间需要 9 分钟。
Java提供了一个工具类, 我们可以获取用户的输入. Java.util.Scanner 是Java5的新特征, 我们可以通过Scanner类来获取用户的输入
Scanner s = new Scanner (System.in);
通过Scanner类的next() 与nextLine() 方法获取输入的字符串, 在读取前我们一般需要使用hasNext() 与hasNextLine() 判断是否还有输入的数据
next和hasNext的使用:
package com.Flonx.Practice;import java.util.Scanner;public class Practice { public static void main(String[] args) { //create a scanner object , to receive the data from keyboard Scanner scanner = new Scanner (System.in); //out---output, in--input System.out.println("receive content by the way of 'next': "); //judge whether the string is input or not by users if (scanner.hasNext()){ //receive the input by user String str = scanner.next(); System.out.println("the input content is : " + str); } //凡是属于IO流的类如果不关闭会一直占用资源, 要养成好习惯用完就关掉 scanner.close(); }}
package com.Flonx.Practice;import java.util.Scanner;public class Practice { public static void main(String[] args) { Scanner scanner = new Scanner (System.in); System.out.println("receive content by the way of 'next': "); if (scanner.hasNextLine()){ String str = scanner.nextLine(); System.out.println("the input content is :" + str); } scanner.close(); }}
package com.Flonx.Practice;import java.util.Scanner;public class Practice { public static void main(String[] args) { int i = 0; float f = 1.0F; Scanner scanner = new Scanner(System.in); System.out.println("请输入一个整数: "); if (scanner.hasNextInt()){ i = scanner.nextInt(); System.out.println("整数:" + i); } else{ System.out.println("输入的不是整数"); } System.out.println("请输入一个小数: "); if (scanner.hasNextFloat()){ f = scanner.nextFloat(); System.out.println("小数:"+f); } else{ System.out.println("输入的不是小数"); } scanner.close(); }}/*请输入一个整数: 10整数:10请输入一个小数: 1.1小数:1.1 */
package com.Flonx.Practice;import java.util.Scanner;public class Practice{ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int count = 0; double sum = 0; System.out.println("请输入数: "); while (scanner.hasNextDouble()){ sum += scanner.nextDouble(); count ++; System.out.println("输入第" + count + "个数字, 总数为:" + sum ); } System.out.println("总数为: "+ sum); System.out.println("平均数为: "+ (sum / count)); scanner.close(); }}
转载地址:http://rpvzb.baihongyu.com/