Solved

Determining if an integer is even or odd

Posted on 2006-11-13
16
696 Views
Last Modified: 2008-02-01
Hello experts:

I am trying to write a method that determines whether an int is even. The method should tak an int arg and return true if even and false if not. The method must be incorporated into an applicaton that inputs a sequence of ints one at a time. (No arrays).
My problem is I am confused on where and how to return the boolean value. Also, I'm not sure if my program is set up logically correct. I have a feeling that some elements are not in the right place in the program(?) Any suggestions are greatly appreciated! Thanx!
................................................................................................................................
public class EvenOdd
{
      boolean result;
      
      public boolean isEven(int number)
      {
            // Instantiate a random number generator object
             Random randomNum = new Random();
             int num;
            
            for(int i =0; i <= 25; i++)
            {
                  // Generate a random number for input
                  num = 1 + randomNum.nextInt(25);
                  
                  // If remainder of input is 0, it was an even integer
                  if( (num % 2) == 0)
                        return result;
                  else
                        return result;
            }
      }
      
      public void print_message(boolean result)
      {
            if(result == true)
                  System.out.printf("%d is an even integer.");
            else
                  System.out.printf("%d is an odd integer.");
      }
}

........................................
// Driver that tests EvenOdd.java
public class EvenOddTest      
{
      public static void main( String args[])
      {
            EvenOdd input = new EvenOdd();
            
            // ?? input.isEven();
            // ?? input.printMessage();
      }
}
0
Comment
Question by:deekakes
  • 5
  • 5
  • 3
  • +1
16 Comments
 
LVL 23

Assisted Solution

by:Ajay-Singh
Ajay-Singh earned 50 total points
ID: 17930108
why don't you use the following method:

public boolean isEven(int number)
     {
        return number % 2 == 0;
     }
0
 
LVL 23

Expert Comment

by:Ajay-Singh
ID: 17930111
> public class EvenOddTest    
> {
>      public static void main( String args[])
>      {
>           EvenOdd input = new EvenOdd();
>
>           // ?? input.isEven();
>           // ?? input.printMessage();
>      }
> }


change to

public class EvenOddTest    
{
     public static void main( String args[])
     {
          EvenOdd input = new EvenOdd();
         
          boolean x = input.isEven(10);
          input.printMessage(x);
     }
}
0
 

Author Comment

by:deekakes
ID: 17930378
Thanks for your response, Ajay-Singh,

I'm still having problems.  
1.  I made the changes you suggested. However, I am not too sure if I should be returning a value of 0. The problem stated true or false. I understand that 0 means false and 1 is true but...I'm not too sure if it makes much of a difference.   :)
2. When I compile the EvenOdd class i get "missing return statement }".
3. Do I have this method set up correctly - print_message(boolean x)? I get "cannot find symbol" in the main program.

Thanx again,
As you can tell I am a very new newbie and am trying to get what I thought was a very easy problem done without any success!!!!

................................................................
// Program that determines whether an integer is even or odd
public class EvenOdd
{
      //boolean result;
      
      public boolean isEven(int number)
      {
            // Instantiate a random number generator object
             Random randomNum = new Random();
             int num;
            
            for(int i =0; i <= 25; i++)
            {
                  // Generate a random number for input
                  num = 1 + randomNum.nextInt(25);
                  
                  // If remainder of input is 0, it was an even integer
                  {
                    return number % 2 == 0;
                   }
             }
      }
      
      public void print_message(boolean x)
      {
            if(result == true)
                  System.out.printf("%d is an even integer.");
            else
                  System.out.printf("%d is an odd integer.");
      }
}

...................................................................

public class EvenOddTest    
{
     public static void main( String args[])
     {
          EvenOdd input = new EvenOdd();
         
          boolean x = input.isEven(10);
          input.printMessage(x);
     }
}
0
 
LVL 23

Expert Comment

by:Ajay-Singh
ID: 17930576
Here is my version of code:


public class EvenOdd {

    //boolean result;

    public boolean isEven(int number) {
        return number % 2 == 0;
    }

