0

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

Gumbo
  • 643,351
  • 109
  • 780
  • 844
appreciation
  • 9
  • 1
  • 2
  • No, it's from a text book. But there is no example of this in it. – appreciation Oct 30 '09 at 23:40
  • 5
    Have you tried compiling this? Doesn't *something* about newnum1,2,3 seem wrong? – alphazero Oct 30 '09 at 23:43
  • 2
    That's possibly the least informative question title ever. You should get a silver badge: "Absolutely Uninformative Title". Please fix the title to describe what your question is so people can help you. – S.Lott Oct 30 '09 at 23:46
  • I think it should be: int newnum1 = Integer.parseInt(num1); int newnum2 = Integer.parseInt(num2); int newnum3 = Integer.parseInt(num3); I have changed this in my code now. – appreciation Oct 30 '09 at 23:47
  • a good extension of the problem would be have it take an arbitrary number of inputs in a single box, and display a running tally of odds/evens. This num1, num2, num3 business is just un-pretty. – Carl Oct 31 '09 at 01:56
  • This sounds awfully like homework (even the class name gives that away) – monksy Oct 31 '09 at 02:46

8 Answers8

11

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

Pascal Thivent
  • 562,542
  • 136
  • 1,062
  • 1,124
5

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?

Community
  • 1
  • 1
OscarRyz
  • 196,001
  • 113
  • 385
  • 569
  • 1
    +1. This is quite possibly the best answer to a simple programming question that I have ever seen. Very well written Oscar. – D.Shawley Oct 31 '09 at 02:39
  • @D.Shawley: Oh thanks. And that was probably the best comment I have ever had :") – OscarRyz Oct 31 '09 at 02:53
1

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...
kurosch
  • 2,292
  • 16
  • 17
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.

Jason S
  • 184,598
  • 164
  • 608
  • 970
  • @Jason S: Good point about negative numbers and the % operator. The behavior of % with negative numbers is actually surprising to many programmers since it's inconsistent with the behavior of % in other languages. This has been reported to Sun as a bug but closed as "not a bug" with the explanation that % is a remainder operator, *not* a modulus operator. http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4639626 Having said that, bitwise comparisons, while they may work, are somewhat unjavaish. Better stick to the more readable % operator even if you have to special case negative numbers. – Asaph Oct 31 '09 at 02:58
  • You don't have to special case negative numbers when testing for even/oddness: compare with 0 instead of 1. – jackrabbit Nov 01 '09 at 20:06
0

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.]

alphazero
  • 27,094
  • 3
  • 30
  • 26
0

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.

Asaph
  • 159,146
  • 25
  • 197
  • 199
  • 2
    Thanks for the code, but could you explain to me how it works please? I'm finding this activity slightly hard! – appreciation Oct 30 '09 at 23:54
  • @appreciation: I just introduced a loop to remove some code duplication. I'll add in comments inside the for loop to clarify what each step does. – Asaph Oct 31 '09 at 00:00
  • 1
    Thanks for your help! I have another question: Why is it important to capitalise the class name? If I am correct, the class name is the same name as the file name. I noticed this when I went into my programs folder. – appreciation Oct 31 '09 at 01:54
  • @appreciation: You are correct. The class name must match the filename. In java, we have a convention that class names are always capitalized, and method and variable names always begin with a lower case letter. These conventions are so widely followed that code that doesn't use them might actually confuse a seasoned java programmer. So go ahead and do capitalize your class name and filename. – Asaph Oct 31 '09 at 02:41
0

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!

migsho
  • 31
  • 4
  • @migsho: Very nice and compact :) However, it doesn't look like java code and this is a java question. – Asaph Oct 31 '09 at 02:47
0

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

inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241