Java, I want to know why this is happening.

Asked 2 years ago, Updated 2 years ago, 112 views

import java.util.Scanner;

public class Main {
    public static void main(String[] arg) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        sc.close();
        int A = a*2-1;
        int K = 1;
        int B = a-1;
        for(int i =1; i<=A; i++) {

            if(i<=a){
                for(int k =0; k<K; k++) {
                System.out.print("*");
            }
        }
            else {
            for(int k=0; k<B; k++) {
                System.out.print("*");
            }

        }
            B--;
            K++;
            System.out.print("\n");
        }

    }

}

//https://codeup.kr/problem.php?id=1357 The problem is that the number of stars is increasing, but the B value is decreasing and the star is decreasing, but it is not decreasing. I'd appreciate it if you could explain why.

java loops

2022-09-22 17:59

1 Answers

When input value is 5

A = 9
K = 1
B = 4
for i = 1; i <= A; i++
    if i <= 5
        for k = 0; k < K; k++
            print "*"
    else
        for k = 0, k < B, k++
            print "*"
    B--
    K++
    print "\n"

So if you look at it, B keeps decreasing from 4 and then becomes -1 when you enter else. So fork = 0, k < B, k++ doesn't work at all.

Fix the point of decreasing B.


2022-09-22 17:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.