Java Math.min Math.max 错误 [英] Java Math.min Math.max Errors

查看:37
本文介绍了Java Math.min Math.max 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

}

推荐答案

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

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

这篇关于Java Math.min Math.max 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