简体   繁体   中英

Java: changing the order of lines with while-loop

I am new to programming and I would like to ask what should I do so that the final value of k will appear before the values of a, when I try to put it inside the loop it repeats the statement and when I put it before the loop, its value is 0.

    System.out.printf("Input an integer: ");
    int a = in.nextInt();
    int k = 0;
    
    System.out.print(a);
    while(a > 1)
    {
        if(a % 2 == 0)
            a = a / 2;
        else
            a = 3 * a + 1;
        System.out.printf(", " + a);
        k++;
    }
    System.out.println("\nk = " + k);


    Output:
    Input an integer: 10
    10, 5, 16, 8, 4, 2, 1
    k = 6

You could try:

    System.out.printf("Input an integer: ");
    int a = in.nextInt();
    int k = 0;
    String str_a = "";
    
    System.out.print(a);
    while(a > 1)
    {
        if(a % 2 == 0)
            a = a / 2;
        else
            a = 3 * a + 1;
        str_a += ", " + String.valueOf(a);
        k++;
    }
    System.out.println("k = " + k);
    System.out.println("a = " + str_a);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM