java 流程控制学习
https://www.kuangstudy.com/course
用户交互Scanner
import java.util.Scanner;
public class Demo01 {
public static void main(String[] args) {
// 创建一个扫描器对象,用于接收键盘数据
// IDEA提供了CTRL+ALT+V对该行快速根据变量类型自动生成变量.
Scanner scanner = new Scanner(System.in);
System.out.println("使用next方式接受:");
//判断用户有没有输入字符串
if(scanner.hasNext()){
// 使用next方式接受
String str=scanner.next();
System.out.println("输入的内容为:"+str);
}
// 凡是属于IO流的类如果不关闭会一直占用资源,要养成好习惯用完就关掉
scanner.close();
}
}
import java.util.Scanner;
public class Demo02 {
public static void main(String[] args) {
// 创建一个扫描器对象,用于接收键盘数据
// IDEA提供了CTRL+ALT+V对该行快速根据变量类型自动生成变量
Scanner scanner = new Scanner(System.in);
System.out.println("使用nextLine方式接受:");
//判断用户有没有输入字符串
if(scanner.hasNextLine()){
// 使用next方式接受
String str=scanner.nextLine();
System.out.println("输入的内容为:"+str);
}
// 凡是属于IO流的类如果不关闭会一直占用资源,要养成好习惯用完就关掉
scanner.close();
}
}
Scanner进阶使用
public class Demo03 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 从键盘j接收数据
int i=0;
float f=0.0f;
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();
}
}
顺序结构
选择结构
循环结构
// idea中 100.for 自动生成一个for循环语句
for (int i1 = 0; i1 < 100; i1++) {
}
public class ForDemo1 {
public static void main(String[] args) {
int[] numbers ={10,20,30};
//遍历数组的元素
for (int x:numbers){
System.out.println(x);
}
}
}
public class LabelDemo {
public static void main(String[] args) {
// 打印101-150之间所有的质数
int count=0;
// 不建议使用
outer:for (int i=101;i<150;i++){
for (int j=2;j<i/2;j++){
if (i%j==0){
continue outer;
}
}
System.out.print(i+" ");
}
}
}