Good day!!
I was observing this class doing their laboratory exercise on java. We are of the same professor that is why I had this instinct that we will be doing the same exercise on our class too.

They were asked to do this:

->Make a class that has the method for accepting infinite input numbers. But when the user enters (zero)”0’, the program stops asking for inputs. No specific range of inputs and should not be stored in an array! Using array is prohibited!
->Your class should also have a method for getting the MAXIMUM and the MINIMUM numbers of the input.
->Also, it should have a method for getting the SUM, the DIFFERENCE and the PRODUCT of the EVEN and ODD NUMBERS of the input.
->Implement this class on your main program.

The output goes like this:
Enter numbers: _ <input “0” to stop>

Maximum number input:
Minimum number input:
Sum of EVEN inputs:
Sum of ODD inputs:
Difference of EVEN inputs:
Difference of ODD inputs:
Product of EVEN inputs:
Product of ODD inputs:

I find it very hard to understand OOPs’ in java. And its too frustrating knowing the fact that I really don’t have any idea on how to implement a class on my main program!

As I was practicing at home, I have made this one… Its totally useless…can you give me a revised form of these…or any ideas about this!!

//My Class
	
public class Exercise 
{
    private int input;
    private int sum, difference, product, sumE, differenceE, productE;
    
    
    public Exercise() 
    {
        input=0;
        sum=difference=product=sumE=differenceE=productE=0;
    }
    public Exercise(int s,int d,int p,int sE,int dE,int pE)
    {
    	sum=s;
    	difference=d;
    	product=p;
    	sumE=sE;
    	differenceE=dE;
    	productE=pE;
    }
    public void set(int s,int d,int p,int sE,int dE,int pE)
    {
    	sum=s;
    	difference=d;
    	product=p;
    	sumE=sE;
    	differenceE=dE;
    	productE=pE;
    	
    }
    public int getInput()
    {
    	return input;
    }
    public int getSum()
    {
    	return sum;
    }
    public int getSumEven()
    {
    	return sumE;
    }
    public int getDiff()
    {
    	return difference;
    }
    public int getDiffEven()
    {
    	return differenceE;
    }
    public int getProd()
    {
    	return product;
    }
    public int getProdEven()
    {
    	if(input%2==0)
    		productE+=input*input;
    	return productE;
    }
    public void display
    {
    	int count;
    	
    	for(int i;i<count;i++)
    	{	
    		System.out.println(productE);
    	}
    }
    
}

//My Main Program

import java.io.*;

public class TestExercise
{
	public static void main(String []args)
		throws IOException
		{
			BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
			
			Exercise nums=new Exercise();
			String str;
		do
		{	
			System.out.print("Enter number: ");
			str=br.readLine();
			nums=Integer.parseInt(str);
		}
		while(nums!=0);
		if(nums==0)
			System.exit(0);	
			
			System.out.println("SUM OF EVEN: ");
			productE.display;		
		}
}

Thanks for further replies!!
God Bless!!

Recommended Answers

All 7 Replies

I think you're making this assignment harder than it really is.

Try to understand the problem first.

You are accepting input into a method. The input can be any number except 0 alone.

You WILL have data types to store information.

At minimum, you will need a data type to store the minimum number, and the max number.

To help you get started, look at the problem again--

"Make a class that has the method for accepting infinite input numbers."

--this can be taken many ways, but assume that when the method is called that there is an infinite loop running that will have a condition for stopping. What is that condition?--

"But when the user enters (zero)”0’, the program stops asking for inputs"

--the condition is that when the user inputs 0, the program must exit.

// Somewhere in the object controlling the data

public void startReading(){

   			BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

       boolean stopped = false;
       while(!stopped){
                System.out.println("Enter a value");
                String s = br.readLine(); // might be nextLine(), I don't recall
                
                if(s.equalsIgnoreCase("0")){ 
                         stopped = true;
                         continue;
                }
                
                // method(s) to accept input
 
       }
}

This way if 0 is entered the rest of the code (the methods reading values) will be skipped due to the continue statement. Stopped will be true, so the expression evaluates to false and the loop ends, and so the method ends.

That takes care of one requirement!

Now think about how you're going to manage getting the max, and min and differentiating between odd and even numbers!

Edit: Here's a modified version that explains the first spec of the project--

import java.io.*;

public class StorageClass{
	// Somewhere in the object controlling the data

	public void startReading(){

				BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

	       boolean stopped = false;
	       while(!stopped){
			System.out.println("Enter a value");

			String s = null;
			try{
				s = br.readLine(); // might be nextLine(), I don't recall
			}catch(IOException io){System.out.println(io);}

			if(s.equalsIgnoreCase("0")){
				 stopped = true;
				 continue;
			}

			// method(s) to accept input

	       }
	}

	public static void main(String... args){

		StorageClass sc = new StorageClass();

		sc.startReading();

	}
}

i got you idea sir!!!

but i still dont have any idea for doing those mathematical operations!!!

i got you idea sir!!!

but i still dont have any idea for doing those mathematical operations!!!

This is not a helpful post. It's a two sentence response to a multiple paragraph response trying to give you some help. Nowhere does it explain what precisely you are stuck on, except for probably the whole thing. This is an assignment with several parts. Do it one part at a time. Decide what you are going to store the input in first. You can't use an array. You'll want some type of Collection:

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collection.html

I think a Vector would be useful here:

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Vector.html

So set up something to hold all the input, read in the input and store it in that Vector or whatever you use, and go from there. Might as well start with finding the max, as Alex suggested. Get the program working for that option, where it reads in the data, calculates the max, and displays the answer. Once that's solved, start working on the other options (sum, product, etc.).

