Alex Edwards 321 Posting Shark

Why not store the current time in a data type (like a long) when the key is pressed and when the key is released subtract the new time from the old time?

Here's an example--

public class ImprovedClock{

	private volatile long first = 0, second = 0;
	private volatile boolean startPressed = false, stopPressed = false;

	public void start(){
		if(!startPressed){
			synchronized(this){
				first = System.currentTimeMillis();
				startPressed = true;
				stopPressed = false;
			}
		}
	}

	public boolean hasStarted(){
		return startPressed;
	}

	public void stop(){
		if(!stopPressed){
			synchronized(this){
				second = System.currentTimeMillis();
				startPressed = false;
				stopPressed = true;
			}
		}
	}

	public boolean hasStopped(){
		return stopPressed;
	}

	public long getElapsedTime(){
		long time = 0;
		synchronized(this){
			time = second - first;
			first = 0;
			second = 0;
		}
		return time;
	}

	public double getSeconds(){
		return ((double)getElapsedTime()/1000);
	}
}
import javax.swing.JFrame;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;

public class TimeMonitorTest extends JFrame{


	public TimeMonitorTest(){
		final ImprovedClock ic = new ImprovedClock();
		addKeyListener(
			new KeyAdapter(){
				@Override public void keyPressed(KeyEvent ke){
					if(!ic.hasStarted()){
						ic.start();
						System.out.println("Clock started!");
					}
				}

				@Override public void keyReleased(KeyEvent ke){
					ic.stop();
					System.out.println("Time elapsed: " + ic.getSeconds() + " seconds!");
				}
			}
		);
		setSize(300, 300);
                setLocation(500, 500);
		setVisible(true);
	}

	public static void main(String... args){
		TimeMonitorTest tmt = new TimeMonitorTest();
	}
}

To make this work simply focus the pane (by clicking it) and key events will be listened for. Hold down a key then when you release it the seconds the key was held down will be displayed.

Alex Edwards 321 Posting Shark

Why not store the current time in a data type (like a long) when the key is pressed and when the key is released subtract the new time from the old time?

Alex Edwards 321 Posting Shark

I think you need to be more concise with the requirements.

You have 30 strings correct? Does this mean that they each cannot be more than 20 characters long (including the null terminator)?

You must make your char[20][30] (or most likely char[30][20]) in pointer form, then convert it into an array of strings, or vice versa?

What are the required functions to use in this project?

Alex Edwards 321 Posting Shark

Do you want to draw an image from a file, or do you want to be able to "rotate" a set of pixels such that they emulate a rotating String?

This can be either really simple or hard depending on where you want to rotate. If you have variable rotation points, this sill be incredibly hard.

Alex Edwards 321 Posting Shark

Oh boy, there is a lot of wind being blown in this topic.

To simplify things, everything sent to a function gets copied (or generates an object) if--

