简体   繁体   English

Java:用while循环改变行的顺序

[英]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.我是编程新手,我想问一下我应该怎么做才能使 k 的最终值出现在 a 的值之前,当我尝试将其放入循环中时,它会重复该语句,而当我将其放在 a 的值之前时循环,其值为 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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