I think it would be more useful if one could pass the string into a method and have it return the number of question-marks found (as an unsigned int, or in extraordinary cases an unsigned long int).
Alex Edwards 321 Posting Shark
William Hemsworth commented: long time, no see :D +9
Alex Edwards 321 Posting Shark
If you post your files, people will be more willing to help because it gives them time to look at your logic and help you understand which steps to take to complete your project.
Alex Edwards 321 Posting Shark
void TestVector(Vector<double> v)
{
}
int main()
{
Vector<double> pd(5.6,3.4,2.4);
// use the cast operator works if copy ctor is not defined
Vector<float> pf = pd;
// use the copy ctor works if cast operator is not defined
TestVector(pd);
}
In the above example, Vector<float> pf = pd won't work because the immediate assignment given a storage type before the identifier is the call to the constructor for the given type. Because it is a call to the constructor, the compiler will do a lookup for a constructor that accepts the given type. You might be successful if your class took more than just one type as a template parameter, and allow a call to the constructor such that your assignment would be legal.
For example, Vector<float, double> pf = pd
In which the second template argument would be used as a means of resolving the other type.
You could either do this, or (possibly) throw pf on the stack without initializing it, then calling the operator () which is what you probably intended to do--
void TestVector(Vector<double> v)
{
}
int main()
{
Vector<double> pd(5.6,3.4,2.4);
Vector<float> pf; // throwing pf on the stack
pf = pd<float>(); // calling overloaded operator () in pd
TestVector(pd);
}
-- then again it's just a theory to help push you in the right direction.
Alex Edwards 321 Posting Shark
You know, I've been wondering about this for awhile now myself.
Honestly you can probably get away with making some kind of regex or key to "compress" files with given values.
For example lets say you have a text document and it is set up something like this--
// myWord.txt
ssssss
ss
-- what is listed is 6 s's, then 6 space characters, then a newline character and then 2 s's. After those s's, the end-of-file character is present (not in the above example, but pretend it is there for the sake of this example @_@ ).
How would you compress this? Right now the amount of space this file takes up on a disk is between (6 * 1 + 6 * 1 + 6 * 2 + (1 or 0)) or 24-25 bytes to 4096 bytes (4 kb) due to the way expansions work on some disk drives. If you want to compress this file to take up less space, you can form a special key that detects multiple values of a particular character and places them in an index.
For example, there are 6 s's. You can make a .compress file such that it has a pair of numbers (like 1 and 6) such that they are read from a parser that you will create that takes an index file of the same name for a particular .compress file and maps the numbers to their corresponding characters in the index file.
…
Alex Edwards 321 Posting Shark
There is hope!
Use fmod to resolve the modulus between two doubles
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main(){
double x = fmod(4.5, 3.22);
cout << x << endl; // 1 R 1.28, so 1.28 should print out
cin.get();
return 0;
}
William Hemsworth commented: ahh x) +5
Alex Edwards 321 Posting Shark
Just a thought, instead of writing each object after serializing one by one to the file, why don't you just serialize the entire ArrayList and write it to a file.
And when you need to add any data to the file, get the ArrayList back from the file, add the object to the ArrayList and serialize this ArrayList overwrite the file with the older file.
Unfortunately, the implementation of ArrayList<T> looks [something] like this--
//... necessary imports
public class ArrayList<T> extends List<T> implements Collection<T>, Serializable{
private transient Object[] elements = null; // key point @_@
public T get(int position){
return (T)elements[position];
}
}
stephen84s commented: Thanks for catching that one, Now I remember the same problem had made me switch to use ArrayDeques in one of earlier projects. +3
Alex Edwards 321 Posting Shark
Hmm, try changing char to unsigned (if it exists @_@ )
-Alex
Edit: I am really tired #_#
I didn't realize I made the array back-asswards XD
XP
Alex Edwards 321 Posting Shark
You can use the bool array as a "bit-position" array for the representation of a char.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main(){
bool bits[] = {0, 1, 0, 0, 0, 0, 0, 1};
char c = 0;
for(int i = 0; i < 8; i++)
c += (bits[i] >> i); // 0 or 1 times 2 to the ith power
cout << c << endl; // should print out A
cin.get();
return 0;
}
Edit: I'm not near a compiler, so the bit-shifting operator may need to be switched but the logic is straightfoward.
Hopefully this helps! =)
-Alex
Alex Edwards 321 Posting Shark
You'll probably have to reposition your read-stream cursor after each object read, otherwise you won't retrieve the right byte value from the file to match the data type(s) for the Object you are creating.
Alex Edwards 321 Posting Shark
I'm not sure how you plan to pause a method from executing instructions within it without somehow pausing (or 'blocking') at a particular line in the method.
If you don't want to use a while loop, you can make a conditional clause where the loop sends its data to a Service object and places it in a Queue. When the JButton is called it will service the request and poll the Service object from the Queue. You can emulate this happening once per method call by making a condition such that when something is inside the queue, nothing in the method happens again until the Queue is empty (basically when the Queue is empty, the non-gui method does something (stores a service object in the queue) and when the Queue is full the non-gui method does nothing).
I'm assuming you don't want to halt your program, and you need something to happen in the future. If so, use a Queue system to Service the requests one at a time when needed.
Alex Edwards 321 Posting Shark
That means you are literally treating something that isn't an lValue as an lValue.
For example if a method doesn't return a reference to something, its possible that attempting to treat the method as an lvalue wont work since you're returning a copy of the actual object in which that copy may not be assigned to anything else...
It's actually hard for me to believe that you can't treat a temporary as an lValue considering potential chained = statements.
I believe this is an appropriate example--
( please excuse the code inlining - I'm in a hurry @_@ )
int method(){
return 9;
}
int& method2(int num){
return num;
}
int main(){
method() = 8; // should throw an error
int x = 10;
method2(x) = 5; // valid since the method returns a reference which can be assigned
a value
}
Edit: Actually its possible that primitive types, which aren't objects, will be the most likely to flag such an error. It's possible that the assignment operator isn't valid for 'const' or temporary types (which makes sense, otherwise you could change the value of the number 9 by assigning it 5 and get the value of 5 instead of 9 wen you need 9... that would be a pain @_@ )
-Alex
Alex Edwards 321 Posting Shark
>Deliberately crashing the kernel isn't funny
Does that mean accidently crashing it is? :)Hah :D , sorry, I coulden't help myself.
Rep-worthy! XD
It's too bad I can't give you any more rep today @_@
-Alex
Alex Edwards 321 Posting Shark
I don't know why... but I found the first post amusing XD
But I'm laughing with you Beast! I promise! O_O
-Alex
Alex Edwards 321 Posting Shark
It sounds like your on to something, only I don't know what it is your saying :(
What do you mean "pull in lines from target read file and store them in a stack<string>"? You mean write a "while" statement, assigning the value of all the information in the column to a string? Wouldn't that go against the idea of using an array?
And whats a "queue"?
My apologies.
Apparently I missed the portion of your first statement "I cannot use anything else, rules are rules." Please forget my previous comment.
Alex Edwards 321 Posting Shark
You may want to consider this process--
-Pull in lines from target read file and store them in a stack<string>
-pop strings from stack and write them to file
That's if the strings need to be listed in reverse order.
If you have to reverse the strings and list them the process can be done the same way except with a queue instead of a stack, and of course the queue would only store the reversed version of the string before writing to the file.
Hopefully this helps.
Alex Edwards 321 Posting Shark
Chances are likely that your Instructor wishes for both your getArms and getLegs methods to return an array of Limbs--
Arm[] getArms(){
return arms;
}
Leg[] getLegs(){
return legs;
}
-- however, something about the assignment suggests that your Human class doesn't simply hold an array of 2 arms and 2 legs, but instead a Limb array of 4 Limbs.
From there you would need to make create a Leg array and extract the instances of leg objects references from the Limb array and assign those references to the local array generated in getLegs. The same idea would hold true for getArms.
jasimp commented: This should hopefully give you four blocks of green :) +9
Alex Edwards 321 Posting Shark
What I was saying is that I don't understand most of that terminology, so the point alone has no impact. I hope I wasn't rude - I wasn't trying to be.
If you work in an environment similar to mine, you'll have people telling you to "GIYF!" quite a bit XD.
If there is a term you don't understand, you should definitely study it. I find it much easier to learn programming concepts after educating myself with terminology.
Not only that, but by understanding more terminology, you can come up with more meaningful definitions for words in code that you are planning to share with others that may work with you or will be the receiver of an implementation you designed when you hand off the code.
Wikipedia, Google and Dictionary are your ultimate programming friends, to say the least! O_O
Alex Edwards 321 Posting Shark
Reflection is a very specialized solution, much like the Java Native Interface, Remote-Method Invocation, Wildcards, Design Patterns, transient values, volatile values, concurrency, etc.
Don't expect simple solutions for something that is seemingly "simple."
Alex Edwards 321 Posting Shark
Is there any way that I can take a String and somehow use it as if its the name of one of my declared Objects? For example, if I have an Animal named germanShephard, is there some way I could say String gerSh = "germanShephard"; and then treat gerSh as if it was the equivalent of saying germanShephard in my program?
Dictionary is also an okay way to go, but I believe it is a deprecated API (or incredibly outdated).
Edit: Actually, you can probably get away with using a Pair<K, V> instead of something that handles an entire collection.
I'm not sure where it is defined in the Java Standard Library, but if all else fails you can easily create your own pair class.
Alex Edwards 321 Posting Shark
http://java.sun.com/javase/6/docs/api/java/math/BigInteger.html
import java.math.BigInteger;
public class TestingBigInteger{
public static void main(String... args){
BigInteger first = new BigInteger("50");
BigInteger second = new BigInteger(first.toString());
System.out.println(first);
System.out.println(second);
}
}
Have fun! =)
Alex Edwards 321 Posting Shark
In regards to the javadoc examples...
Did you remake some of the old API listings with new and improved ones that consist of examples of function usage? O_O
Even if it isn't you... it really must've taken said individual(s) quite some time @_@
Alex Edwards 321 Posting Shark
Here's something I managed to whip up thanks to your logic--
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::cin;
using std::endl;
using std::flush;
using std::string;
using std::vector;
bool isPalindrome(const string&);
const char* result(bool);
int main(){
vector<string> values;
values.push_back("mom");
values.push_back("ffaff");
values.push_back("dad");
values.push_back("nonPalindrome");
values.push_back("blah");
values.push_back("A");
values.push_back("");
for(vector<string>::iterator i = values.begin(); i != values.end(); i++)
cout << (*i) << " is a Palindrome? - " << result(isPalindrome((*i))) << endl;
cout << "\n\nEnter a word to be determined as a palindrome" << endl;
values[0].clear();
cin >> values[0];
cout << values[0] << " is a Palindrome? - " << result(isPalindrome(values[0])) << endl;
cin.ignore();
cin.get();
return 0;
}
/**
* Returns true if the argument string is a palindrome, returns false otherwise
*/
bool isPalindrome(const string& arg){
/*
* LOGIC:
* -If string length is 0 or 1
* -string is a palindrome, so return true
* -Else
* -If first and last indice of said string have the same char
* -generate a new string that is a substring of this string
* discluding the first and last indice of the previous string
* -Else
* -return false
*/
string temp (arg);
if(temp.length() == 0 || temp.length() == 1)
return true;
else{
if(temp[0] == temp[temp.length() - 1]){
string next = temp.substr(1, temp.length() - 2); // substring from indice 1 and up to (length() - 2) from 1
// i.e. - ffaff, f is at [1] and length is 5, so from 1 go up to 2+1
// because even though length() - …
Alex Edwards 321 Posting Shark
I thought I had the specs right until you said down-right instead of up-right in your 2nd paragraph.
Maybe a picture will be helpful?
Also, what are you using to graphically display your program? Is it a Console program or are you using some kind of GUI API? This question is merely out of curiosity.
Alex Edwards 321 Posting Shark
A lot of complicated terminology being thrown around here but a few points:
> A static member of a class is a shared location in memory between objects of that class.
Don't mix concepts and implementation details when explaining. From the JLS:
> static values are resolved at compile time, before objects are created.A compile time constant expression when assigned to a static field[or not] is evaluated at compile time; a static field is incarnated when the class is initialized. There is no *static value*.
> Notice that in main of a different class file, I didn't need to create an object of MyClass in
> order to access sharedInt - the address of the reference-variable sharedInt is resolved at
> Compile Time and all MyClass objects have access to it.`sharedInt' is a variable of Primitive Type and not Reference Type.
> If q is not a static member, then although each C class object has q, they have their own
> individual address for their reference variable and thereforeEach instance created has its own set of the state/member variables. There is no *individual address for their reference variables*.
> to access q you need to give a hint to the compiler (or runtime) of which particular C
> object you want to qualify q with to access the appropriate value of q for whatever
> purpose you need to access it forThere is no *hinting* or *forcing*; the …
Alex Edwards 321 Posting Shark
the variable q is not declared in the class A and I dont want to declare it. Is there anyway this can be done? I tried that and it says "non-static variable cannot be referenced from a static context" If also someone could share with me what this means. Thanks alot
static values are resolved at compile time, before objects are created.
A static member of a class is a shared location in memory between objects of that class.
Because static values are resolved at compile time before an object is created, and all objects of the class share the value, you have the right [with the appropriate access modifier] to access that shared address between objects of the class without needing an actual object to qualify the member to access the member.
For example...
public class MyClass{
static int sharedInt = 0; // package accessible for enclosing classes of MyClass
}
public class Main{
public static void main(String... args){
System.out.println(MyClass.sharedInt); // legal if class MyClass and Main are in the same package
}
}
Notice that in main of a different class file, I didn't need to create an object of MyClass in order to access sharedInt - the address of the reference-variable sharedInt is resolved at Compile Time and all MyClass objects have access to it.
When you call C.q the compiler is forced to believe q is a static member in class C, but if it does not see the static …
Alex Edwards 321 Posting Shark
It may be possible that Java won't support an image-type in future releases and therefore not provide Serialization support for it but that depends on what it is.
I remember getting warning pertaining to images of a specific class and that class might be the culprit but I can't completely confirm this @_@. It's just a possibility >_<
-Alex
Alex Edwards 321 Posting Shark
is there any advantage to placing it after main? I mean is there any particular reason why it would have been after?
I personally consider code in a Driver Program to be cleaner when the logic of main is known before anything else.
Also, function declarations make code more readable because you know of the functions that are in the program before they are defined (at least hopefully they are defined, otherwise its just unnecessary information).
Other than that, I'm not entirely sure. Though I do know that you don't have to declare a function elsewhere in the same file, you can do so in other files but it would require you to also tag on the word extern to your function declaration to send a flag to your compiler stating the function is defined in a separate file.
Alex Edwards 321 Posting Shark
void printmovie (movies_t movie);
Is a function declaration.
The definition exists elsewhere in the same file.
Short/Simple reason: C++ can be very linear. If you comment out the function declaration, you will get a compiler error. That is because the function printmovie is found after the definition of main, but main is evaluated first during parsing and the compiler wont find the definition of printmovie until after main ( in this case the compiler will most likely flag an error, but then again this is completely dependent on the settings of the compiler).
I'm sure there are some compilers that can be configured to evaluate a function call and determine if it exists somewhere in a document without a need to evaluate the function declaration first, but I have yet to see such a compiler and even if one did exist it would be poor programming practice to code around what one compiler would accept vs multiple popular and conforming compilers.
If you want to use the function printmovie without the declaration, you will have to place the definition of printmovie before main.
Alex Edwards 321 Posting Shark
In C++, you can declare a function, constructor, or operator to accept a type by reference and not value.
For example, the declaration of the function--
void foo(int);
--states that the function foo takes [a copy of] an integer and returns void.
So the following would be legal--
int main(){
foo(3); // legal
int x = 4;
foo(x); // legal
return 0;
}
--however, you could instead declare a foo to take a reference to an int instead--
void foo(int&);
-- which means foo takes [a reference of] an int and returns void. Before proceeding, let's think of what a reference is.
Reference(programming) - the underlying address of an object, or type.
Hmmm... what does that mean?
Ok, in English... let's say you live at a particular address. Your house sits on top of that address, so therefore in order to access your house I need only to know your address.
If, for example, I sent someone information that contained your address, that individual would know where the house is and be able to access it (well in reality that's a big maybe, but in programming that's true to a certain extent).
int main(){
// foo(3); // illegal, because '3' itself is not an address!
int x = 4;
foo(x); // legal, because the value x has an address and therefore can be passed by reference
return 0;
}
The real question is, what is the benefit of …
Alex Edwards 321 Posting Shark
You can't declare a method within another method O_O
You'll have to pull all of your other methods (add, subtract etc) outside of the definition of your simp method. Your simp method can have the logic of the continuous play, but it can't have method definitions >_<
-Alex
Alex Edwards 321 Posting Shark
[Linker error] undefined reference to `add()'
Can someone explain that a little? Do i need to include my code to help you guys explain? Thanks
It never hurts to include your code (provided it's not too long! O_O).
Just be sure to use code tags @_@
-Alex
Alex Edwards 321 Posting Shark
Hey, thanks, but from exam point of view, what shall i write True or False? From examples it is clear that surely we can add, but it's not recommended, isn't it? So shall i go with option "True"?
I don't believe Menus or certain 'Views' would be possible without some type of Composite structure, so a reference to a Collection (or more appropriately, a Composite) within a Collection is good for specific uses.
It's hard to argue what's right or wrong in the Exam perspective. It depends on how the question is worded.
But since you're just adding a reference to a Collection of the same type, you can think of it as a Composite List of some sort. I don't see any harm in it as long as the reference is set dynamically.
Alex Edwards 321 Posting Shark
Hi
I have come across a question in a collection which says:
One can add a reference of a collection to itself. Is it true or false?
I read the explanation that, we can add the reference to the collection to itself, but it results in the stack overflow of the JVM. Please people tell me what is the correct answer, i am confused because we can add the reference but we should not add it.
Please help me
Ok, let me see if I understand what you're asking.
Let's first determine what a collection is.
Collection (programming) - a structure that holds many objects of some type (in old versions of Java, collections stored arbitrary objects, and in new versions you can specify a Generic collection that is 'at least' the type specified).
Reference (programming) - An address of the underlying object.
So can we add a Reference of a Collection to a Collection? Sure you can. I believe that is called a composite structure, though I'm no professional so I could be wrong =P
/*Declare an ArrayList that can store Object references*/
ArrayList<Object> myArrayList = new ArrayList<Object>(0);
// ... some time later in code...
/*Adding the address of the ArrayList itself to itself*/
myArrayList.add(myArrayList);
--the only way you can make a collection overflow is if you are creating a custom collection and you attempt to declare a globally scoped Reference to a collection that is the same class (or …
Alex Edwards 321 Posting Shark
I'd like to apologize...
the previous example can be forgiven for not implementing Node deletion (since OP has it defined), but can't be forgiven for forgetting appropriate Node declarations in global scope of NodeType structs (in both classes).
This is a corrected version--
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
template<class ItemType>struct NodeType;
template<class ItemType>struct List;
template<> // specialization for chars
struct NodeType<char>{
char item;
NodeType<char> *next;
NodeType(char);
};
NodeType<char>::NodeType(char myItem) : next(0){
item = myItem;
}
template<> // specialization for chars
struct List<char>{
NodeType<char> *root;
List();
void add(char);
void viewAll();
};
List<char>::List() : root(0){}
void List<char>::add(char val){
if(root == NULL){
root = new NodeType<char>(val);
}else{
NodeType<char> *temp = root;
while(temp->next != NULL)temp = temp->next;
temp->next = new NodeType<char>(val);
}
}
void List<char>::viewAll(){
NodeType<char> *temp = root;
while(temp != NULL){
cout << temp->item << endl;
temp = temp->next;
}
}
template<class ItemType> // generalized for all other types
struct NodeType{
ItemType *item; // ptr to prevent "slicing", see Stanley B. Lippman's 'The C++ Object Model' for a thorough explanation
NodeType<ItemType> *next;
NodeType(ItemType&);
};
template<class ItemType>
NodeType<ItemType>::NodeType(ItemType& myItem) : next(0) {
item = &myItem;
}
template<class ItemType> // generalized for all other types
struct List{
NodeType<ItemType> *root;
List();
void add(ItemType&);
};
template<class ItemType>
List<ItemType>::List() : root(0){}
template<class ItemType>
void List<ItemType>::add(ItemType& val){
if(root == NULL){
root = new NodeType<ItemType>(val);
}else{
NodeType<ItemType> *temp = root;
while(temp->next != NULL)temp = temp->next;
temp->next = new NodeType<ItemType>(val);
}
}
class MyObject{
public:
const char *name;
MyObject(const char*);
};
MyObject::MyObject(const char * theName) …
Alex Edwards 321 Posting Shark
Please put code tags around your code.
Also, wouldn't it be easier to store the binary value you are computing in a string, inside your binary class ? And then just start at position starting point in the string and then scan for the next zero ?
That would be the ideal way, but also a lot slower.
Question for the original poster - what is a word? Is a word like the definition of a Windows WORD, or is it any 32bit (unsigned) int, or what exactly?
Also it looks like you're searching for the first 0 from the right (or from the "start") of the bitset.
I believe this will work for you O_O --
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <bits.h>
#include <cmath>
using namespace std;
// Print a number in binary:
class Bin{
public:
Bin(int num){
n = num;
}
friend ostream& operator<<(ostream& os, const Bin& b){
unsigned int bit = 1 << (sizeof(int)*CHAR_BIT - 1);
while (bit){
os << ((b.n & bit) ? 1 : 0);
bit >>= 1;
}
return os;
}
private:
int n;
};
unsigned int Scan0(unsigned int word, unsigned int startingBit);
int main(){
unsigned int i, x;
while (cin >> x){
cout << setw(10) << x << " base 10 = " << Bin(x) << " base 2" << endl;
for (i = 0; i < sizeof(unsigned int) * CHAR_BIT; ++i)
cout << "Scan0(x, " << setw(2) << i << ") = "
<< setw(2) << …
Alex Edwards 321 Posting Shark
You can't make a typedef out of an incomplete type, so the following would be illegal if NodeType is generalized--
typedef NodeType* NodePtr;
struct NodeType
{
ItemType item;
NodePtr next;
};
-- because templates of typedefs are illegal.
You would need to alter your struct to have a variable type, like such--
template<class ItemType>
struct NodeType{
ItemType* item;
NodeType* next;
};
--if your Node is declared outside of your List class.
If its outside your list class and you want to create NodeTypes that hold the same type as the list, you'll have to do something like this--
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
template<class ItemType>struct NodeType;
template<class ItemType>struct List;
template<> // specialization for chars
struct NodeType<char>{
char item;
NodeType *next;
NodeType(char);
};
NodeType<char>::NodeType(char myItem) : next(0){
item = myItem;
}
template<> // specialization for chars
struct List<char>{
NodeType<char> *root;
List();
void add(char);
void viewAll();
};
List<char>::List() : root(0){}
void List<char>::add(char val){
if(root == NULL){
root = new NodeType<char>(val);
}else{
NodeType<char> *temp = root;
while(temp->next != NULL)temp = temp->next;
temp->next = new NodeType<char>(val);
}
}
void List<char>::viewAll(){
NodeType<char> *temp = root;
while(temp != NULL){
cout << temp->item << endl;
temp = temp->next;
}
}
template<class ItemType> // generalized for all other types
struct NodeType{
ItemType *item; // ptr to prevent "slicing", see Stanley B. Lippman's 'The C++ Object Model' for a thorough explanation
NodeType *next;
NodeType(ItemType&);
};
template<class ItemType>
NodeType<ItemType>::NodeType(ItemType& myItem) : next(0) {
item = &myItem;
}
template<class ItemType> // generalized for …
Alex Edwards 321 Posting Shark
This managed to work for me--
import java.util.*;
public class TestClass1{
static String seatLayout = null;
static String fn = null;
public static void main(String... args){
System.out.println(showAllSeats("1294"));
}
public static String showAllSeats(String flightNumber){
fn = flightNumber;
// Make a set of arrays for each flight. This is only one flight. If the flightNumber is "1294" ...
if(fn.equalsIgnoreCase("1294")){
ArrayList<String> r1 = new ArrayList<String>();
r1.add("Row 1");
r1.add("_");
r1.add("_");
r1.add("_");
String row1 = r1.toString();
ArrayList<String> r2 = new ArrayList<String>();
r2.add("Row 2");
r2.add("_");
r2.add("_");
r2.add("_");
String row2 = r2.toString();
ArrayList<String> r3 = new ArrayList<String>();
r3.add("Row 3");
r3.add("_");
r3.add("_");
r3.add("_");
String row3 = r3.toString();
seatLayout = row1 + row2 + row3;
}
return seatLayout;
}
}
Tyster commented: Thanks for your help! +2
Alex Edwards 321 Posting Shark
You could use a State Machine, or State Pattern based on how many times an object has been encountered, or the State of an object can depend on the type of object it encounters...
It may simplify things, but only if you can work out the different possible states of objects.
I think this is the closest thing to a solution to your problem, though considering I know what you're trying to do, and State patterns can be bulky... it can be somewhat complicated @_@
I still struggle making State Patterns, unless I study the behavior between objects thoroughly. Below is just a sample program. a collides into b multiple times, and the behavior is different each time.
Of course this is just a test program, but the concept may be powerful enough to provide a solution to the problem O_O
/**
* Just testing the State Pattern =)
*/
public class TestingGrounds{
/**
* Interface for all Collidable objects
*/
interface Collidable{
public void collideInto(Collidable other); // collide into the object
public void react(Collidable theCollider); // triggered from another object
public void setState(SomeObjectState behavior); // set the behavior of the object
}
/**
* The State of SomeObject has the same exact interface as the Object itself
*/
abstract class SomeObjectState implements Collidable{
protected Collidable ref = null;
public SomeObjectState(Collidable ref){
this.ref = ref;
}
public void setState(SomeObjectState behavior){} // hook, States aren't meant to be composite @_@
}
/**
* The Normal State …
Alex Edwards 321 Posting Shark
Here's an example of encapsulating a 2D vector and emulating the behavior or a 2D vector through a class--
#include <iostream>
#include <vector>
#include <cmath>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::ostream;
using std::size_t;
class TwoDimensional{
vector<int> dummyVec;
vector< vector<int> > rowContent;
public:
TwoDimensional(unsigned int rowSize = 0, unsigned int columnSize = 0){
rowContent = vector< vector<int> >( static_cast<int>( pow(static_cast<double>(2), static_cast<double>(rowSize)) ),
vector<int>( static_cast<int>( pow(static_cast<double>(2), static_cast<double>(columnSize))), 0));
}
ostream& showDimensions(ostream& out = cout){
out << "Column Size: " << rowContent[0].size() << "\n";
out << "\nRow Size: " << rowContent.size();
return out;
}
ostream& showContents(ostream& out = cout){
for(size_t i = 0; i < rowContent.size(); i++){
for(size_t j = 0; j < rowContent[i].size(); j++){
out << rowContent[i][j] << " ";
}
out << endl;
}
return out;
}
vector<int>& operator[] (unsigned int indice){
if(indice >= 0 && indice < rowContent.size()){
return rowContent[indice];
}
return dummyVec;
}
};
int main(){
TwoDimensional td (2, 4); // 2^N rows, 2^T columns, in this case 2^2 rows, 2^4 columns
td[2][3] = 5;
td.showDimensions() << endl;
td.showContents();
cin.ignore();
cin.get();
return 0;
}
Alex Edwards 321 Posting Shark
>Is there a better way?
Yes, design the class hierarchy such that you don't need to know the dynamic type of the object. Perhaps some form of strategy pattern would clean up that selection code.
Would an Adapter be overkill?
I.E.
public class AdaptedA<T extends A> extends A{
private T myType = null;
public AdaptedA(T type){
myType = type;
}
T getType(){ return type; }
void performSpecializedOperation(Object parameters...){
// your if statements here...
}
}
public void foo(A object, Object parameters...){
if(object instanceof AdaptedA){
((AdaptedA)object).performSpecializedOperation(parameters);
}else{
// basic commands for A objects
}
}
The only advantage to this is centralizing the code in the Adapter class and not the method that handles A-types.
Hopefully this is reasonable @_@
Alex Edwards 321 Posting Shark
Bah, disregard this post >_<
public <T extends A> void doSomething(T type){
if(type instanceof [SpecialNeedClass]){
// typecast only for this type
}
// else if(...) // other specialized types
else{ // if no other specialized type, perform basic A operations
}
}
It would've been a good idea if Incomplete types were allowable in Java, but unfortunately Java isn't the same as C++ @_@
Alex Edwards 321 Posting Shark
Correct me if I'm wrong, but doesn't the cavet ^ symbol in C++.NET mean that the type is actually a pointer?
List1.Add(Vec1());
looks fishy... Vec1 is a pointer-type, so doesn't that mean you need to call gcnew to properly instantiate that Vec? O_O
List1.Add(gcnew Vec1());
I'd assume.
Alex Edwards 321 Posting Shark
I had to edit what you posted... the indentation got to me--
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <sstream>
using namespace std;
void getfile (ifstream&);
void input (ifstream&, int&, string*);
void write (int, string*, int*, string);
void createArray (string*, string*, int, int, string*, int&);
void run (int, string*, string*, int, int&);
bool check (string*, string*, int);
bool check2 (string*, string*, int, int, int);
void set (int*, int);
void createBit (string*, string*, int, int, int*);
void removeDup (string*, int);
void developArray (string*, string*, string*, int, int, int&, int*, int*, int*);
void intersect (int*, int*, int*, string*, string*, int);
main (){
int ALast, BLast, ABLast=1, x=0;
string letter[5] = {"A", "B", "AUB", "A^B", "A-B"};
int BitA[ABLast], BitB[ABLast], BitAUB[ABLast], BitAIB[ABLast];
string A[10], B[10], AB[20], AIB[20], A_B[20];
ifstream InData;
getfile (InData);
input (InData, ALast, A); // Puts the lines into an array
input (InData, BLast, B); // Puts the lines into an array
developArray (A, B, AB, ALast, BLast, ABLast, BitA, BitB, BitAUB);
set (BitAIB, ABLast);
intersect (BitA, BitB, BitAIB, AIB, AB, ABLast);
//print outputs
write (ABLast, A, BitA, letter[0]);
cout << endl;
write (ABLast, B, BitB, letter[1]);
cout << endl << endl << endl;
write (ABLast, AB, BitAUB, letter[2]);
write (ABLast, AIB, BitAIB, letter[3]);
cout << endl;
system ("pause");
return 0;
}
void getfile (ifstream& InData){// Gets the file from the user
string file;
cout << "Enter the name of the file: ";
cin >> file;
InData.open (file.c_str());
while(!InData){// Prompt for new file name if not able to open …
Alex Edwards 321 Posting Shark
Thank you for the reply,
but wrong way, I believe you're showing pushing an array of character strings into a vector<string>.
Regards.
Not quite. It would be valid if your array consisted of const char* values because strings accept const char* (and also chars) as a constructor argument via the ADT implementation in C++. Since the constructor of the string class isn't marked explicit, using const char* arguments where a string is expected will cause the compiler to generate a string object with the given const char* argument as a parameter for the constructor.
So during a push_back call using a const char* for a vector<string>, you will generate string objects to be stored inside the vector<string>
Alex Edwards 321 Posting Shark
I am working on a logger showing showing types and values for classes and sql statements (ie parameters in sql statements)
From the example above I will need to show output as something like
Long: null and BIGINT: nullWhat is a possible recommendation to be able to do this?
Should I create overloaded methods for each type or pass in the class at runtime? Any other suggestions are welcome and thanks for your help!!!
This might help--
public class NullTest{
public static void main(String... args){
Object obj = null;
System.out.println(determineNull(obj));
obj = new Object();
System.out.println(determineNull(obj));
}
private static String determineNull(Object o){
return (o == null) ? "Object is null": "Object is not null";
}
}
Alex Edwards 321 Posting Shark
Is there a reason you are using '/n' instead of '\n' ?
Also, is there a defined expression for a string being equivalent to a char? If not then you could try line != "\n" instead, though I don't mess with file I/O in C++ too much so I can't completely confirm this without a brief look-up =P
Edit: After looking here I realized that you might have to encapsulate the "\n" value in a string object before doing the comparison.
Alex Edwards 321 Posting Shark
I marked the Thread daemon as a good practice. Unfortunately it makes the example hard to see, the way the code is currently written. Consider this example instead--
import javax.swing.*;
public class NameSpaceClass001{
class A extends JPanel{
// blah... mumble...
private B myB = null;
public A(){
myB = new B(this);
Thread t = new Thread(myB);
t.setDaemon(true);
t.start();
}
public B getB(){
return myB;
}
}
class B implements Runnable{
private A panel = null;
public boolean running = true;
public B(A ref){
panel = ref;
}
public int safeWait(int seconds){
long l = System.currentTimeMillis(); // get current time
long next = l + (seconds * 1000); // get current time + future time
while(l < next) l = System.currentTimeMillis(); // wait specified seconds
return seconds;
}
@Override public void run(){
while(running){
System.out.println("Calling repaint after " + safeWait(3) + " seconds...");
panel.repaint();
}
}
}
public static void main(String... args){
NameSpaceClass001 nsc001 = new NameSpaceClass001();
NameSpaceClass001.A myA = nsc001.new A();
myA.getB().safeWait(15);
}
}
stephen84s commented: The good guy guiding everyone to the finish and ensuring people get there ;) +3
Alex Edwards 321 Posting Shark
Though Stephen has already pointed this out, you need to get rid of the access modifiers when declaring data types in your main method.
The reason is because it is irrelevant for a method to have access specifiers within its scope when you are declaring local variables that will not "escape" the scope of the method unless returned, and even so it would be a copy of that value (or a copy of a pointer) in which you will have access to it publicly.
Also consider the following--
import java.util.Scanner; //input scanner
public class Inventory001
{
// main method begin program execution
public static void main( String args[] )
{
String productName; // product name
double number; // product item number
double units; // number of units in stock
double price; // price per unit
double value; // total value of all units in stock
// scanner to obtain user input
Scanner input = new Scanner ( System.in );
Product001 p = null;
// scanner product object
{
// You need to specify 5 values for your constructor!
//p = new Product001(productName, number, units, price);
}
// value total of all units
{
System.out.printf(p.toString() );
}
} // end main method
} // end Inventory class
I attempted to fix your constructor problem, but I want you to think of a few reasons of why it is incorrect so that you wont make the same mistake again.
Alex Edwards 321 Posting Shark
I do not recall the arrow keys having a virtual key code associated with them from standard C++.
I think the only way to do it is through the OS interpretation of the virtual key code of the keyboard, though I could be wrong...
Alex Edwards 321 Posting Shark
Why exactly does class B have to extend A?
From an immediate glance I can see a potential cycle instantiation issue.
Think about it--
1) Class A, after static initialization, will instantiate a class B object--
2) Class B extends A, so when a B object is constructed, the super constructor of A is called but between that process the pre-initialization is done again leading back to step 1!
--which means that your program will cause new memory to be called and constructors to be (in theory) pushed on stack memory along with variables that are used within them, and additional growth of objects in the heap due to subsequent calls of new that are not resolved to make objects unreachable since there is a valid reference pointing to it.
What you want to do is something like this--
import javax.swing.*;
public class NameSpaceClass001{
class A extends JPanel{
// blah... mumble...
private B myB = null;
public A(){
myB = new B(this);
Thread t = new Thread(myB);
t.setDaemon(true);
t.start();
}
}
class B implements Runnable{
private A panel = null;
public boolean running = true;
public B(A ref){
panel = ref;
}
private int safeWait(int seconds){
long l = System.currentTimeMillis(); // get current time
long next = l + (seconds * 1000); // get current time + future time
while(l < next) l = System.currentTimeMillis(); // wait specified seconds
return seconds;
}
@Override public void run(){
while(running){
System.out.println("Calling repaint after " + safeWait(3) …