首页 > 编程语言 >Java流程控制

Java流程控制

时间:2023-02-17 11:34:32浏览次数:34  
标签:控制 Java scanner int 流程 System println public out

流程控制

用户交互Scanner(java5新特性)

通过Scanner类来获取用户的输入

基本语法:Scanner s = new Scannner(System.in);

方法:

  • next() 获取输入字符串
  • nextLine() 获取输入字符串
  • hasNest() 是否有下一个输入数据
  • hasNestLine() 是否有下一行输入数据

next():

  1. 一定要读取到有效字符后才可以结束输入。
  2. 对输入有效字符之前遇到的空白,next() 方法会自动将其去掉。
  3. 只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。
  4. next()不能得到带有空格的字符串。

nextLine():

  1. 以Enter为结束符,也就是说nextLine()方法返回的是输入回车之前的所有字符。
  2. 可以获得空白。
package com.ll.parse1;

import java.util.Scanner;

public class Demo {
    public static void main(String[] args) {
        //创建一个扫描器对象,用来接受键盘数据
        Scanner scanner = new Scanner(System.in);

        System.out.println("使用next方法接受:");//输入hello word

        //判断用户有没有输入字符串
        if (scanner.hasNext()){
            //使用next方式来接受
            String str = scanner.next();//程序会等待用户输入完毕
            System.out.println("输入的内容为:"+str);//hello 
        }

        //凡是属于IO流的类如果不关闭会一直占用资源,所以需要关掉
        scanner.close();
    }
}

package com.ll.parse1;

import java.util.Scanner;

public class Demo {
    public static void main(String[] args) {
        //创建一个扫描器对象,用来接受键盘数据
        Scanner scanner = new Scanner(System.in);

        System.out.println("使用nextLine方法接受:");//输入hello word

        //判断用户有没有输入字符串
        if (scanner.hasNextLine()){
            //使用next方式来接受
            String str = scanner.nextLine();//程序会等待用户输入完毕
            System.out.println("输入的内容为:"+str);//hello word
        }

        //凡是属于IO流的类如果不关闭会一直占用资源,所以需要关掉
        scanner.close();
    }
}

scanner进阶使用
  //创建一个扫描器对象,用来接受键盘数据
        Scanner scanner = new Scanner(System.in);

        //从键盘接受数据
        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("输入的不是小数数据");
        }

        //凡是属于IO流的类如果不关闭会一直占用资源,所以需要关掉
        scanner.close();
package com.ll.parse1;

import java.util.Scanner;

public class Demo {
    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 = m+1;//输入了多少个数字
            //求和
            sum = sum + x;
        }
        //求平均数
        double v = (sum / m) + (sum % m);
        System.out.println("个数的和:"+sum);
        System.out.println("个数的平均值:"+v);
        scanner.close();

    }
}

顺序结构

基本算法结构

选择结构

if选择结构
equals("")//判断字符串

if单选择结构:

if(布尔表达式){
	//如果布尔表达式为true时执行的代码块
}

if双选择结构

if(布尔表达式){
	//如果布尔表达式为true时执行的代码块
}else{
    //如果布尔表达式为false时执行的代码块
}

if多选择结构

  • if语句中至多只有一个else
  • else if必须在else之前
  • 其中一个else if为true ,其他的else if和else都将跳过执行
if(布尔表达式 1){
	//如果布尔表达式 1为true时执行的代码块
}else if(布尔表达式 2){
	//如果布尔表达式 2为true时执行的代码块
}else if(布尔表达式 3){
	//如果布尔表达式 3为true时执行的代码块
}else{
    //如果以上布尔表达式都不为true时执行的代码块
}
package com.ll.parse1;

import java.util.Scanner;

public class Demo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("请输入成绩:");
        int score = scanner.nextInt();

        if (score == 100){
            System.out.println("恭喜满分");
        }else if (score<100 && score>=90){
            System.out.println("A级");
        }else if (score<90 && score>=80){
            System.out.println("B级");
        }else if (score<80 && score>=70){
            System.out.println("C级");
        }else if (score<70 && score>=60){
            System.out.println("D级");
        }else if (score<60 && score>=0){
            System.out.println("不及格");
        }else {
            System.out.println("成绩不合法");
        }

        scanner.close();
    }
}

嵌套的if结构

if(布尔表达式 1){
    //入股布尔表达式 1的值为true执行的代码
    if(布尔表达式 2){
        //入股布尔表达式 2的值为true执行的代码
    }
}
switch选择结构

语句中的变量类型可以时byte\short\int\char,在Java SE7开始支持String类型了,其中case标签必须为字符串常量或者字面量

switch(expression){
    case value:
        //语句
        break;//可选
    case value:
        //语句
        break;//可选
    defalut://可选
        //语句
}
package com.ll.parse1;


