How to have a range of numbers in an if/else statement Java

后端 未结 6 550
轮回少年
轮回少年 2021-01-03 04:37

I\'m learning Java through a series of explanations and exercises, and one of them was to create a program that would display a number grade (0-5) in accordance to a number

6条回答
  •  心在旅途
    2021-01-03 05:13

    You can use a NavigableMap, most commonly a TreeMap. The method used below is floorEntry. Quoting Javadoc:

    Returns a key-value mapping associated with the greatest key less than or equal to the given key, or null if there is no such key.

    Note: Your code was missing an = sign on the 29 boundary, and the points value should be an integer.

    Changed to use a grade (0-5), instead of the string used in question.

    // Grade boundary is lower-inclusive (grade is 0-60)
    TreeMap gradeMap = new TreeMap<>();
    gradeMap.put( 0, 0); //  0–29
    gradeMap.put(30, 1); // 30–34
    gradeMap.put(35, 2); // 35–39
    gradeMap.put(40, 3); // 40–44
    gradeMap.put(45, 4); // 45–49
    gradeMap.put(50, 5); // 50+
    
    System.out.println("Type the points [0-60]: ");
    int points = reader.nextInt();
    reader.nextLine();
    int grade = gradeMap.floorEntry(points).getValue();
    System.out.println("Grade: " + grade);
    

提交回复
热议问题