tags:

views:

386

answers:

8

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

+10  A: 

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
+1  A: 

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
How about this: oddcount += newnum1 mod 2;
pkaeding
That breaks for negative numbers: -1 % 2 == -1
jackrabbit
A: 

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

I'm going to down vote myself for spec'ing 2 vars in this answer ;)
Apparently can't down vote myself.
A: 

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
Thanks for the code, but could you explain to me how it works please? I'm finding this activity slightly hard!
appreciation
@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
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
@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
+5  A: 

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?

OscarRyz
+1. This is quite possibly the best answer to a simple programming question that I have ever seen. Very well written Oscar.
D.Shawley
@D.Shawley: Oh thanks. And that was probably the best comment I have ever had :")
OscarRyz
Well to be fair, that one and a "I love you" here: http://bit.ly/34oAze
OscarRyz
Jherico
A: 

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
@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=4639626Having 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
You don't have to special case negative numbers when testing for even/oddness: compare with 0 instead of 1.
jackrabbit
A: 

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
@migsho: Very nice and compact :) However, it doesn't look like java code and this is a java question.
Asaph
A: 

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