public class Demo {
    public static void main(String[] args) {
        //case 穿透   switch就是匹配一个具体值
        char grade = 'C';
        //反编译,可以通过(IDEA)反编译查看生成的源码时什么样子
        switch (grade){
            case 'A':
                System.out.println("优秀");
                break;
            case 'B':
                System.out.println("良好");
                break;
            case 'C':
                System.out.println("及格");
                break;
            case 'D':
                System.out.println("再接再厉");
                break;
            case 'E':
                System.out.println("挂科");
                break;
            default:
                System.out.println("未知等级");
        }
    }
}

反编译(IDEA)
  1. 点击IDEA中的File->Project Settings->Project
  2. 在Project compiler output中查看反编译之后的文件的位置

循环结构

while循环

只要布尔表达式为true就会一直,循环下去;我们一般需要一个让表达式失效的方法,来结束循环

少部分情况下需要循环一直执行比如服务器的请求相应监听等

循环条件一直为true就会造成无限循环(死循环)

while(布尔表达式){
    //循环内容
}
public class Demo {
    public static void main(String[] args) {
       //输出1-100
        int i = 0;
        //先判断布尔表达式
        while (i < 100){
            i++;
            System.out.println(i);
        }
    }
}
public class Demo {
    public static void main(String[] args) {
       //计算1+2+3····+100=?
        int i = 0;
        int sum = 0;
        while (i <= 100){
            sum = sum+i;
            i++;
        }
        System.out.println(sum);
    }
}
do....while循环

即使布尔表达式不为true,也会执行一次代码语句

do{
    //代码语句
}while(布尔表达式)
public class Demo {
    public static void main(String[] args) {
       int i = 0;
       int sum = 0;
       do {
           sum = sum +i;
           i++;
       }while(i<=100);
        System.out.println(sum);
    }
}
while与do····while的区别
  1. while是先判断在循环,do···while是先循环在判断
  2. do···while总是保证循环体至少被执行一次
public class Demo {
    public static void main(String[] args) {
       int a = 0;

        while (a < 0) {
            a++;
            System.out.println(a);
        }
        System.out.println("======================");
       do {
           System.out.println(a);
           a++;
       }while(a<0);

    }
}
for循环

使支持迭代的一种通用结构

是最有效、最灵活的循环结构

可以使一些循环结构变得更加简单,循环的次数在执行前就确定了

  • 最先执行初始化步骤,可以声明一种类型,可以初始化一个或者多个循环控制变量,也可以是空语句
  • 执行一次循环后,会更新循环控制变量(迭代因子控制循环变量的增减)
  • 再次检查布尔表达式,循环执行上面的过程
for(初始值;布尔表达式;更新){
	//代码语句
}
public class Demo {
    public static void main(String[] args) {
        int a = 1; //初始化条件

        while(a<=20){//判断条件
            System.out.println(a);//循环体
            a+=2;//迭代
        }
        System.out.println("while循环结束!");

        //初始化  //条件判断 //迭代
        for (int i = 1;i<=20;i++){
            System.out.println(i);
        }

        System.out.println("for循环结束");

    }
}

//for的死循环
for(;;){
    //代码语块
}
练习1:0-100的奇数和偶数的和
public class Demo {
    public static void main(String[] args) {
       //0-100的奇数和偶数的和
        int oddSum = 0;//奇数和
        int evenSum = 0;//偶数和


        for (int i = 0; i <= 100; i++) {
            if (i%2!=0){//奇数
                oddSum+=i;//oddSum = oddSum + i
            }else {//偶数
                evenSum+=i;
            }
        }
        System.out.println("奇数和是:"+oddSum);//2500
        System.out.println("偶数和是:"+evenSum);//2550

    }
}
练习2:用while或者for循环输出1-1000之间能被5整除的数,并每行输出3个
public class Demo {
    public static void main(String[] args) {
        //练习2:用while或者for循环输出1-1000之间能被5整除的数,并每行输出3个
        for (int i = 0; i <= 1000; i++) {
            if (i%5==0){
                System.out.print(i+"\t");
            }
            if (i%(5*3)==0){//每行
                System.out.println();
                //System.out.print("\n");
            }
        }
        //println 输出完会换行
        //print  输出完不会换行
    }
}
练习3:打印九九乘法表
public class Demo {
    public static void main(String[] args) {
        //练习3:打印九九乘法表
        //1.先打印第一列
        //2.我们把固定的1再用一个循环包起来
        //3.去掉重复项,j<=i
        //4.调整样式
        int sum = 0;
        for (int i = 1; i <= 9; i++) {
            for (int j = 1; j <= i; j++) {
                sum = i*j;
                System.out.print(j+"*"+i+"="+sum+"\t");
            }
            System.out.println();
        }
    }
}
增强for循环

主要用于数组和集合的

  • 声明语句:声明新的局部变量,该变量的类型必须和数组元素类型匹配。其作用域限定在循环语句块,其值与此时数组元素的值相等。
  • 表达式:表达式是要访问的数组名,或者是返回值为数组的方法。
