繁体   English   中英

Java Math.min Math.max 错误

[英]Java Math.min Math.max Errors

我的目标是让java程序接收用户的输入,显示输入的数字,1到5之间。所以如果用户输入一个大于5的数字,它显示为5,如果数字小于1,它显示为 1。然而,无论输入的数字如何,程序都只显示输出 1。

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);
        }

}

Math.min(1, n)将始终返回1 ,如果n >= 1Math.max(5, n)将总是返回5如果n <= 5 你需要交换它们:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM