简体   繁体   English

满足特定条件时添加消息(Java)

[英]Adding message when certain condition is met (Java)

Total newbie here, please forgive the silly question. 这里有新手,请原谅这个愚蠢的问题。 As an exercise I had to make a program (using do and while loops) that calculates the average of the numbers typed in and exits when the user types 0. I figured the first part out :) The second part of the exercise is to change the program to display an error message if users types 0 before typing any other number. 作为练习,我必须编写一个程序(使用do和while循环),该程序计算用户键入0时输入和退出的数字的平均值。我弄清楚了第一部分:)练习的第二部分是更改如果用户在键入任何其他数字之前输入0,则程序将显示错误消息。 Can you kindly explain to me what is the easiest way to accomplish this? 您能否向我解释最简单的方法是什么? If you provide the code is great but I'd also like an explanation so I am actually understanding what I need to do. 如果您提供的代码很棒,但是我也想解释一下,那么我实际上已经知道我需要做什么。 Thank you! 谢谢! Here is the code: 这是代码:

import java.util.Scanner;

public class totalave1 {
    public static void main(String[] args) {
        int number, average, total = 0, counter = 0;
        Scanner fromKeyboard = new Scanner(System.in);
        do {
            System.out.println("Enter number to calculate the average, or 0 to exit");
            number = fromKeyboard.nextInt();
            total = total + number;
            counter = counter + 1;
            average = (total) / counter;
        } while (number != 0);
        System.out.println("The average of all numbers entered is: " + average);
    }
}

The good news is that you probably have done the hardest part. 好消息是您可能已完成了最艰巨的任务。 :) However, I don't want to give too much away, so... :)但是,我不想付出太多,所以...

Have you learned about control flow? 您了解控制流吗? I assume you might have a little bit, as you are using do and while . 我认为您可能会有点,因为您正在使用dowhile I would suggest taking a look at the following Java documentation first: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html 我建议先看看以下Java文档: https : //docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html

Then, look at your current solution and try to think what conditions you have that would lead you to display the error message, using if statements. 然后,查看您当前的解决方案,并尝试使用if语句来考虑哪些条件会导致您显示错误消息。 How do you know the user typed a 0? 您怎么知道用户输入了0? How do you know it's the first thing they entered? 您怎么知道这是他们输入的第一件事? Are there any variables that you have now that can help you, or do you need to create a new one? 您现在是否有任何变量可以帮助您,还是需要创建一个新变量?

I know this is not a code answer, but you did well in this first part by yourself already. 我知道这不是代码答案,但是您在第一部分中已经做得不错。 Let us know if you need further hand. 让我们知道您是否需要进一步的帮助。

The second part of the exercise is to change the program to display an error message if users types 0 before typing any other number. 练习的第二部分是,如果用户在键入任何其他数字之前输入0,则更改程序以显示错误消息。

It is not very clear : 还不是很清楚:

  • Do you you need to display a error message and the program stops ? 您是否需要显示错误消息并且程序停止?
  • Do you you need to display a error message and to force the input to start again ? 您是否需要显示错误消息并强制输入重新开始?

In the first case, just add a condition after this instruction : number=fromKeyboard.nextInt(); 在第一种情况下,只需在此指令后添加一个条件: number=fromKeyboard.nextInt(); :

     do{
        System.out.println("Enter number to calculate the average, or 0 to exit");
        number=fromKeyboard.nextInt();
        if (number == 0 && counter == 0){
            System.out.println("Must not start by zero");
            return;
        }
       ...
      }  while (number!=0);

In the second case you could pass to the next iteration to take a new input. 在第二种情况下,您可以传递到下一个迭代以获取新的输入。 To allow to go to next iteration, just change the number from zero to any value different from zero in order that the while condition is true. 为了允许进行下一次迭代,只需将数字从零更改为任何与零不同的值,以使while条件成立。

     do{
        System.out.println("Enter number to calculate the average, or 0 to exit");
        number=fromKeyboard.nextInt();
        if (number == 0 && counter == 0){
            System.out.println("Must not start by zero");
            number = 1;
            continue;
        }
       ...
      }  while (number!=0);

Here is a simple program that extends on yours but uses nextDouble() instead of nextInt() so that you can enter numbers with decimal points as well. 这是一个扩展到您的简单程序,但是使用nextDouble()而不是nextInt()因此您也可以输入带小数点的数字。 It also prompts the user if they have entered invalid input (something other than a number): 它还会提示用户是否输入了无效的输入(数字以外的东西):

import java.util.Scanner;

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

    System.out.println("Java_Paws's Average of Numbers Program");
    System.out.println("======================================");
    System.out.println("Usage: Please enter numbers one per line and enter a 0 to output the average of the numbers:");
    double total = 0.0;
    int count = 0;

    while(scanner.hasNext()) {
      if(scanner.hasNextDouble()) {
        double inputNum = scanner.nextDouble();
        if(inputNum == 0) {
          if(count == 0) {
            System.out.println("Error: Please enter some numbers first!");
          } else {
            System.out.println("\nThe average of the entered numbers is: " + (total / count));
            break;
          }
        } else {
          total += inputNum;
          count++;
        }
      } else {
        System.out.println("ERROR: Invalid Input");
        System.out.print("Please enter a number: ");
        scanner.next();
      }
    }
  }
}

Try it here! 在这里尝试

Don't go down code after reading and if you cant then see the code. 阅读后不要记下代码,如果看不到,则请查看代码。

First you have to learn about the flow control . 首先,您必须了解flow control Second you have to check whether user entered 0 after few numbers get entered or not, for that you have to some if condition . 其次,您必须检查是否在输入了几个数字之后用户是否输入了0 ,为此您必须输入if condition If current number if 0 and it is entered before anyother number then you have to leave rest of the code inside loop and continue to next iteration. 如果当前编号为0并且在任何其他编号之前输入,那么您必须将其余代码留在循环内,并继续进行下一个迭代。

import java.util.Scanner;
public class totalave1
{
    public static void main (String[]args)
     {
          int number, average, total=0, counter=0;
          boolean firstTime = true;
          Scanner fromKeyboard=new Scanner (System.in);
          do{
               System.out.println("Enter number to calculate the average, or 0 to exit");
               number=fromKeyboard.nextInt();
               if(firstTime && number==0){
                     System.out.println("error enter number first");
                     number = -1;
                     continue;
               }
               firstTime = false;
               total=total+number;
               counter=counter+1;
               average=(total)/counter;
            } while (number!=0);
    System.out.println("The average of all numbers entered is: "+average);  
    }

}

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

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