-An implicit cast is done (sending an int to a function that takes an Integer object for example (and for further clarity, the Integer object has a constructor that isn't marked explicit and takes an int)) (non-pointer)
-You send a value of a built-in type to a function (non-pointer)
-You send a value of an object to a function (non-pointer)
-*You send a pointer to a function

* yes, a copy of the actual pointer is sent to the function, not the pointer itself.

To elaborate on the pointer issue, think about what a pointer's purpose is first. A pointer simply points to an address (with the restriction of the type of address the pointer can point to).

When you pass a pointer to a function, you are passing a copy of the pointer (so you're sending a copy-pointer to the function. It still references the same address though).

Alterations to the elements of the pointer will obviously effect the original version because the original version and the copy pointer point to the same address, so the de-referenced objects of both are the same.

However, if you change what the pointer is pointing to in the function, it changes what the copy is pointing to and not the initial pointer.

For …

Alex Edwards 321 Posting Shark

Is there any real different between using an union between two types and a reinterpret_cast between two types, for example--

#include <iostream>

int main(){
    union{
        unsigned short *a;
        float *b;
    };

    float value = 0.6f;
    b = &value;

    std::cout << *a << std::endl;

    unsigned short *s;
    float *f;

    f = &value;
    s = reinterpret_cast< unsigned short*>(f);

    std::cout << *s << std::endl;
    return 0;
}

--the results of the test are the same between the union and the reinterpret_cast but I would like to know if there is some kind of difference I should be aware of when using both.

Thank you!

-Alex

Alex Edwards 321 Posting Shark

Most companies that I know that use Cobol are moving towards Java.

I'd guess that being, strictly a Java developer would be much more ideal in America, though I do not know about anywhere else.

Then again if you want to companies migrating from Cobol to Java you would probably be an ideal candidate. Just a possibility.

Alex Edwards 321 Posting Shark

Your professor may have last compiled a "massive project" in 1970. :)
My workstation compiles and jars a Java project of 869 class files in ~20 seconds. Incremental background compiles while editing are near enough real-time.

Oh, and what about the Metaprogram compiles for languages that support templates?

Would that not be longer if there are a lot of template algorithms used? >_>

Alex Edwards 321 Posting Shark

Haven't you been to work experience yet ?
When I went to work experience, We (me and another friend) ended up getting a placement at Juiced Games for 2 weeks. That gave me a big experience of what programming can be like in a job. To be totally honest, it was a very relaxed environment, the only thing you had to watch out for is something called sprints. A sprint is a deadline to complete a task, and if you fall behind then I guess you have a problem. We also got to see a few of the programmers at work, and it looks like a lot of fun. Every 30-60 mins they would compile their new project and test for bugs. Some programmers would be developing the game itself, while others would be producing tools for the Artists to use.

I hope this answers abit of your question :)

Except you didn't say how long compile times can be for massive projects! O_O

I recall my professors saying that compiling can take a very long time... so it's best to get things right the first time X_X

Alex Edwards 321 Posting Shark

I suppose you're using a GCanvas, or most likely the GraphicsProgram from the acm.program package?

You could have GCanvases pre-painted with components and when you advance a level, simply set the contentpane to a particular GCanvas of interest.

I think it may be better for me to produce an example, but that might take a bit of time --

esy928 commented: helpfull +1
Alex Edwards 321 Posting Shark

My first question to you is...

Do you know what the different between an interface and an abstract class is? O_o

Alex Edwards 321 Posting Shark

Although I haven't attempted it before, I'd assume you'd have a particular zone renderred on the screen with a type of "cover" over it. Either that or only render certain pixels ahead of the borders on a pane.

The position of your character would, obviously determine when the screen will be renderred on the side...

Bah this has given me some ambition to make a game like this @_@

Alex Edwards 321 Posting Shark

I started learning C++ (which is supposedly harder to learn than Java) at the age of 13, and im completely self taught. All it takes is a bit of time and effort, and it seems you just haven't put in the effort. :-O

Theres also plenty of resources over the web that could help you, so saying "My teacher didn't do a good job of telling us how to work on it" shoulden't really matter.

It still amazes me that you've become as good as you are at such a young age =)

It'll be awhile before I can catch up to you in C++ and Assembly. Until then, I must study more! XP

Edit: Actually, come to think of it... you pretty much have to be willing to study your entire life to be a good programmer.

Change happens and you just have to deal with it. If you fold your arms and close your eyes to things that change, you'll be left in the dust @_@

William Hemsworth commented: I'm sure you will catch up :)! +3
Alex Edwards 321 Posting Shark

Ok one big thing to note, before anything else--

vector<vector<double>>

-- is not a portable statement because >> may (depending on the compiler) be analyzed as the right bitshifting operator and throw an error. You'll want to space out those symbols.

vector<vector<double> >

Edit: Also I think you may need to push_back vectors into your main vector before you can access any elements in the matrix-vector.

sciwizeh commented: thanks i probably wouldn't have caught that +1
Alex Edwards 321 Posting Shark

Although I'm Atheist, I swear to god I got dumber from reading this topic.

Alex Edwards 321 Posting Shark

Javascript is in the web development section, not here =/

Alex Edwards 321 Posting Shark

Hmm, can that union trick work with reinterpret_cast also?

i.e.--

#include <iostream>

using namespace std;

int main(){
    union{
        short *a;
        float *b;
    };

    float value = .1f;
    b = &value;

    std::cout << *a << std::endl;

    short *s;
    float *f;

    f = &value;
    s = reinterpret_cast<short*>(f);

    std::cout << *s << std::endl;
    return 0;
}
Alex Edwards 321 Posting Shark

I'd assume this is because of the padding factor and vtable pointers like you mentioned before.

Alex Edwards 321 Posting Shark

Don't forget what classes are for!

Classes are things capable of having behavior and encapsulating information.

Encapsulated information can be data, but it's slightly beyond just that.

Behavior can be considered a method, but it's slightly beyond that as well.

If you're not worried about the stats of a unit changing, I'd most likely place that information in the abstract unit class and each derived unit can have the same stats with different values.

This isn't encouraged though - chances are you will want a Stat class that holds the information of the stats.

Alex Edwards 321 Posting Shark

I can already see you using the Bridge and/or Strategy pattern from the specs.

You'll also most likely end up using the Observer pattern.


Try not to be distracted by the specs too much. Break down the problem.

You're limited to 1000 points of units. What I'd do is have the army class abstractly contain a set of units to use (an array or list of units - your call).

The set of type of units will be set during construction of the army, but you may also want to provide functionality to set the type of units during run-time to show flexibility to the system (though this is most likely not required).

Each abstract unit has a cost() method that defines how much that unit will cost.

You van use a separate list that will be the result of populated units (obviously an implementation of a random generator and a data type that contains the max amount of cost for the army).

Each Army class (or class the encapsulates the units) can act as the Observable and signal to all units, or observers, within the given army to initiate an attack.

Implement an attack(Unit other) command for all units, and also a react(Unit fromUnit) command. Since the kind of attacks can vary, you may (or may not) want to consider using an encapsulated Action interface that has a method act() which defines what will be done during an attack …

Ezzaral commented: Very helpful answer. +11
Alex Edwards 321 Posting Shark

The error-- append(java.lang.String) in javax.swing.JTextArea cannot be applied to (PhoneDirectorySystem)PhoneBook_TextArea.append(list); --is a fairly obvious statement.


You could return the toString() of an element in the list and add to the JTextArea.

It may even be better to have a toString method available for the entire list (if you're making a custom list) and separate the values with the line-terminator "\n".

Alex Edwards 321 Posting Shark

Note that it is a String representation of the memory address and not an accessible (or directly modifiable) memory address.

Alex Edwards 321 Posting Shark

Thanks sciwizeh for ur reply.

I need to fetch the memory address of the variable . In one article which i have read that "we cant say that we cant access the memory location".

Use the Object.toString() method to return the memory address.

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

       Object o = new Object();
       System.out.println(o.toString());

}
Alex Edwards 321 Posting Shark

I have the Art of Assembly book, so learning Assembly to understand another book won't be too much of an issue. It'll just take time @_@

And thank you Radical Edward and vijayan121 for the recommendation of the same book - I plan to get that next =)