    public void print_message(boolean x) {
        if (x == true)
            System.out.printf("%d is an even integer.");
        else
            System.out.printf("%d is an odd integer.");
    }
}


public class EvenOddTest {

    public static void main(String args[]) {
        EvenOdd input = new EvenOdd();

        boolean x = input.isEven(10);
        input.print_message(x);
    }
}
0
 

Author Comment

by:deekakes
ID: 17930610
Please disregard my last comment. I made some corrections to the code and the only error I now get is: "missing return statement".

import java.util.Random;

// Program that determines whether an integer is even or odd
public class EvenOdd
{
      public boolean isEven()
      {
            // Instantiate a random number generator object
             Random randomNum = new Random();
             int num;
            
            for(int i =0; i <= 25; i++)
            {
                  // Generate a random number for input
                  num = 1 + randomNum.nextInt(25);
                  
                  // If remainder of input is 0, it was an even integer
                  {
                    return num % 2 == 0;
                   }
             }
      }
      
      public void printMessage(boolean x)
      {
            if(x == true)
                  System.out.printf("%d is an even integer.");
            else
                  System.out.printf("%d is an odd integer.");
      }
}
........................
      
// Program driver for EvenOdd.java
public class EvenOddTest    
{
     public static void main( String args[])
     {
          EvenOdd input = new EvenOdd();
         
          boolean x = input.isEven();
          input.printMessage(x);
     }
}
0
 
LVL 6

Expert Comment

by:SamsonChung
ID: 17930739
boolean result;
     
     public boolean isEven(int number)
     {
          // Instantiate a random number generator object
           Random randomNum = new Random();
           int num;
         
          for(int i =0; i <= 25; i++)
          {
               // Generate a random number for input
               num = 1 + randomNum.nextInt(25);
               
               // If remainder of input is 0, it was an even integer
               if( (num % 2) == 0)
                    return result;
               else
                    return result;
          }
     }


result was never set!!!!
0
 

Author Comment

by:deekakes
ID: 17930940
Sorry, Ajay-Singh, but I could not get your version of the code to work so I went back to my original implementation (the first posting) and made a few corrections. However, I am still getting "missing return statement".
SamsonChung, did I set the result variable correctly? Are my parameters correct?
I have been working on this "simple" problem for a few days!.....help.......need rest.....  :(
If anyone has any other suggestions i would be more than willing to increase the points and split them accordingly.

Listed below is the corrected code that still gives me an error:

import java.util.Random;

// Program that determines whether an integer is even or odd
public class EvenOdd
{
        //boolean result;

      public boolean isEven()
      {
            // Instantiate a random number generator object
             Random randomNum = new Random();
             int num;
             boolean result;
            
            for(int i =0; i <= 25; i++)
            {
                  // Generate a random number for input
                  num = 1 + randomNum.nextInt(25);
      
               // If remainder of input is 0, it was an even integer
                 if( (num % 2) == 0)
                 {
                    result = true;
                    return result;
                 }
                 else
                 {      
                    result = false;
                    return result;
                  }      
            }
      
      public void printMessage(boolean result)
      {
            if(result == true)
                  System.out.printf("%d is an even integer.");
            else
                  System.out.printf("%d is an odd integer.");
      }
}
............................
public class EvenOddTest    
{
     public static void main( String args[])
     {
          EvenOdd input = new EvenOdd();
         
          boolean result = input.isEven();
          input.printMessage(result);
     }
}
0
 
LVL 6

Accepted Solution

by:
SamsonChung earned 400 total points
ID: 17931035
Rewriting your code for you....

first off, you don't need a for loop..... you are only getting one random number.....
2nd, missing }.
3rd, return should only occur at end of Method (good OOP practices)
4th, System.out.println not System.out.printf (even if it may work, printf is usually written by people, such as myself, to make life easier on coding when you have to display it a zillion times, within the function)

5th, Please, please please, do not forgot if () { } even it it is a oneliner..... for small programs like this, it is fine.. for big programs, (ie, 50000+ lines) u'll hate yourself for spending 4 weeks on debuging and you found that you meant to do if (alpha) then do pink and mindy, while due to  missing {}, you are doing mindy constantly.

import java.util.Random;

// Program that determines whether an integer is even or odd
public class EvenOdd{
        //boolean result;

     public boolean isEven() {
          // Instantiate a random number generator object
           Random randomNum = new Random();
           int num;
           boolean result;
         
          //for(int i =0; i <= 25; i++) {
               // Generate a random number for input
               num = 1 + randomNum.nextInt(25);
     
              // If remainder of input is 0, it was an even integer
                 if( (num % 2) == 0){
                    result = true;
                 } else {    
                    result = false;
                  }    
            //}
            return result;
     }
}
............................
public class EvenOddTest {
     public static void main( String args[]) {
          EvenOdd input = new EvenOdd();
         
          boolean result = input.isEven();
          if(result){
               System.out.println("This is an even integer.");
          } else {
               System.out.println("This is an odd integer.");
          }
     }
     }
}
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 13

