如何用Java分析数字的偶数/奇数

发布于 2024-08-09 10:04:49 字数 785 浏览 2 评论 0原文

我必须编写一个程序来读取 3 个数字(使用输入框)​​,并且根据它们的值,它应该写入以下消息之一:

  • 所有 3 个数字都是奇数 或者
  • 3 个数字都是偶数 OR
  • 2 个数字是奇数,1 个数字是偶数 或者
  • 1 个数字是奇数,2 个数字是偶数

这是我到目前为止所拥有的:

import javax.swing.JOptionPane;
class program3

{
    public static void main(String[] args)

    {

        String num1 = JOptionPane.showInputDialog("Enter first number.");
        String num2 = JOptionPane.showInputDialog("Enter second number.");
        String num3 = JOptionPane.showInputDialog("Enter third number.");

        boolean newnum1 = Integer.parseInt(num1);
        boolean newnum2 = Integer.parseInt(num2);
        boolean newnum3 = Integer.parseInt(num3);
    }

}

这就是我陷入困境的地方。我不知道如何使用 MOD 来显示消息。我想我也必须使用 IF 语句...但我不太确定。

请帮忙! :D

I have to write a program which reads in 3 numbers (using input boxes), and depending on their values it should write one of these messages:

  • All 3 numbers are odd
    OR
  • All 3 numbers are even
    OR
  • 2 numbers are odd and 1 is even
    OR
  • 1 number is odd and 2 are even

This is what I have so far:

import javax.swing.JOptionPane;
class program3

{
    public static void main(String[] args)

    {

        String num1 = JOptionPane.showInputDialog("Enter first number.");
        String num2 = JOptionPane.showInputDialog("Enter second number.");
        String num3 = JOptionPane.showInputDialog("Enter third number.");

        boolean newnum1 = Integer.parseInt(num1);
        boolean newnum2 = Integer.parseInt(num2);
        boolean newnum3 = Integer.parseInt(num3);
    }

}

This is where I am stuck. I am not sure how to use the MOD to display the messages. I think I have to also use an IF Statement too...But I'm not too sure.

Please help! :D

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

嘿嘿嘿 2024-08-16 10:04:49

在Java中,模运算符是%。你可以这样使用它:

if ( (a % 2) == 0) {
    System.out.println("a is even");
}
else {
    System.out.println("a is odd");
}

将它与一些 if 语句或一些计数器结合起来以实现最终结果。

PS:newnumX 的类型看起来很奇怪:)

In Java, the modulus operator is %. You can use it like this:

if ( (a % 2) == 0) {
    System.out.println("a is even");
}
else {
    System.out.println("a is odd");
}

Combine it with some if statements or some counter to implement the final result.

PS: the type of newnumX looks odd :)

浅听莫相离 2024-08-16 10:04:49

我建议您

  • 开始在一张纸上写下您将如何手动完成此操作。
    (编写算法)

  • 然后识别哪些部分是“可编程的”,哪些部分不是(识别变量、语句等)。

  • 手动尝试不同的数字,看看它是否有效。

  • 从那里我们可以帮助您将这些想法转化为工作代码(这是最简单的部分)。

这些是您必须掌握的基本编程技能。