Alex Edwards 321 Posting Shark

I'm enjoying the book Effective C++. It has highlighted things that I've looked over, never heard of, or never even though of before! However, even with this book my understanding of C++ still doesn't seem to be solid.

For some time now I've been curious about how binary data is handled as well as developing efficient algorithms to improve performance. My curiosity grew after seeing a lot of posts here that strictly deal with data problems (conversions, casts, copying data, serialization and file I/O, binary algorithms, etc).

From what I understand, at some point or another, an object in C++ holds data based on the built-in types of C++ (and if it doesn't, I'd assume for that object to be a "tool" object, like pow or other math funcctions I suppose). What I want to understand is how to have better control of data and how it is represented in a class, structure, union or namespace. Basically a recommendation for a book that really goes in depth on how data is represented in all possible data containers.

For example, how is data (at the binary level) sorted in a struct or a class? In a union it's fairly straightforward (the amount of memory that's used in a union is shared across its members). For classes and structs I'd assume for it to be conditional (what separates the binary representation of the data, or is it simply "summed up?"). Additionally how does a namespace resolve data - is …

Alex Edwards 321 Posting Shark

What if exponent is a double itself :-)

Then use the Math Library =P

Alex Edwards 321 Posting Shark

To make this easier, you might want to consider using a Server class that encapsulates a ServerSocket and has an array of Sockets.

The ServerSocket will be used to establish the Server, while the array of Sockets will be used for awaiting Clients (via ServerSocket.accept() ).

Attached is a poorly written Checkers project I made. The highlight of the project is how information is being sent and received between the CheckersDisplay classes and the ServerObject class.

To run the program, run the Server first then run the CheckersDisplay project twice (though, you may want to wait until one is showing first before loading the other).

Somewhere in the CheckersDisplay is a main with the CheckersDisplay constructor called. Change the String after you have one running so that the chat-box will have different users displayed instead of the same name between both clients.

Again it's poorly written but it should suffice for a good example of Client/Server programming in a nutshell.

Alex Edwards 321 Posting Shark

I'm assuming you're not allowed to use the Math library or recursion.

If that's the case, use--

