如何在程序中包含输入的整数必须介于0到100之间?

时间:2016-11-06 00:57:49

标签: java

练习让我计算平均值,最大值和最小值。我的代码实现了这个目的,但是我需要在我的代码中包含某个地方,用户输入的考试成绩必须在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");



    }

    }

谢谢!

2 个答案:

答案 0 :(得分:0)

创建一个嵌套循环,一旦用户满足条件,该循环将停止执行。像这样:

object(stdClass)#181 (2) {
  ["preprocedure"]=>
      array(3) {
       [1]=>
         string(5) "demo1"
       [2]=>
         string(0) ""
       [3]=>
         string(5) "demo3"
     }
 ["submitbutton"]=>
     string(12) "Save changes"

请注意,此代码尚未经过测试,这只是它应该是什么样子的概念。

答案 1 :(得分: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);