Day13 FlowControl Practise

FlowControl Practise

打印三角形

将三角形用矩形锁住,分成四部分

1.倒三角空白部分

2.正三角符号部分

import java.util.Scanner;

public class Practise01 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Scanner scanner1=new Scanner(System.in);
        int a=scanner.nextInt();//输入三角形的行数
        String q=scanner1.nextLine();
        String w=scanner1.nextLine();
        for (int b=1;b<=a;b++){
            for (int c=a;c>=b;c--){
                System.out.print(" ");
            }//获得空白倒三角形
            for (int d=1;d<=b;d++){
                System.out.print(q);
            }//获得字符左半边三角形
            for (int e=1;e<b;e++){
                System.out.print(w);
            }//获得字符右半边三角形
            System.out.println();
        }
    }
}

BUG:Scanner中nextLine()在nextInt()的几种解决方式

原因

  • java中next().nextInt().nextDouble().和nextFloat()方法的回车会被nextLine()识别输入
  • 会出现nextLine()为空的值
import java.util.Scanner;

public class Practise01 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int a=scanner.nextInt();
        String q=scanner.nextLine();
        String w=scanner.nextLine();

  • 即会导致q的值为空白值

解决办法

  • 直接重新new一个Scanner1;如上图打印三角形的代码
import java.util.Scanner;

public class Practise01 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Scanner scanner1=new Scanner(System.in);
        int a=scanner.nextInt();
        String q=scanner1.nextLine();
        String w=scanner1.nextLine();
  • 多放置一个nextLine()来进行接收空白
import java.util.Scanner;

public class Practise01 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int a=scanner.nextInt();
        scanner.nextLine();//多放置一个nextLine()来进行接收空白
        String q=scanner.nextLine();
        String w=scanner.nextLine();
  • 输入字符串-通过方程Integer.parseInt将字符串变成int

​ (因为本身字符串的nextLine()是不会输出空白的)

import java.util.Scanner;
public class Practise02 {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            String a=scanner.nextLine();//输入行数
            int aa=Integer.parseInt(a);//转换行数为int类型
            String q=scanner.nextLine();
            String w=scanner.nextLine();

Debug

  • 可以通过点击看清楚每一步代码是如何运行
posted @ 2021-09-25 13:59  Hacker-红烧肉  阅读(29)  评论(0)    收藏  举报