从用户那里读取一系列数字,直到输入 -1,Java

Reading a series of numbers from the user until -1 is inputted, Java

我正在尝试编写一个程序来从用户那里读取一系列数字,直到输入 -1。然后它应该打印这些数字的平均值(带小数点)(不包括 -1)。到目前为止,这是我所拥有的,但每当我输入 -1 时,它似乎都无法正常工作。这是我到目前为止所拥有的:

   import java.util.Scanner;
    import java.util.*;  
    public class Tute1
    {
public static void main (String[] args) {
   Scanner sc = new Scanner(System.in);
  System.out.println("Enter how many numbers you want: ");
  int numb = sc.nextInt();
  int i =0;
  int total =0;
  while (i <= numb) {
      Scanner scan = new Scanner(System.in);
      System.out.println("Enter an integer ");
      int myChoice=scan.nextInt();
      total=total+myChoice;
      i=i+1;
if(myChoice == -1) {
          System.out.println("The average is "+ (total+1)/numb);
          break;
}    
}
    System.out.println("The average is "+ total/numb);
     }  
     }

您的代码似乎有点奇怪。这是我的做法

import java.util.Scanner;
import java.util.*;

public class Tute1 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int i = 0;
        int total = 0;
        while (true) {
            System.out.println("Enter an integer ");
            int myChoice = scan.nextInt();
            if (myChoice != -1) {
                total = total + myChoice;
                i += 1;
            } else {
                break;
            }

        }
        float average = total / i;
        System.out.println("The average is " + average);

    }

希望这对您有所帮助。您可以添加 try-catch 和其他东西来制作它,这样用户就不会利用这个

几件事:

  • 首先,您不需要在 while 循环中创建一个新的扫描器作为您的代码。这是因为 while 循环在你的函数范围内,所以你在函数上声明的每件事 while 循环都知道。 (反之则不行)
  • 其次,你的中断条件应该在 while 循环内,带 break 的 if 是多余的和不必要的。
  • 你应该摆脱麻木的第三件事,因为它在做 nithung
    import java.util.Scanner;
    import java.util.*;
    public class Tute1 {
        public static void main (String[] args) {
            Scanner sc = new Scanner(System.in);
            int numb = sc.nextInt();
            int i =0;
            int total =0;
            while (numb != -1) 
            { 
                total=total+numb;
                i=i+1;
                int numb = sc.nextInt() 
            }
            System.out.println("The average is "+ total/i); 
        }
    }

我认为这个解决方案更小更优雅