没有在循环中打印某些元素

时间:2019-02-11 01:13:26

标签: java

所以我有以下代码:

public class MyClass {
    public static void main(String args[]) {
        Scanner reader = new Scanner(System.in);

        System.out.println("Enter the upper limit: ");
        int input = reader.nextInt();

        int i = 0;
        int power = 1;
        long sum;

        while (i <= input) {
            System.out.print(power + " + ");
            sum = power + power;
            power = power * 2;
            i++;

            if (power > input) {
                System.out.print(" = " + sum);
                System.exit(0);
            }
        }
    }
}

假设用户输入了500。

输出为:

1 + 2 + 4 + 8 + 16 + 64 + 128 + 256 + = 512

我想摆脱最后一个“ +”,所以它看起来像一个实际的方程式。

4 个答案:

答案 0 :(得分:1)

您可以在循环外打印和递增power,然后反转打印顺序:

System.out.print(power++);
while (i <= input)
{

   System.out.print(" + " + power );
   //...
}

哪个会输出:

Enter the upper limit: 
500
1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 + 256 = 51

答案 1 :(得分:1)

只需在else语句中添加打印 std::cout << typeid( static_cast<void (*)(A)>(f) ).name() << std::endl;

+

输出

 Scanner reader = new Scanner(System.in);

    System.out.println("Enter the upper limit: ");
    int input = reader.nextInt();

    int i = 0;
    int power = 1;
    long sum;

    while (i <= input) {
        System.out.print(power);
        sum = power + power;
        power = power * 2;
        i++;

        if (power > input) {
            System.out.print(" = " + sum);
            System.exit(0);
        }else {
            System.out.print(" + ");
        }
    }

答案 2 :(得分:0)

生成您的字符串,然后将其切掉,而不是打印出来。我更改了while循环,因此它确实做到了:

...
StringBuilder powerLine = new StringBuilder();
while (i <= input) {

    powerLine.append(power + " + ");
    //System.out.print(power + " + ");

    sum = power + power;
    power = power * 2;

    i++;

    if (power > input) {
        System.out.print(powerLine.substring(0, powerLine.length() - 3));
        System.out.print(" = " + sum);
        System.exit(0);
    }
}

答案 3 :(得分:0)

只需像下面那样更改行

  

System.out.print(power +(power * 2 <= input?“ +”:“”));