不值得我们只回答:

 boolean areAllEven = ( one % 2 == 0 ) &&  ( two % 2 == 0 ) && ( three % 2 ==  0 ) ;
 boolean areAllOdd  = ( one % 2 != ..... etc etc 

因为我们会不帮助你。

相关条目: 从问题传递到代码的过程。你是怎么学的?

I would recommend you to

  • Start writing down in a piece of paper how would you do it manually.
    ( Write the algorithm )

  • Then identify which parts are "programmable" and which ones are not ( identify variables, statements, etc ) .

  • Try by hand different numbers and see if it is working.

  • From there we can help you to translate those thoughts into working code ( that's the easy part ).

These are basics programming skills that you have to master.

It is not worth we just answer:

 boolean areAllEven = ( one % 2 == 0 ) &&  ( two % 2 == 0 ) && ( three % 2 ==  0 ) ;
 boolean areAllOdd  = ( one % 2 != ..... etc etc 

Because we would be diss-helping you.

Related entry: Process to pass from problem to code. How did you learn?

你的往事 2024-08-16 10:04:49

为了避免又大又难看的嵌套 IF,我会声明一个小计数器(用伪代码):

if newnum1 mod 2 == 1 then oddcount += 1;
etc...

switch oddcount
    case 0:
        print "All three numbers are even"
    etc...

To avoid big ugly nested IFs, I would declare a small counter (in pseudocode):

if newnum1 mod 2 == 1 then oddcount += 1;
etc...

switch oddcount
    case 0:
        print "All three numbers are even"
    etc...
傻比既视感 2024-08-16 10:04:49

如果您选择在 Java 中使用 % 运算符,请注意:如果其左侧操作数为负数,则会产生负数。 (请参阅语言规范)也就是说,(-5) % 2 产生结果 -1。

您可能需要考虑按位运算,例如“x & 1”来测试偶数/奇数。

Just a warning if you choose to use the % operator in Java: if its left-hand operand is negative, it will yield a negative number. (see the language specification) That is, (-5) % 2 produces the result -1.

You might want to consider bitwise operations e.g. "x & 1" to test for even/odd-ness.

岁月打碎记忆 2024-08-16 10:04:49

它甚至比这更简单,你有树编号 a、b、c

n = a%2 + b%2 +c%2
switch (n):
 case 0: 'three are even'
 case 1: 'one is odd'
 case 2: 'one is even'
 case 3: 'three are odd'

瞧!

Its even simpler than that, you have tree numbers a, b, c

n = a%2 + b%2 +c%2
switch (n):
 case 0: 'three are even'
 case 1: 'one is odd'
 case 2: 'one is even'
 case 3: 'three are odd'

And voila!

我也只是我 2024-08-16 10:04:49

写下执行该任务必须执行的基本步骤,然后尝试用代码实现它。

您需要执行以下操作:

1 - 从用户处获取 3 个号码。

2 - 您需要两个变量:一个用于保存奇数输入的数量,另一个用于保存偶数输入的数量。我们称它们为 EvenCnt 和 oddCnt。 (提示:因为你知道你只有 3 个数字,所以一旦你确定了其中一个,另一个就是与 3 的差)

3 - 然后你需要一系列测试(如果 EvenCnt 是 3 则显示“3 Evens”) ,否则如果....)

(Pascal 和 Kurosch 已经为您提供了填写步骤 2 和 3 所需的片段。)

[编辑:我的 #2 是个糊涂人。你只需要一个变量。]

Write down the basic steps that you have to do to perform the task and then try to implement it in code.

Here is what you have to do:

1 - Get 3 numbers from the user.

2 - You need two variables: one to hold the number of odd inputs and the other to hold the number of the even ones. Lets call these evenCnt and oddCnt. (Hint: Since you know you only have 3 numbers, once you have determined one of these, the other one is just the difference from 3)

3 - Then you need a series of tests (If evenCnt is 3 then show "3 evens", else if ....)

(And Pascal and Kurosch have pretty much given you the fragments you need to fill in steps 2 and 3.)

[Edit: My #2 is wooly-headed. You only need one variable.]

栀梦 2024-08-16 10:04:49

干得好。我刚刚编译并运行了一些测试用例来确认它的工作原理。

import javax.swing.JOptionPane;

class Program3 {
    public static void main(String[] args) {
        int evenCount = 0;

        for (int i=0; i<3; i++) {
            // get the input from the user as a String
            String stringInput = JOptionPane.showInputDialog("Enter number " + (i+1) + ".");

            // convert the string to an integer so we can check if it's even
            int num = Integer.parseInt(stringInput);

            // The number is considered even if after dividing by 2 the remainder is zero
            if (num % 2 == 0) {
                evenCount++;
            }
        }

        switch (evenCount) {
            case 3:
                System.out.println("All are even");
                break;
            case 2:
                System.out.println("Two are even, one is odd");
                break;
            case 1:
                System.out.println("One is even, two are odd");
                break;
            case 0:
                System.out.println("All are odd");
                break;
        }
    }
}

顺便说一句:我将类名大写是因为在 Java 中这样做是最佳实践。

Here you go. I just compiled and ran some test cases through this to confirm it works.

import javax.swing.JOptionPane;

class Program3 {
    public static void main(String[] args) {
        int evenCount = 0;

        for (int i=0; i<3; i++) {
            // get the input from the user as a String
            String stringInput = JOptionPane.showInputDialog("Enter number " + (i+1) + ".");

            // convert the string to an integer so we can check if it's even
            int num = Integer.parseInt(stringInput);

            // The number is considered even if after dividing by 2 the remainder is zero
            if (num % 2 == 0) {
                evenCount++;
            }
        }

        switch (evenCount) {
            case 3:
                System.out.println("All are even");
                break;
            case 2:
                System.out.println("Two are even, one is odd");
                break;
            case 1:
                System.out.println("One is even, two are odd");
                break;
            case 0:
                System.out.println("All are odd");
                break;
        }
    }
}

BTW: I capitalized the class name because it's best practice to do so in Java.

醉生梦死 2024-08-16 10:04:49

我不同意阿尔法零。我不认为两个变量是必需的。每个数字要么是曾经的,要么是奇数的。因此,数一数就足够了。

至于 Asaph 的代码,我认为它有很好的文档记录,但如果您仍然想要解释,请看这里:

这就是 for 循环的作用:

它读取(作为字符串)用户输入的 3 个数字
Integer.parseInt 是一个函数,它采用 String 作为参数(例如 '4')并返回 int< /code>(在此示例中为 4)。然后,他通过将这个整数除以 2 来检查该整数是否为偶数。基本思想是:4%2 = 0 且 9%2 = 1(mod 运算符用作 a%b 时给出余数在操作a/b之后。因此,如果a%2为0,则a是偶数)。有一个计数器(称为evenCount)用于跟踪有多少个整数是偶数(基于%s 测试)。

然后,他继续对 evenCount 执行 switch 语句。 switch 语句有点像 if-else 语句。它的工作方式是根据 case 值(在本例中为 3, 2, 1, 0)测试 switch 参数(在本例中为 evenCount)。如果测试返回 True,则执行 case 块中的代码。如果该 case 块末尾没有break 语句,则也会执行后面的 case 块中的代码。

在这里,Asaph 通过将 EvenCount 与 0、1、2 和 3 进行比较来检查有多少个数字是偶数,然后使用适当的打印语句告诉用户有多少个偶数

希望这有帮助

I disagree with alphazero. I don't think two variables are REQUIRED. every number is either ever or odd. So keeping count of one is enough.

As for Asaph's code, I think it is well documented, but if you still want an explanation, here goes:

This is what the for loop does:

It reads (as Strings) user input for the 3 numbers
Integer.parseInt is a function that takes a String as a parameter (for example, '4') and returns an int (in this example, 4). He then checks if this integer is even by modding it by 2. The basic idea is: 4%2 = 0 and 9%2 = 1 (the mod operator when used as a%b gives the remainder after the operation a/b. Therefore if a%2 is 0, then a is even). There is a counter (called evenCount) that keeps track of how many integers are even (based on the %s test).

He then proceeds to do switch statement on the evenCount. A switch statement is sort of like an if-else statement. The way it works is by testing the switch parameter (in this case, evenCount) against the case values (in this case, 3, 2, 1, 0). If the test returns True, then the code in the case block is executed. If there is no break statement at the end of that case block, then, the code in the following case block is also executed.

Here, Asaph is checking to see how many numbers are even by comparing the evenCount to 0, 1, 2, and 3, and then usinga appropriate print statements to tell the user how many even numbers there are

Hope this helps

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文