for(声明语句:表达式){
    //代码语句
}
public class Demo {
    public static void main(String[] args) {
        int[] numbers = {10,20,30,40,50};//定义一个数组
        //遍历数组的元素
        for (int i = 0; i <5; i++) {
            System.out.println(numbers[i]);
        }
        System.out.println("================");
        //遍历数组的元素
        for (int x:numbers){
            System.out.println(x);
        }
    }
}

break&continue

break

用于强制退出循环,不执行循环中剩余的语句(break语句也在switch语句中使用)

continue

用于终止某次循环过程,即跳出循环体中尚未执行的语句,接着进行下一次是否执行循环的判定

goto关键字(不建议使用)

goto关键字很早就在程序设计语言中出现。尽管goto仍是Java的- 个保留字,但并未在语言中得到正式使用; Java没有goto。然而,在break和continue这两个关键字的身.上,我们仍然能看出一些goto的影子---带标签的break和continue。

  • "标签"是指后面跟一一个冒号的标识符,例如: label:
  • 对Java来说唯一用到标签的地方是在循环语句之前。而在循环之前设置标签的唯一理由是:我们希望在其中嵌套另一个循环,由于break和continue关键字通常只中断当前循环,但若随同标签使用,它们就会中断到存在标签的地方。
public class Demo {
    public static void main(String[] args) {
        //打印101-150之间所有的质数
        //质数:大于1的自然数中,除了1和它本身以外不在有其他因数的自然数
        int count = 0;
        //不建议使用
        outer:for (int i = 101; i < 150; i++) {
            //i/2就是小于它的倍数
            for (int j = 2;j<i/2;j++){
                if (i%j==0){
                    continue outer;
                }
            }
            System.out.print(i+" ");
        }
    }
}

流程控制的练习

public class Demo {
    public static void main(String[] args) {
        //打印三角形  5行

        for (int i = 1; i <= 5; i++) {
            for (int j = 5; j >=i ; j--) {
                System.out.print(" ");
            }
            for (int j = 1; j <=i ; j++) {
                System.out.print("*");
            }
            for (int j = 1; j <i ; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

标签:控制,Java,scanner,int,流程,System,println,public,out
From: https://www.cnblogs.com/ayyo/p/17129512.html

相关文章

  • jenkins 流水线构建发布流程
    jenkins流水线构建发布流程:1.输入一个任务名称:xxx.xxxx.WebApi.prod2.选择-》pipeline3.流水线:pipelinescriptfromSCM4.SCM--Subversion5.RepositoryURL:http://......
  • Create port ip分配流程梳理
    Createportip分配流程梳理self.ipam.allocate_ips_for_port_and_store(context,port,port_id)#/usr/lib/python2.7/site-packages/neutron/db/ipam_pluggable_......
  • Java-
    mvnpackage-DskipTests报错:[INFO]BUILDFAILURE[INFO]------------------------------------------------------------------------[INFO]Totaltime:5.311s[INF......
  • Windows 10 无网络的情况下手动升级补丁的流程和方法:
    Windows10无网络的情况下手动升级补丁的流程和方法:从微软官网下载需要的更新补丁;将下载的更新补丁保存到本地;打开“设置”,点击“更新和安全”;点击“查看可用更新”,......
  • 【tomcat启动报类找不到】java.lang.NoSuchMethodError org.springframework.util.Ref
    springboot项目打成war包,放tomcat里启动报错:java.lang.NoSuchMethodErrororg.springframework.util.ReflectionUtils.accessibleConstructor(Ljava/lang/Class;[Ljava/la......
  • [javascript]端序(endian)和Buffer对象的read|write系列函数
    假设有如下对象:varbuf=Buffer.from("Hello.\n");其保存在内存当中的形式实际上是这样的,这里我们假设该对象的内存地址从0x00开始:地址0x000x010x020x030x04......
  • 2023前端开发最新面试题收集-Javascript篇
    前台、中台、后台-前台:面向用户、客户可以感知的,如商城-中台:可以看着对前台的补充,公共服务功能,如支付系统、搜索系统、客服-后台:面向运营、比如商品管理、物流管理1......
  • Java线程基础
    线程的创建Java线程可以通过实现Runnable接口、Callable接口或继承Thread类进行创建。实现Runnable接口实例可以使用Runnable接口实现多线程,Runnable接口实现类必须实现......
  • 使用alert卡住electron界面,打开调试控制台
    思路主要的思路是在electron的app.asar解包后,在主页面的html中加入js脚本alert,再重新打包,打开程序卡住界面,在按enter键的同时,按ctrl+shift+i,打开控制台案例说明观......
  • Java 文件上传
    一:配置springBoot上传文件限制spring:servlet:multipart:max-file-size:100MB#单个文件大小max-request-size:1024MB#总文件大小二:代码i......