Java流程控制
1.用户交互Scanner
- next()不能得到带有空格的字符串,空格后字符串自动去除
package com.zhang.scanner;
import java.util.Scanner;
public class Demo01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);//创建一个扫描对象,用于接收键盘数据
System.out.println("使用next方式接受:");
if(scanner.hasNext()){ //判断用户有没有输入字符串
String str = scanner.next(); //程序会等待用户输入完毕
System.out.println("输出的内容为:"+str);
}
scanner.close();
}
}
输入:我爱你 输出:我爱你 输入:我爱 你 输出:我爱
- nextLine()以Enter为结束符
package com.zhang.scanner;
import java.util.Scanner;
public class Demo01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("使用next方式接受:");
String str = scanner.nextLine();
System.out.println("输出的内容为:"+str);
scanner.close();
}
}
- 案例
package com.zhang.scanner;
import java.util.Scanner;
public class Demo02 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double sum = 0;
int m = 0;
while(scanner.hasNextDouble()){
double x = scanner.nextDouble();
m++;
sum+=x;
System.out.println("你输入了第"+m+"个数据,然后当前结果sum="+sum);
}
System.out.println(m+"个数的和为"+sum);
System.out.println(m+"个数的平均值是"+(sum/m));
scanner.close();
}
}
2.增强for循环
int[] numbers={10,20,30,40,50};
for(int x:numbers){
System.out.println(x);
} //10,20,30,40,50
标签:控制,Java,scanner,流程,System,println,out,sum,Scanner
From: https://www.cnblogs.com/rockz/p/17150745.html