static double power(double value, short exponent){
       if(exponent >= 0){ // if exponent is greater than or equal to zero...
       double result = 1; // set result to one

       for(short i = 0; i < exponent; i++){ // doing something exponent times
             result = result * value; // result is assigned the number of itself times value
       }     
       
       return result; // return the result
       }else return 0; // exponent was less than 0 - return 0 for simplicity.
}
Alex Edwards 321 Posting Shark

Well guess I will have to do that, can't see any other way. I have spent like two days trying to make this work, and I guess I have had enough ^^

Thank you all for your help, hope my bad English hasn't been a problem ;)

Off topic: You actually type better English than some people who have lived in America for over 40 years...

Alex Edwards 321 Posting Shark

I still haven't figured out how to give someone neutral rep, yet I see everyone do it @_@

How is this done? I've tried clicking on the radio buttons multiple times in the add-rep form but no luck.

Damn you geniuses at Daniweb programming! XP

-Alex

Alex Edwards 321 Posting Shark
/*
 * Author@WilliamHelmsworth
 *  Make sure project type is windows application
 */

#define _WIN32_WINNT 0x0500
#include<windows.h>
#include<cmath>

LRESULT CALLBACK mouseHookProc(int nCode, WPARAM wParam, LPARAM lParam) {
   // Get event information
   PMSLLHOOKSTRUCT p = (PMSLLHOOKSTRUCT) lParam;

   bool eat = false;

   // Screen resolution
   static float screen_cx = static_cast<float>( GetSystemMetrics(SM_CXSCREEN) );
   static float screen_cy = static_cast<float>( GetSystemMetrics(SM_CYSCREEN) );

   // Centre of screen
   static float screen_centre_x = screen_cx / 2.0f;
   static float screen_centre_y = screen_cy / 2.0f;

   // Calculate distance away from centre of screen
   float dx = p->pt.x - screen_centre_x;
   float dy = p->pt.y - screen_centre_y;

   float dist = sqrt(dx * dx + dy * dy);

   // Check if cursor is more than 300px away from centre of screen
   if (dist > 300) {
      float angle = atan2(dy, dx);

      // Trap cursor
      SetCursorPos(
         /* X */ int( screen_centre_x + cos(angle) * 300 ),
         /* Y */ int( screen_centre_y + sin(angle) * 300 )
      );

      // Stop windows handling event
      eat = true;
   }

   return (eat ? 1 : CallNextHookEx(NULL, nCode, wParam, lParam));
}

int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine,
                   int nShowCmd) {

   // Set mouse hook
   HHOOK mouseHook = SetWindowsHookEx(
                  WH_MOUSE_LL,      /* Type of hook */
                  mouseHookProc,    /* Hook process */
                  hInstance,        /* Instance */
                  static_cast<DWORD>(NULL));

   // Wait for user to exit
   MessageBox(NULL, "Press OK to close.", "", MB_OK);
   return 0;
}

I did make one minor change and that is the static cast from NULL to DWORD to satisfy the compiler.

I ran this using Dev-CPP default compiler …

Alex Edwards 321 Posting Shark

I like williamhelmswort's mouse-hook snippet. It always makes random amusement when I use it on somebody elses computer and watch them struggle to move the mouse XD

William Hemsworth commented: Thanks !! :) +3
Alex Edwards 321 Posting Shark

Again, just because you can do something on one compiler doesn't mean that you should. See the output I posted when trying to compile your code with G++ 4.2.1. ( a very recent version ).

If I uncomment the line const int GamePlayer::NumTurns; , then the linker error goes away ( still with G++ ).

Maybe VC++ has been lax about issuing an error, and/or has implemented the feature in a way that differs from other compilers. For best portability, follow this author's recommendation.

It's not that I ignored your post. I replied to the other individual with what I understood.

This is probably the best answer, and is a good lesson to have multiple compilers on hand instead of just one.

Curse the competitive compiler vendors! @_@

-Alex

Alex Edwards 321 Posting Shark

By "taking the address" I believe it means using the address-of operator (&). An example of taking the address of something:

int x;
int* y = &x; // here we take the address of x and assign it to the pointer y

See my comment below--

The "definition" part it talks about should be implemented something like below. Assume you have GamePlayer class defined in GamePlayer.h and the actual implementation is in GamePlayer.cpp:

// GamePlayer.h
class GamePlayer{
   public:
      static const int NumTurns = 5;

      GamePlayer();
};
// GamePlayer.cpp
#include "GamePlayer.h"

const int GamePlayer::NumTurns; // definition of NumTurns... 

