2016-11-06 48 views
-1

練習要求我計算平均值,最大值和最小值。我的代碼滿足這個目的,但是我需要在我的代碼中包含用戶輸入的考試成績必須介於0和100之間的地方。包含這個的最佳方式是什麼? 這是我的代碼。如何在我的程序中包含輸入的整數必須介於0和100之間?

import java.util.Scanner; 
import java.io.*; 
import java.text.DecimalFormat; 


public class hw 
{ 
public static void main (String[] args) 
{ 
    int maxGrade = Integer.MIN_VALUE; 
    int minGrade = Integer.MAX_VALUE; 
    int count=0; 
    int total=0; 
    final int SENTINEL = -1; 
    int score; 

    Scanner scan = new Scanner(System.in); 
    System.out.println("To calculate the class average, enter each test 
    score."); 
    System.out.println("When you are finished, enter a -1."); 

    System.out.print("Enter the first test score > "); 
    score = scan.nextInt(); 


    while (score != SENTINEL) 
    { 
     total += score; 
     count ++; 
     if(score > maxGrade) 
      maxGrade = score; 
     if(score < minGrade) 
      minGrade = score; 

     System.out.print("Enter the next test score > "); 
     score = scan.nextInt(); 
    } 
    if (count != 0) 
    { 
     DecimalFormat oneDecimalPlace = new DecimalFormat("0.0"); 
     System.out.println("\nThe class average is " 
       + oneDecimalPlace.format((double) (total)/count)); 
     System.out.println("The minimum value is " + minGrade); 
     System.out.println("The maximum value is " + maxGrade); 
    } 
    else 
     System.out.println("\nNo grades were entered"); 



    } 

    } 

謝謝!

+0

您在哪裏(以及如何)防止處理'SENTINEL'?這似乎是一個適當的鄰居來強制限制輸入值。 – greybeard

回答

0

創建一個嵌套的循環,一旦用戶滿足條件就會停止執行。事情是這樣的:

while (score < 0 || score > 100) 
{ 
    System.out.println("please enter a number between 0 and 100."); 

     while(!scan.hasNextInt()) 
     { 
      scan.next(); 
     } 
     score = scan.nextInt(); 
    } 

請注意,此代碼沒有經過測試,這只是它應該是什麼樣子的想法。

0
do { 
      System.out.print("Enter number between 1-100:"); 
      while (!option.hasNextInt()) { 
       System.out.println("That's not a number!!!"); 
       option.next(); // this is important! 
       System.out.print("Enter number between 1-100:"); 
      } 
      choice = option.nextIn`enter code here`t(); 
      if (choice < 1 || choice > 100) { 
       System.out.println("Please input 1-100!!!"); 
      } 
     } while (choice < 1 || choice > 4); 
相關問題