There's no need for any type of collection or multi-storage type.

As the user enters input, the max is updated and so is the min. Also the sum of the odds, sum of evens, product of odds, product of evens and difference of odds and difference of evens are updated.

He just needs 6 data types really (+ the 2 for the max and min, so really only 8). 3 setters with a switch/if-else statement based on the odd or even number then update the current sums, differences and products.

I think the instructor's overall goal is to see if the students can update a continuous amount of information by updating single data types based on previous values (without using an array).

Because I'm a nice person, I'll give you some hints.

To differentiate between even and odd use this--

public void showNumStatus(int b){
      if(b%2 == 0){
            System.out.println(b + " is an even number");
      }
      else if(b%2 == 1){
            System.out.println(b + " is an odd number");
      }
}

--this simply displays if a number is even or odd. You can replace the else-if with else since a number is either even or odd (with the abstract exception that 0 is considered an even number, though I doubt in reality it is. In Java it's treated that way).

Furthermore you will want 3 methods that set the Difference, Product and Sum of a number argument and have this even/odd switch statement in each that handle each case accordingly.

Remember what a class is for! Classes are meant to contain data and provide functionality. There's more to classes than just this definition (Classes can represent real-life things with traits and responsibilities, but I'm assuming you're getting adjusted to the idea of a class so stick with data and functionality for now).

There's no need for any type of collection or multi-storage type.

I suppose not. Rereading the OP's first post, I don't see anywhere where storing all of the information entered is either prohibited or required. That said, if the program is to be expanded later to include something else, say a sort, you might well need to have access to all of the numbers, not just the most recent two and some running total variable. Also, when displaying the results, it often looks nicer to display the original numbers too, which would require keeping track of them. From the original requirements posted by the OP, you could do everything in one big loop and never call a function, but I think it's generally better to store the data and pass it to functions to break the work up.

I think the instructor's overall goal is to see if the students can update a continuous amount of information by updating single data types based on previous values (without using an array).

Quite possibly true, but we really don't know until the OP tells us. Perhaps by disallowing arrays, the instructor intends to make any type of storage of all the numbers off-limits, but the OP doesn't actually say that. If we take the word "infinite" literally, that precludes storing all of the data obviously.

I suppose not. Rereading the OP's first post, I don't see anywhere where storing all of the information entered is either prohibited or required. That said, if the program is to be expanded later to include something else, say a sort, you might well need to have access to all of the numbers, not just the most recent two and some running total variable. Also, when displaying the results, it often looks nicer to display the original numbers too, which would require keeping track of them. From the original requirements posted by the OP, you could do everything in one big loop and never call a function, but I think it's generally better to store the data and pass it to functions to break the work up.

Quite possibly true, but we really don't know until the OP tells us. Perhaps by disallowing arrays, the instructor intends to make any type of storage of all the numbers off-limits, but the OP doesn't actually say that. If we take the word "infinite" literally, that precludes storing all of the data obviously.

I guess it would be nice if he had separate lists that store the total input, even number inputs and odd number inputs.

Edit: To the original poster, you may find using Integer.MAX_VALUE and Integer.MIN_VALUE useful for this assignment.

Just my aspect, beware, it'll be subjective:
- 1st about OOP: On the binary level, an OOP program works the same way a Process Oriented one does. OOP is not about the program, but the code you write for the compiler. It can help making your work easier, not the program better. So the way learning OOP is just finding out how can it make your work easier in any and every aspect. It's as simple as this.
For example, if you write a lot of small classes and small specific methods, then you won't wonder later, what this long loop do with those 20 declared variables. This is the so called encapsulation, which makes your code more readable.

- You shouldn't try to find out what will be your next task updating the program, simply because you can't. You just have to prepare for the unexpected, because this aproach always works. :) This is one of the thing an OO design can help you out: If you use self containing calsses that provide just one simple part of the functionality, fx. an itterator that stops at 0, or a summer that just adds up the given number to it's inner storage, then you won't have to scrap anything, because those basic parts will be always required. This is the so called reusability. Of course you have to write 1 class, but that can use other classes. :)

And trust me, in real life, we are almost always "firing on moving targets". Sometimes the only thing that's changing is the client's mod(I'm serious here!). We use to say here, it's like if sby ask you to make a photo of him, but then can't find out where exactly, and start running around like crazy. :D So writing reusable code will be one of your most important skills later.

- Just for the specific exercise:
I think it must be noticed that the kind of statistics the program have to export are all easily associative. That means 1+2+3=(1+2)+3. So if you would use an array, all the numbers would fill your memory for no reason. This would mean that if the programs would get millions of numbers, the ones designed by arrays would crash and the others would "beat them up"! This is called scalability. Too bad the teacher don't have the patience to demonstrate it with this contest, but now at least you can imagine it.

- "Implement this class on your main program." Maybe it means you shoud write a main class that demonstrate your class's functionality. Maxbe not... my english is not good enough to crack this. Maybe it can't be cracked, because it's just ambiguous.
But what I would do:
I write a program with reusable classes, and with enoug encapsulation I can point out any point of code without even seeing the letters. Then assume it means this, and go to consult about my work, if I've been wrong or not. Whatever he say, I'm 2 mins from the sollution, so I don't care. :)

Usually clients request me complete stupidity, or I can't even nunderstand whatever they want, and the only way I can make them understand just my question is to make a demonstration code. But I won't waste any time even with that, because that code's components could be entirely rearanged in mins.

Well, I didn't wrote your code, but I hope I helped with the OOP. It cold even be solved by firing events onto a bean context, but no point, so your code is as good as mine. And moreover others did good work about this already. :)

commented: None of this post makes the least bit of sense. -2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.