GamePlayer::GamePlayer() {
   // constructor code here
}

This isn't exactly what I'm misunderstanding. The author made this clear to me already. It's what he means by taking the address of the value when it is declared and not defined.


I've tried using the ampersand symbol to reference the address of the value and assigning it to a pointer. The result is the same as the code I posted.

// Effective_CPP_Practice_1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>

class GamePlayer{
	public:
		static const int NumTurns = 5;

		GamePlayer(){
		}
};

//const int GamePlayer::NumTurns;

int main()
{
	const int *iPtr = &GamePlayer::NumTurns; // taking the address of GamePlayer::NumTurns...?
	std::cout << *iPtr << std::endl; // no run-time error either??
	return 0;
}
Alex Edwards 321 Posting Shark

I'm using VC++ Express Edition

The book states that the technique isn't portable across older compilers (due to the fact that initialization wasn't allowed for field data types in classes for those versions).

Edit: I'll have to reread through the current section to make any further comments--

Alex Edwards 321 Posting Shark

Hello I'm reading through Scott Meyer's book Effective C++, third Edition.

I'm having an issue understanding Page 14, Item 2, paragraph 4.

The below is a snippet of code with an explanation quoted from his book--

// Author: Scott Meyers

class GamePlayer{
     private:
         static const int NumTurns = 5; // constant declaration
         int score[NumTurns]; // use of constant
         ...
};


"What you see above is a declaration for NumTurns, not a definition. Usually, C++ requires that you provide a definition for anything you use, but class-specific constants that are static and of integral type (e.g., integers, chars and bools) are an exception. As long as you don't take their address, you can declare them and use them without providing a definition. If you do take the address of a class constant, or if your compiler incorrectly insists on a definition even if you don't take the address, you provide a separate definition like this;

"

const int GamePlayer::NumTurns; // definition of NumTurns...

Maybe I'm not understanding the part bolded. I made this program to try to confirm my understanding of not being able to take an address of the class declared member, and I was capable of doing so without any issue.

Here's the code I use to test the example provided--

// Effective_CPP_Practice_1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>

class GamePlayer{
	public:
		static const int NumTurns = 5;

		GamePlayer(){
		}
};

//const int …
Alex Edwards 321 Posting Shark

I didn't pay close attention to the first post. Apparently JFrame has an initial Layout of BorderLayout.

The OP added the TextArea to the Center Border. By simply adding the JMenuBar, I suppose it will have a default add to either the center of the next available border, or in a random location though I can't confirm which.

All he has to do is add the JMenuBar to the North to ensure that the JMenuBar will be visible and alligned over the JTextArea

Alex Edwards 321 Posting Shark

You may also want to consider using a BorderLayout so that your Menu bar will appear at the top within a JFrame--

import javax.swing.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;


public class JotPad extends JFrame
{
	private JTextArea textArea;

	public JotPad()
	{
		super("Jot Pad");
		setLayout(new BorderLayout());
		//Arrange the Editing Pane
		textArea = new JTextArea(20, 50);
		textArea.setEditable(true);
		setBounds(300, 500, 700, 500);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JScrollPane scrollingText = new JScrollPane(textArea);

		//Set all the panel to size and add the components
		JPanel mainPanel = new JPanel();
		mainPanel.setLayout(new BorderLayout());
		mainPanel.add(scrollingText, BorderLayout.CENTER);
		setLocationRelativeTo(null);
		setContentPane(mainPanel);
		mainPanel.setOpaque(true);

		// We must set it as visible or else it will run in the background which is bloody useless
		setVisible(true);

		//Set all the menu bits
		JMenuBar menu = new JMenuBar();
		JMenu file = new JMenu("File");
		menu.add(file);

		add(menu, BorderLayout.NORTH);


	}

	public static void main(String[] args)
	{
		new JotPad();

	}

}
Alex Edwards 321 Posting Shark

class bubbleSort1{


public static void bubbleSort(int[] x) {
int n = x.length;
for (int pass=1; pass < n; pass++) { // count how many times
// This next loop becomes shorter and shorter
for (int i=0; i < n-pass; i++) {
if (x > x[i+1]) {
// exchange elements
int temp = x; x = x[i+1]; x[i+1] = temp;
}
}
}
}
}
the output say..

java.lang.NoSuchMethodError: main
Exception in thread "main"

The class that you're trying to run doesn't have an entry point (main) method.

Try declaring this method in your class--

public static void main(String[] args){


}

