简体   繁体   English

没有输入正数时如何显示正确的输出

[英]how do I display the correct output when no positve numbers are entered

I'm new to coding.我是编码新手。 Assignment is to calculate the average of all the positive numbers input and exit when a zero is input.赋值是计算所有输入的正数的平均值,当输入一个零时退出。 If no positive numbers are input display a message average not possible.如果没有输入正数,则显示消息平均不可能。

The following is what I have so far.以下是我到目前为止所拥有的。 I am stuck on the part about printing out the message "cannot calculate the average" when only a zero or negative numbers are input.当仅输入零或负数时,我坚持打印“无法计算平均值”的消息。

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int numbers = 0;
    int sumOfNumbers = 0;
    double averagePositive = 0;
    while (true) {
        System.out.println("Give a number: ");
        int number = Integer.valueOf(scanner.nextLine());
        if (number == 0)
            break;

        if (number > 0)
            sumOfNumbers = number + sumOfNumbers;

        if (number > 0)
            numbers = numbers + 1;

        if (number > 0)
            averagePositive = (double)sumOfNumbers / (double)numbers;
    }   
    System.out.println(averagePositive);
}

Try it as follows...尝试如下...

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

    System.out.print("Give a number: ");
    int num=input.nextInt();
    int tot=0; //total
    int count=0; // counting the positive numbers
    if(num>0){
         while(num!=0){
             tot+=num;
             count++;
             System.out.print("Give a number: ");
             num=input.nextInt();
             if(num<0){
              System.out.print("Not possible");
              return;
              }
         }
         double avg =(double)tot/n;
         System.out.print("Average: "+avg);

    }else{
         System.out.println("Cannot calculate the average.");
    }

}

I'd probably do it like this to keep it simple.我可能会这样做以保持简单。 Also in general, try not to cramp code together.此外,一般来说,尽量不要将代码挤在一起。 Most formal project demand a certain degree of styling and usually spaces between operators and braces, etc... is required.大多数正式项目需要一定程度的样式,并且通常需要运算符和大括号等之间的空格。 In the long run it makes the code more readable and easier to maintain.从长远来看,它使代码更具可读性和更易于维护。

In your code there was no need to repeat the same if test for number > 0 multiple times, they could have all been bundled together.在您的代码中,如果多次测试 number > 0,则无需重复相同的操作,它们可以全部捆绑在一起。 If the program was bigger and more complex I may have named the variable names with more qualification but for a short program like this, brief names were sufficient for clarity.如果程序更大更复杂,我可能会用更多限定条件命名变量名,但对于像这样的短程序,简短的名称就足够清晰了。

continue and break are important keywords to control loop behavior and can be used to increase brevity and clarity. continuebreak是控制循环行为的重要关键字,可用于提高简洁性和清晰度。 continue goes back to the top of the loop immediately and break exits the innermost loop immediately. continue立即返回到循环的顶部,而break立即退出最内层的循环。 Dividing a double by an int yields a double so I was able to eliminate a cast.double除以int产生double因此我能够消除强制转换。 And the += operator makes it a little easier to read the line. +=运算符使阅读该行变得更容易一些。

Also in Java and C any if() or else clause that contains one line doesn't require braces and unless a program is nested in such a way that adding the braces anyway adds to the clarity, it is often clearer to omit the braces in that case.同样在 Java 和 C 中,任何包含一行的if()else子句都不需要大括号,除非程序以这样一种方式嵌套,即无论如何添加大括号都会增加清晰度,否则省略大括号通常更清晰那种情况。 The if statement illustrates both ways in a single statement. if语句在一个语句中说明了两种方式。

import java.util.Scanner;
public class avg 
{
    static int count = 0;
    static double sum = 0;

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("\nEnter a sequence of positive numbers (0 to calculate average):\n");

        while (true) {
            System.out.print("Number? ");
            int n = scanner.nextInt();
            if (n < 0) {
                System.out.println("Negative numbers not allowed.");
                continue;
            } else if (n == 0)
                break;

            sum += (double)n;
            ++count;
        }           

        System.out.println("Average of " + count + " numbers = " + 
            (double)(sum / count) + "\n");


        System.exit(1);
    }
}

Sample output:示例输出:

$ java avg

    Enter a sequence of positive numbers (0 to calculate average)

    Number? 1
    Number? 2
    Number? 3
    Number? 4
    Number? 5
    Number? -6
    Negative numbers not allowed.
    Number? 0

    Average of 5 numbers = 3.0

I'm new to coding.我是编码新手。 Assignment is to calculate the average of all the positive numbers input and exit when a zero is input.分配是计算输入的所有正数的平均值,当输入零时退出。 If no positive numbers are input display a message average not possible.如果没有输入正数,则显示消息平均值。

The following is what I have so far.以下是我到目前为止的内容。 I am stuck on the part about printing out the message "cannot calculate the average" when only a zero or negative numbers are input.我只停留在输入零或负数时打印出“无法计算平均值”消息的部分。

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int numbers = 0;
    int sumOfNumbers = 0;
    double averagePositive = 0;
    while (true) {
        System.out.println("Give a number: ");
        int number = Integer.valueOf(scanner.nextLine());
        if (number == 0)
            break;

        if (number > 0)
            sumOfNumbers = number + sumOfNumbers;

        if (number > 0)
            numbers = numbers + 1;

        if (number > 0)
            averagePositive = (double)sumOfNumbers / (double)numbers;
    }   
    System.out.println(averagePositive);
}

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

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