打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
java 流程控制学习


用户交互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+" ");

        }

    }
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
java基础习题(一)
Java程序设计总复习题
JAVA经典算法50题(4)【面试+工作】
Java基础语句
Scanner常用的方法
弄清楚next(),nextLine(),nextInt()
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服