java 用户的数字范围0到100 [已关闭]

niwlg2el  于 2023-02-18  发布在  Java
关注(0)|答案(3)|浏览(136)

已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题?**添加详细信息并通过editing this post阐明问题。

16小时前关门了。
Improve this question
我是编程新手,我的任务之一是为0到100的数字编写代码;如果一个数是负数,我必须把负数变成正数。我试了很多方法来解决这个问题,但是都没有成功。如果有人能解释一下如何解决这个问题,那就太好了。

System.out.print("Enter a number between 0 to 100: ");
    Scanner input = new Scanner(System.in);
    int range = input.nextInt();
    
    // Display the user result 
    if (user1 > range) 
        System.out.println("A correct number was entered "); 
    else if (user1 > range) 
        System.out.println("An incorrect number was entered"); 
    else 
    {
    System.out.print("The number range " + range + " needs to be positive "); 
    System.out.print(range * -1); // If the number is negative convert to positive
    }
        
}
htzpubme

htzpubme1#

我会改写为:

int minInclusive = 0;
int maxInclusive = 100;
Scanner input = new Scanner(System.in);

System.out.print("Enter a number between " + minInclusive + " and " + maxInclusive + " inclusive: ");    
int number = Math.abs(input.nextInt()); // number is now POSITIVE    
if (number >= minInclusive && number <= maxInclusive) {  // COMPOUND BOOLEAN EXPRESSION!
    System.out.println("A correct number was entered "); 
}
else {
    System.out.println("An incorrect number was entered"); 
}
rvpgvaaj

rvpgvaaj2#

如果它是负的,那么简单地否定该值

if(range < 0) {
  range = -range;
}
xfb7svmp

xfb7svmp3#

这里是你错过了什么:
“range”变量的不准确命名很可能会使您感到困惑
我认为你的意思是user1是用户输入而不是“range”变量,在这里,它给所有程序员上了一堂非常重要的课:为变量命名,以便您能够理解它们
以获得更具描述性的变量名,因此我将user1重命名为user_input

int user_input = input.nextInt();

它会修改代码以

if (user_input > range) {
        System.out.println("A correct number was entered "); 
    }
    else if (user_input > range) {
        System.out.println("An incorrect number was entered"); 
    }
    else 
    {
        System.out.print("The number range " + user_input + " needs to be positive "); 
        System.out.print(user_input * -1); // If the number is negative convert to positive
    }
  • 我还添加了一些括号以提高可读性和格式正确性 *

从这里继续,看起来你这里的值域是问题中0到100的值域

if (user_input > 0) {
        System.out.println("A correct number was entered "); 
    }
    else if (user_input > 100) {
        System.out.println("An incorrect number was entered"); 
    }
    else 
    {
        System.out.print("The number range " + user_input + " needs to be positive "); 
        System.out.print(user_input * -1); // If the number is negative convert to positive
    }

我们终于有了一个可以工作的,漂亮的代码。
在最后一次触摸中,我建议使用abs来改变符号,以便更好地理解。

if (user_input > 0) {
            System.out.println("A correct number was entered "); 
        }
        else if (user_input > 100) {
            System.out.println("An incorrect number was entered"); 
        }
        else 
        {
            System.out.print("The number range " + user_input + " needs to be positive "); 
            System.out.print(Math.abs(user_input)); // If the number is negative convert to positive
        }

现在我们完成了:)

相关问题