如何在Java的while循环中将变量初始化回0?

时间:2019-01-30 02:36:03

标签: java

我希望我的代码循环,但将变量重新初始化为0。每次输入数字时,它将其添加到先前的结果中,但我希望将其重置。我在下面附加了两张图片。一个是实际输出,另一个是预期输出。

import java.util.Scanner;

public class AddOrMultiplyNNumbers {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    String am;
    int sum = 0;
    int total = 1;
    int n = 0;

    while (true) {

        System.out.print("enter an integer number: ");
        n = input.nextInt();
        if(n == 0) {
            break; 
        }
        System.out.print("enter either 'a' or 'm': ");
        input.nextLine();
        am = input.nextLine();
        if (am.equals("a")) {
            for (int y = 1; y <= n; y++) {
                sum = sum + y;
            }
            System.out.println(sum);
        } else if (am.equals("m")) {
            for (int x = 1; x <= n; x++) {
                total = total * x;
            }
            System.out.println(total);
        }
      }
   }
} 

实际输出

Actual Output

所需的输出

Desired Input

4 个答案:

答案 0 :(得分:2)

您可以使用continue

if(n == 0) {
    sum = 0;
    total = 1;
    continue; 
}

答案 1 :(得分:0)

我不知道我是否完全理解您的问题,但只求sum = 0;总计= 1;在您打印出最终结果之后。您还应该考虑在nextInt上执行try / catch语句,以确保其健壮性,以便字符和字符串不会破坏您的程序...

try {
    n = input.nextInt();
}
catch (Exception e) {
    System.out.println("Not a Number");
}

答案 2 :(得分:0)

您可以在while循环中初始化变量

public class AddOrMultiplyNNumbers {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    String am;

    while (true) {

        int sum = 0;
        int total = 1;
        int n = 0;

        System.out.print("enter an integer number: ");
        n = input.nextInt();
        if(n == 0) {
            break; 
        }
        System.out.print("enter either 'a' or 'm': ");
        input.nextLine();
        am = input.nextLine();
        if (am.equals("a")) {
            for (int y = 1; y <= n; y++) {
                sum = sum + y;
            }
            System.out.println(sum);
        } else if (am.equals("m")) {
            for (int x = 1; x <= n; x++) {
                total = total * x;
            }
            System.out.println(total);
        }
      }
   }
} 

答案 3 :(得分:0)

要将变量清零,只需在适当的位置分配0

sum = 0;

在第一个for循环之前紧接为您所需的输出插入此语句的适当位置。同样,在第二个total之前重置for

但是,一种更好的编写方式是像在xy中所做的那样,在需要的位置声明变量。这适用于amsumtotaln

Scanner input = new Scanner(System.in);

while (true) {
    System.out.print("enter an integer number: ");
    int n = input.nextInt();
    if (n == 0) {
        break; 
    }
    System.out.print("enter either 'a' or 'm': ");
    input.nextLine();
    String am = input.nextLine();
    if (am.equals("a")) {
        int sum = 0;
        for (int y = 1; y <= n; y++) {
            sum = sum + y;
        }
        System.out.println(sum);
    } else if (am.equals("m")) {
        int total = 1;
        for (int x = 1; x <= n; x++) {
            total = total * x;
        }
        System.out.println(total);
    }
  }
相关问题