Java流程控制

Java流程控制

1、用户交互Scanner

用来实现程序和人的交互,内置的类。

可以通过scanner类来获取用户的输入。

Scanner s=new Scanner(System.in);

通过Scanner类的next()和nextLine()方法获取输入的字符串,在读取前我们一般需要使用hasNext()与hasNextLine()判断是否还有输入的数据。

package com;
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();
    }
}

使用next方式接受:
123 123
输入内容:123

Process finished with exit code 0

package com;

import java.util.Scanner;

public class Demo02 {
    public static void main(String[] args) {
        //创建一个扫描对象,用来接受键盘的输入
        Scanner scanner = new Scanner(System.in);
        System.out.println("使用nextLine方式接受:");
        //判断有没有输入
        if (scanner.hasNextLine()){
            String str=scanner.nextLine();
            System.out.println("输入内容:"+str);
        }
        scanner.close();
    }
}

使用nextLine方式接受:
123 123
输入内容:123 123

Process finished with exit code 0

看懂区别就行。

输入小数和整数

package scanner;

import sun.awt.geom.AreaOp;

import java.util.Scanner;

public class Demo03 {
    public static void main(String[] args) {
        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("输入的不是小数!");
        }

    }
}

请输入整数:
12
整数数据:12
请输入小数:
1.222
小数数据:1.222

Process finished with exit code 0
2、顺序结构
package struct;

public class ShnXu {
    public static void main(String[] args) {
        System.out.println("hello 1");
        System.out.println("hello 2");
        System.out.println("hello 3");
    }
}
3、选择结构
if单选择

if(){

}

if双选择

if(){

}

else{

}

if多选择

if(){

}

else if(){

}

else if(){

}

else{

}

switch

switch(){

case value:

​ 语句

​ break;

case value:

​ 语句

​ break;

}

4、循环结构
while循环:

while(){

}

do···while循环:

do{

}while();

for循环:

for(初始化;布尔表达式;更新){

}

print()输出不换行

printlen()输出后换行

增强for循环

遍历数组

5、break,continue(循环控制关键字)

break退出一个循环

continue退出此次循环

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值