2017-10-17 87 views
-3

所以我写了这个简单的应用程序。现在我想要做的是打印按键时的平均结果。当我将字符串值设置为“getal”时,将打印出平均结果。Java:按下0时平均打印

有人能指出我正确的方向吗?下面你可以看到代码:

double i; 
    double getal = 0; 
    int tellen = 0; 

    while(input.hasNextDouble()) { 
      System.out.println("Volgenge getal"); 
      i = input.nextDouble(); 
      getal = getal + i; 
      tellen++; 
     } 

    System.out.println("Gemiddelde is " + getal/(tellen)); 
+3

你已经说过你想要做什么。你只需要在代码中表达它。这里有一个重播:**如果按下**零,你想** break **退出循环。 – Makoto

+0

我已经试过,它打印Gemiddelde是NaN –

+0

[“有人可以帮我吗?”不是一个问题](http://meta.stackoverflow.com/q/284236)。请[编辑]你的问题,以更具体地了解你需要什么。 –

回答

1

当用户输入什么是你应该做的是把你的计数逻辑死循环里面,然后打破这个循环的等于0:

double i; 
    double getal = 0; 
    int tellen = 0; 

    Scanner input = new Scanner(System.in); 

    while(true) { 
      System.out.println("Volgenge getal"); 
      i = input.nextDouble(); 
      getal = getal + i; 
      if(i == 0){ 
       //break statements end the loop 
       break; 
      } 
      //we need to increment our count down here so the '0' doesnt count 
      tellen++; 
     } 

    System.out.println("Gemiddelde is " + getal/(tellen)); 
    input.close(); 
} 

还有很多其他的方法可以做到这一点,它不一定要用我使用的确切逻辑。另一种方法是使用do while循环。

double i; 
    double getal = 0; 
    //in this example we need to start the count at -1 since we are going to be counting the '0' 
    int tellen = -1; 

    Scanner input = new Scanner(System.in); 

    do{ 
      System.out.println("Volgenge getal"); 
      i = input.nextDouble(); 
      getal = getal + i; 
      //we need to increment our count down here so the '0' doesnt count 
      tellen++; 
     }while(i != 0); 

    System.out.println("Gemiddelde is " + getal/(tellen)); 
    input.close(); 
} 
+0

是的,这是我一直在寻找。谢谢! –

+0

没问题。很高兴我能帮上忙。 – luckydog32