-- also please use code tags.

Alex Edwards 321 Posting Shark

It was a very interesting remark especially taking into account:
1. No classes in pure C
2. It's C++ forum.
;)

And this is why you are getting reputation, for noting my mistake of thinking he compared structs with classes =P

Alex Edwards 321 Posting Shark

I reattempted this problem without using namespaces, and the partial class realized each others methods...

I guess this is solved, but I'd still like to know why I must leave off the namespaces for the class to realize methods in a different file with the same partial class declaration/definition?

Edit: Figured it out. If you use the same namespace for each partial class then it's considered the same partial class. I guess this makes sense.

Thanks!

Alex Edwards 321 Posting Shark

I think Bitwise & operator can be useful.

No & 2 == 0 means Odd
and
No & 2 == 2 means Even
(here No is any number)

Is this correct?

I think it also using condition but different approach rather than modulus

Though zero isn't an even number, it's even enough.

No & 2 == 2 would return false for No = 0.

.
.
.

Modulus wins!

Alex Edwards 321 Posting Shark

I've read up to the point where the author explains partial classes.

I understand the general concept - they're used when a class is so big that it is better to split it across files.

I created two .cs files. Let's say one is CS1.cs and the other is CS2.cs

For each file I have a partial class MyPartialClass

I have tried implementing a Constructor in one file and a method in the other, in which the Constructor calls the method across files, however I receive error messages saying that the method doesn't exist in this context or the Constructor (with parameters) isn't realized.

When I qualify a partial class with its respective namespace it is treated as that namespace's specific class.

I've tried the using directive (where one file is using the other file and vice versa) so that the partial class would possibly be realized, but to no effect.

I've even tried NOT doing any of this, implementing the "using" calls for each namespace in the separate files and simply calling the constructor of one but with disappointing results (still treated as a separate class and not a partial class).

Basically, how do I make a partial class realized? In other words, how do I invoke commands from a part of the class within a file that has the same partial class, or is this impossible?

I know there is something I am not understanding. …

Alex Edwards 321 Posting Shark

Classes are same as structs with the exception of default private and public.

That's a good C++ definition, but that doesn't hold true for pure C.

Alex Edwards 321 Posting Shark

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.

Alex Edwards 321 Posting Shark

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 …

Alex Edwards 321 Posting Shark

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 …

Alex Edwards 321 Posting Shark

if you are using other dll's you can't access their internal classes or properties.

http://msdn.microsoft.com/en-us/library/7c5ka91b(VS.80).aspx check this url for examples

It seems that I need to continue reading and get a thorough grasp on how assemblies are used in C# before I can really understand the difference.

Thanks!

Alex Edwards 321 Posting Shark

I'm pretty sure it's something along the lines of--

Runtime.getRuntime().gc();

Or the long way--

Runtime rt = Runtime.getRuntime();

rt.gc();

I do believe you can do the same using System instead of Runtime (without calling getRuntime - just System.gc() )


This simply suggests for the Garbage-Collecting threads to begin garbage collecting. It does not mean that it will be immediately done. In that respect, it's not really known when garbage collecting will be done. Lastly, explicitly calling the gc causes additional overhead since the call to gc is suggesting that there are unreferenced objects to collect and the threads are signalled to do extra work and search through all possible objects to garbage collect ones that are reachable and unreferenced.

The process is slightly more complicated than mentioned. This is a watered down and brief explanation.

Alex Edwards 321 Posting Shark

Hi, my name is Alex. I'm fairly new to C# but apparently I may be required to know how to manipulate .NET Frameworks via C# so I am studying a beginners book and another book to thoroughly understand the language.

The problem is that I am struggling to understand the concept of the internal command.

As quoted from the 2nd book I'm reading--

"...On the other hand, if a class is internal, the semantics of access modifies is identical to those of a public class except for one key restriction: Acces is limited to those classes within the same compiled unit. Otherwise, no method or data field of an internal class is directly accessible among classes that are compiled separately."

It seems straightforward, but now I'm curious as to how a class is considered to be in our outside of a compiled unit?

For example, if I include ('using') a class to be used within the current C# program, is that class now included in the compiled unit also, and therefore I have access to its internal methods? Or is the compiled unit strictly the classes within the initial namespace (or in a namespace)?

Also, if C# is like C++ where you can use other namespaces in a given namespace, will the namespace that is included be a part of the compiled unit?

Any explanation to clear up this mist would be nice. Thank you!

-Alex