Scanner
1. next——hasNext
next 不能获得带有空格的字符串
next 不能获得带有空格的字符串
next 不能获得带有空格的字符串
//代码
import java.util.Scanner;
public class next {
public static void main(String[] args) {
Scanner hhh = new Scanner(System.in); /* 开始 */
System.out.println("使用 next 进行接收:");
//判断用户有没有输入字符串
if (hhh.hasNext())
{
//用 next 方法进行接收
String str = hhh.next();
System.out.println("输出内容为"+str);
}
//关闭scanner
hhh.close(); /* 结束 */
}
}
// 截图
2. nextLine——hasNextLine
nextLine 可以获得带有空格的字符串 (回车结束)
nextLine 可以获得带有空格的字符串 (回车结束)
nextLine 可以获得带有空格的字符串 (回车结束)
// 代码
import java.util.Scanner;
public class nextLine {
public static void main(String[] args) {
// 从键盘接收数据
Scanner hhh1 = new Scanner (System.in); /* 开始 */
System.out.println("使用 nextLine 进行接收:");
// 判断是否还有输入
if (hhh1.hasNextLine())
{
String str = hhh1.nextLine();
System.out.println("输出内容为:"+str);
}
hhh1.close(); /* 结束 */
}
}
// 截图
3. nextInt—nexFloat—nexDouble…
// ctrl + 双击要进入的类 , 可以进入库(源码)
// ctrl + 双击要进入的类 , 可以进入库(源码)
// ctrl + 双击要进入的类 , 可以进入库(源码)
// nex+类型 ,只会与类型相同时才会执行语句,例如 : i = hhh2.nextInt(); 只能给 i 赋值整数,如果不是整数,执行不了!!!
// nex+类型 ,只会与类型相同时才会执行语句,例如 : i = hhh2.nextInt(); 只能给 i 赋值整数,如果不是整数,执行不了!!!
//代码
import java.util.Scanner;
public class nextInt {
public static void main(String[] args) {
int i = 0 ;
float f = 0.0f;
Scanner hhh2 = new Scanner (System.in); // ctrl + 双击要进入的类 , 可以进入库(源码)
System.out.println("请输入字符:");
if(hhh2.hasNextInt())
{
i = hhh2.nextInt();
System.out.println(" 整数数据 "+i);
}else
System.out.println("输入的数据不是整数");
System.out.println("请输入小数");
if(hhh2.hasNextFloat())
{
f = hhh2.nextFloat();
System.out.println(" 小数数据 "+f);
}else
System.out.println("输入的数据不是小数");
hhh2.close();
}
}
// 截图
4. 例题
题目:我们可以输入多个数字 ,并求其总数及平均值 ,每输入一个数字回车结束 ,通过非数字输入结束并输出结果
import java.util.Scanner;
public class example {
// 我们可以输入多个数字 ,并求其总数及平均值 ,每输入一个数字回车结束 ,通过非数字输入结束并输出结果
public static void main(String[] args) {
Scanner hhh3 = new Scanner(System.in);
System.out.println("请输入数字:");
double sum = 0;
int m = 0; /* 输入的个数 */
while (hhh3.hasNextDouble())
{
double str = hhh3.nextDouble();
sum += str;
m++;
System.out.println("当前为第"+m+"个数,当前的和为"+sum);
}
System.out.println("和为:"+sum);
System.out.println("平均值为"+(sum/m));
hhh3.close();
}
}
// 截图