为什么我的代码没有运行?

时间:2015-10-05 05:04:06

标签: java if-statement

我有这段代码:

import java.util.Scanner;  

public class PositiveNegative   {    public static void main(String[] args)    {
      int numbers, plus = 0, minus = 0;
      int count = 0;
      double total = 0;

      Scanner scan = new Scanner(System.in);
      System.out.print("Enter an integer (0 to quit): ");
      numbers = scan.nextInt();

      while(numbers != 0)
      {
         total += numbers;
         if(numbers > 0)
            plus++;
         if(numbers < 0)
            minus++;   
      }
      System.out.println("The number of positives is: " +plus);
      System.out.println("The number of negatives is: " +minus);
      System.out.println("The number of total is: " +total);    
    }
}

问题在于我尝试运行它并键入数字,但它什么也没做。我想要它,这样当你输入0时它会停止数字并开始处理代码。我该怎么办?

3 个答案:

答案 0 :(得分:0)

您需要更新numbers,否则您的循环将永远运行。我建议使用大括号(和else)。像,

System.out.print("Enter an integer (0 to quit): ");
numbers = scan.nextInt();
while (numbers != 0) {
    total += numbers;
    if (numbers > 0) {
        plus++;
    } else if (numbers < 0) {
        minus++;   
    }
    System.out.print("Enter an integer (0 to quit): ");
    numbers = scan.nextInt();
}

或者,您可以使用do-while循环。然后,您只需要一份提示副本。像,

do {
    System.out.print("Enter an integer (0 to quit): ");
    numbers = scan.nextInt();
    total += numbers;
    if (numbers > 0) {
        plus++;
    } else if (numbers < 0) {
        minus++;   
    }
} while (numbers != 0);

答案 1 :(得分:0)

试试这个:

    import java.util.Scanner;

public class PositiveNegative {
    public static void main(String[] args) {
        int numbers = 0, plus = 0, minus = 0;
        double total = 0;
        do{
            Scanner scan = new Scanner(System.in);
            System.out.print("Enter an integer (0 to quit): ");
            numbers = Integer.valueOf(scan.nextLine());
            total += numbers;
            if (numbers > 0)
                plus++;
            if (numbers < 0)
                minus++;
        }
        while (numbers != 0);
        System.out.println("The number of positives is: " + plus);
        System.out.println("The number of negatives is: " + minus);
        System.out.println("The number of total is: " + total);
    }
}

将您的扫描仪置于while循环中,以便每次循环启动时都会询问用户输入。

答案 2 :(得分:0)

您每次都需要修改numbers才能使其在while中有效。

因此,在您现有的代码中,只需注释掉numbers = scan.nextInt();并使用下面的代码 -

// numbers = scan.nextInt();  //comment out this call

    while ((numbers = scan.nextInt()) != 0) {
    ....

这将为您提供所需的输出 -

Enter an integer (0 to quit): 9
4
-9
1
0
The number of positives is: 3
The number of negatives is: 1
The number of total is: 5.0