Expert Comment

by:marchent
ID: 17931329
change this
>>result = true;
>>return result;
return (result = true);

>>result = false;
>>return result;
return (result = false);

~marchent~

                 
0
 
LVL 6

Expert Comment

by:SamsonChung
ID: 17931356
Marchent....

Just a suggestion..

that's not what you want..

because you are then returning whether it is true or false that you can perform (result = true or result = false).

.... with result being boolean, it will always be true.
0
 

Author Comment

by:deekakes
ID: 17931376
I always used to write my if...else statements with {}, but lately I've been seeing them
omitted and I guess I decided to follow suit somehow thinking it was a better coding practice. i will definitely use them always from now on. (Besides, the braces make the program easier to read.)

I think I do need a loop because the problem states that I should input a sequence of integers. Now that I've thought it over and have realized that I misunderstood the question, I don't think I'll be needing the Random object. Probably just a for loop with n numbers.

Well, anyway, thanks a heap for your useful hint/tips.
0
 
LVL 6

Expert Comment

by:SamsonChung
ID: 17931417
you are most welcome....

Java is my fav language.... well, its ranking is slightly below that of Prolog, Lisp and Miranda...... (Functional Programming languages should rule the net.... )

Anyways, yes, {} are very useful..... trust me, I spend 2 months debugging my classmate's buggy code in my final year at University..... it was a 2,000,000+ line program involving AI.

Which resulted in me throwing two bricks at him after 30 min of reading his horrible code.

I've never seen a constructor that large....ever......
0
 

Author Comment

by:deekakes
ID: 17931441
lol  :)
0
 
LVL 13

Expert Comment

by:marchent
ID: 17937662
Chung

>>Just a suggestion..
where is the suggestion

>>because you are then returning whether it is true or false that you can perform (result = true or result = false).
did i say somthing wrong?

>>.... with result being boolean, it will always be true.
what do u mean by this?

thank you
~marchent~

0
 
LVL 6

Expert Comment

by:SamsonChung
ID: 17939013
Marchent my friend,

let me make this more clear.

your statement says. return (result = false);

Let me ask you this question, have you ever try doing the following.

int i;
if (i = 5) {
   System.out.println("This is AMAZING");
}

if you run that, it will say 'This is AMAZING'.

The reason is, you are asking the Java VM, if (true or false) {do something}

now, true or false, to VM means, in this case, can I assign 5 to variable i (note, = is also a function) so, if variable is capable of accepting 5, then true, else false.

so, in the case of your return statement, result is boolean. Can VM Assigning false to a boolean? can VM Assign true to a boolean?

So, the answer will always be true.

Hope that is more clear..... I doubt I can make it anymore clearer then that........
0
 
LVL 13

Expert Comment

by:marchent
ID: 17944784
offcoure can, why not?
try this example
public class Test
{
   
    public static void main(String argc[])
    {
        boolean b = false;
        if(b == false) System.out.println("False");
        b = true;
        System.out.println("True");
    }
}

is that what u said? of did i understand ur point? i'm confused !!!!

~marchent~

0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
sumHeights2  challenge 7 78
json example 39 115
JList custom Cell Renderer refresh 15 43
HSSFWorkbook cannot be resolved error 10 23
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now