Java Math.min Math.max Errors

心不动则不痛 提交于 2020-03-25 22:01:50

问题


My goal is to have the java program receive input from a user, display the inputted number, between 1 and 5. So if a user enters a number greater than 5, it shows as 5, and if the number is lower than 1, it shows as 1. However the program is only showing an output of 1 regardless of the number entered.

import java.util.Scanner;

public class TestMax {

        int minNum = 1;
        int maxNum = 5;

        public int inputNum() {
            Scanner userInput = new Scanner(System.in);
            int userinput = Integer.parseInt(userInput.nextLine());
            return (userinput);
        } 

        public void displayNum(int userNum) {
            userNum = 0;
            Math.min(userNum, minNum);
            Math.max(userNum, maxNum);
            System.out.printf("%d\n", Math.min(1, 
            Math.max(5, userNum)));
        }

        public static void main(String[] args) {    
            TestMax TestMax = new TestMax();
            int userNum = TestMax.inputNum();
            TestMax.displayNum(userNum);
        }

}


回答1:


Math.min(1, n) will always return 1 if n >= 1 and Math.max(5, n) will always return 5 if n <= 5. You need to swap them:

System.out.printf("%d\n", Math.max(1, Math.min(5, userNum)));


来源:https://stackoverflow.com/questions/60178792/java-math-min-math-max-errors

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!