2016-11-06 99 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); 
相关问题