zoukankan      html  css  js  c++  java
  • Day03_流程控制

    Day03_流程控制

    用户交互Scanner

    注意:每次使用完IO接口后都要关闭,防止一直占用。

    使用next()和nextLine()方法读取输入内容的区别:

    import java.util.Scanner;
    
    public class Demo01 {
        public static void main(String[] args) {
          //创建一个scanner对象,用于接收键盘数据
            Scanner scanner = new Scanner(System.in);
            System.out.print("用next方式输入:");
    
            //判断用户有没有输入字符串
            if(scanner.hasNext()){
                String str= scanner.next();
                System.out.println("输入的内容为:"+str);
            }
            scanner.close();
        }
    }
    

    用next方式输入:Hello World!
    输入的内容为:Hello

    import java.util.Scanner;
    
    public class Demo02 {
        public static void main(String[] args) {
            //创建一个scanner对象,用于接收键盘数据
            Scanner scanner = new Scanner(System.in);
            System.out.print("用nextLine方式输入:");
    
            //判断用户有没有输入字符串
            if (scanner.hasNextLine()) {
                String str = scanner.nextLine();
                System.out.println("输入的内容为:" + str);
            }
            scanner.close();
        }
    }
    

    用nextLine方式输入:Hello World!
    输入的内容为:Hello World!

    原因是next()方法遇到空字符值时停止读取,故只读取了Hello就停止读取了。nextLine()方法遇到回车符值时才停止读取,故读取到!后的回车键时才停止读取。

    判读输入的内容是否是int类型:scanner.hasNextInt()。判断其他数据类型,将Int替换即可。

    反编译

    将.class文件放入IEDA中查看,可以看源码。

    while语句和doWhile

    while()是不满足条件时,就不执行。

    doWhile()是即使不满足条件,也会至少执行一次。

    利用for循环打印三角形

    public class Demo03 {
        public static void main(String[] args) {
            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("");
            }
        }
    }
    
  • 相关阅读:
    (全国多校重现赛一) H Numbers
    (全国多校重现赛一)E-FFF at Valentine
    (全国多校重现赛一)B-Ch's gifts
    (全国多校重现赛一)A-Big Binary Tree
    UVA-10391 Compoud Words
    HDU-1027Ignatius and princess II
    CodeForces-501B
    UVA-136Ugly numbers
    UVA-101
    UVA-10474
  • 原文地址:https://www.cnblogs.com/gaoyao/p/13308507.html
Copyright © 2011-2022 走看看