Perhaps:
char * str = "something"; std::cout << &str;
That would work, but here's a question for ya...
What about individual characters? Is it possible to get the address of those, or are char values stored in a special way?
Perhaps:
char * str = "something"; std::cout << &str;
That would work, but here's a question for ya...
What about individual characters? Is it possible to get the address of those, or are char values stored in a special way?
I was tinkering around with code in C++ last night trying to make a template algorithm that would be evaluated at compile time and also print information.
Unfortunately, because std::cout and std::cin are references to objects and they aren't considered built in types (directly at least), I suppose the compiler considers them variable and not a "constant expression," so statements like the following--
template<int N>
class PrintInfo{
enum {RESULT = ((std::cout << N << (N == 1) ? std::endl : std::flush ) , N) + PrintInfo<N-1>::RESULT};
};
template<>
class PrintInfo<0>{
enum {RESULT = 0};
};
--are unallowed.
The same problem occurs if I try to specify a reference (or pointer) argument to the template, as well as pointer to function... etc. Basically anything that cannot be resolved at compile time due to its chance to vary will be unworkable.
What I'd like is a way to print the information at compile-time. I know for a fact that if the compiler is capable of doing parsing and optimizations during compile-time, it can at least flag what it is doing (possibly) in the error-window.
I'm using Microsoft Visual 2005/2008 compiler, on Windows XP.
-Alex
you can also use String Tokenizer class.
Or not, because StringTokenizer is considered an Obsolete class that receives no further support in future releases.
Furthermore, String.split() is better because it takes regular expressions into consideration. StringTokenizer does not.
Strongly recommended books--
-Java, How To Program 7th edition (Deitel & Deitel)
-Head First Design Patterns
I suggest reading both in parallel. You will find both to be an easy read (in my opinion at least) until you get to harder concepts in the 16+ chapters of Deitel&Deitel book or occasionally in the Design Patterns book.
You'll, of course want to read Java, How To Program more often than Design Patterns (up to Inheritance/Polymorphism) then you may want to start reading Design Patterns.
How do you need your tokens to be parsed?
An example...
public class TokenMaster{
public static void main(String... args){
String myReallyBIGString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ\n"
+ "ALPHABETICAL!\n"
+ "SOMETIMES I FEEL I'VE GOT TO 'AH-AH' RUN AWAY, I'VE GOT TO... "
+ "'AH-AH' GET AWAY!!!\n"
+ "RING RING RING RING RING RING RING... BANANA PHONE! 'doot, doot doot doot doot doot'"
+ "DING-DONG DING-DONG DING-DONG DING... BANANA PHONNNNNE!!!!!";
String tokens[] = myReallyBIGString.split("\n"); // each token is determined by the newline character
for(String element : tokens)
System.out.println(element); // printing the individual tokens generated from String.split("\n")
System.out.println("\nTokens counted: " + tokens.length);
}
}
>>are STL containers faster then c-style arrays?
No. you can't get any faster access than c style arrays. But that isn't the point -- c++ STL eliminate many of the problems with c style arrays, such as dynamic array allocations. vector and other containers expand/contract by themselves, and they always know their size, unlike c style arrays.
Don't forget the Pattern-implementation of iterators too! They provide an interface for unrelated iterable types to be related.
no.
When will you ever say yes, or turn off your email blocking???
When will the madness stop???
=P
Are there any highly recommended books for file systems?
If so, I would appreciate a few titles to look into! =)
The purpose of doing this research is to further my understanding with programming. If I can better understand the File Allocation Table as well as other popular File-Systems today I think it will increase my understanding and bridge a few gaps that are still present.
I've tried Wikipedia, but some information is briefly touched and has me jumping around to different sources a bit too much. I'd like to have a concrete source of information I can read through and question.
Thank you!
-Alex
I can see a few ways of this being done...
First of all, why use an array?
You can easily use a LinkedList (and even a nested LinkedList) to get the job done. Chances are you'll only need a 1 LinkedList anyways.
For example, you can track time using a time implementation and generate a new node in your LinkedList for each incrementing hour. The currently farthest node from the root will be the one that records the information that's occurring currently.
You probably wont need to delete nodes in this case, but you'll need to delete information stored in one.
By the way, what have you started with?
...If you haven't already, I strongly suggest that you read Inside The C++ Object Model (by Stanley B. Lippman).
thanks alex edwards the character part is working along with no. of lines but the no. of words seems to give a wrong output.
can you guide me in that
thanks in advance
Personally I'd read all of the characters into a String then tokenize the String based on the space character.
Open a socket , read at server end , write at client end , you will not get a simple homework than this .
Pretty much, especially since the Client connects to the server at a different port (called the HandShake point) so that the Server can accept connections from other Clients.
Like previously stated, the static modifier allows Objects that consist of that static data type to share data from the same address.
One word of warning though - static variables are initialized once and only once! Not only that, but the scope of static is contained within the JVM it was declared in.
Here's an example of a static field being initialized once--
public class StaticTest{
// static member - initalized to zero once per definition
static byte timesCreated = 0;
// static context - happens once per JVM
static{
System.out.println("Time static block ran = " + (++timesCreated));
}
// static member - initalized to zero once per definition
static byte tC2 = 0;
// non-static context (each class gets its own one of these)
{
System.out.println("Times anonymous block ran = " + (++tC2));
}
public static void main(String... args){
new StaticTest(); // first object of type StaticTest created
new StaticTest(); // second " "
}
}
Actually .jsp files have html "code" inside them (the proper term is html tags). But with JSPs you can add java code inside them. For example calling a method to get in an array data from DB and displaying them:
<html> <head></head> <body> <% String [] array = getData(); %> <% for (int i=0;i<array.length;i++) { %> <!--HTML CODE HERE--> <h4> <%= array[i]%> </h4> <br> <% } %> </body> </html>
This is a poor example but the general idea is that if you want to develop a web application with java you will write jsp and you will need to learn HTML as well.
Write the code and create classes with java. Don't put "business" in jsp.
For example don't create connection to read from a database in a jsp.
Create classes that do what you want and then create the GUI (jsp/ html) and call those classes in the jsp in order just to display the results
I'm not sure if I agree with this 100%.
Can't you use NetBeans and generate a JSP designer (with the XHTML and Page-Bean implementation) and simply reference components using the Page-Bean?
You can also make HTML implementations in the XHTML page, but that's another story @_@
JSP/JSF is the way to go for this project!
The reason? It sounds to me like you're forming a front-end for Database management.
From what I understand, JSP has support for Database management, allowing one to make a visual representation of a database, though it isn't incredibly easy to implement.
This project could also be deployed as an Applet, though you would then have to learn about swing components (to a certain extent), and developing a back-end and front-end interface for the Database you wish to communicate with.
Either route will be tricky to tackle in a mere 15 days, though it's not entirely difficult so long as you and your team decide which route you will want to take soon.
Edit: Java has support for JSP, especially via NetBeans.
I glanced through your files ad noticed quite a few errors...
You initialize your "cube" char arrays in class-global scope (which, from what I understand is illegal in standard C++). You'll have to create temporary arrays in your constructor and copy their contents into your global arrays, or use a copy function in the STL if one's available, or better yet use a vector to prevent the headache of option a or b.
You need to separate your direction symbols when forming nested templates. >> will be parsed as the shift-bits right operation and not as the enclosing direction symbol for a nested template, so space it out!
Furthermore, your cube char arrays do not have characters stored in them. You need to wrap your char symbols inside ' ' so they will be read as characters.
The list goes on, but this should give you a reasonable start to get your program functional.
I'm not exactly savvy with pulling information from a URL in C++ but I did make a program in Java that generates a dictionary and sorts it for you.
If you have a JDK and your paths set right to compile this, then it may help you get a little over a thousand real words for you to use as a small yet sufficient dictionary to use in your project.
import java.io.*;
import java.util.*;
import java.net.*;
/**
* Goal - to retrieve information from URLs that are .txt files
*/
public class RetrieveInfo{
public static void main(String... args){
final String MY_DICTIONARY = "___MY_DICTIONARY.txt";
RetrieveInfo ri = new RetrieveInfo();
RetrieveInfo.Dictionary myD = ri.new Dictionary(MY_DICTIONARY, true);
String urls[] = {
"http://dictionary-thesaurus.com/wordlists/ActionWords(114).txt",
"http://dictionary-thesaurus.com/wordlists/Adjectives(50).txt",
"http://dictionary-thesaurus.com/wordlists/Consanants(120).txt",
"http://dictionary-thesaurus.com/wordlists/DescriptiveWords(86).txt",
"http://dictionary-thesaurus.com/wordlists/GRE_WordList(1264).txt"
};
RetrieveInfo.setDictionary(myD, urls);
myD.printList();
RetrieveInfo.sortDictionary(myD);
System.out.println("Task Completed...?");
}
public class Dictionary{
String fileName = "";
boolean append = false;
private ArrayList<String> wordList = new ArrayList<String>(0);
public Dictionary(String fileName, boolean append){
this.fileName = fileName;
this.append = append;
}
public boolean appending(){
return append;
}
public void store(String value){
wordList.add(value);
}
public String[] getItems(){
String arg[] = new String[wordList.size()];
return wordList.toArray(arg);
}
public void setList(String... values){
wordList.clear();
for(String element : values){
wordList.add(element);
}
}
public void printList(){
for(String element : wordList){
System.out.println(element);
}
}
@Override public String toString(){
return fileName;
}
}
public static void setDictionary(Dictionary d, String... urls){
try{
boolean existingFile = new File(d.toString()).exists();
if(existingFile){
System.out.println("File already exists! Enter yes to continue or anything else to …
I'm not exactly sure how your professor wants this done, but...
Personally what I'd do is make a topic for each game of Boggle and implement a dictionary of words then map out specific words to a specific topic (using a map most likely).
A random topic is chosen (or generated) and the a double array of characters will be generated.
There will also be a class that maps paths for characters (for a given topic, there will be a class that iterates through the entire mapping of characters and checks for potential words on the board)).
All the user has to do is enter the row/column of the starting char and the string resembling the actual word possible.
I believe this topic may also be of some help-- Click! O_O
The problem is that your Charact method is stuck in the while loop. You obtain the length of the file and state the conditon numChar != -1.
Keep in mind what data types are for. They store a copy of the data they accept.
Here you're calling f.length() and placing it in numChar (once). Though I'm not very savvy on files, from what I understand you are only storing the file's (current) length once in numChar which means that your while loop will either never execute or execute infinitely since numChar != -1 will be true or false and in your while loop you are not manipulating or changing the data stored in numChar to cause an escape from the loop... therefore an infinite loop.
long numChar = f.length();
int countChar =0;
while(numChar !=-1) // condition - will evaluate to true so long as numChar isn't -1
{
countChar++; // countChar changes, but numChar doesnt ^
}
I made this change and it seemed to work, though I'm not entirely sure it's what you wanted to do--
while(countChar < f.length()){
countChar++;
System.out.println("CharactWhileLoop");
}
Here's an idea...
Instead of buying Vista, wait until 2011 for Windows 7
I'd rather wait 3-5 years for a new OS than invest in one that will become yesterdays news fairly soon.
You need to think about what you want to use C++ for. I personally am interested in teh game development aspect of C++, but there are many other route C++ can tke you. so once you've made up you mind you should re ask your question with that in mind. in the mean time go pick up a good STL book and read up on that.
I strongly suggest the books that were recommended to me--
Starting out with C++, Early Objects
Effective/More Effective C++
Inside the C+ Object Model
C++ Templates
-- but they aren't oriented around game development. They're more-so general books for good C++ programming practices, etc.
It might also help if you gained a thorough understanding of objects, data and algorithms. I constantly find myself limited in capability due to the lack of understanding solid approaches to breaking and creating algorithms.
Just my opinion though - take it for however many grains of salt you wish =)
Typically when you overload something (a function for example), you're giving a new option as to how the client/programmer can use that function.
Polymorphism is slightly more difficult to describe. It's as if you're giving new meaning to an existing procedure in a way that is transparent to the client.
Note: Polymorphism is one of the big traits of Design Patterns, but not the only trait of course.
Is this the timer in swing or util?
If swing then you just need to place an if-else in the actionPerformed method that the timer is firing.
I'd use a circular (or random) iterator for the actions that you need to take place during calls to the actionPerformed method.
Errors 1, 2 (and most likely 3) are generated because third.getPages is being parsed as a variable that exists within the Class associated by the object third.
total=first.getPages()+ second.getPages()+ third.getPages; // missing parenthesis after getPages
Edit: 1-upping me, eh javaAddict? =P
Searchig engine of Google is suspected to do extrapollation based on his database ...
This has been proved with mathematical appliance on a website ...
So can I be called an agnostic if I don't believe in google ? ^^
I thought agnostic implied that one doesn't follow a religion, but that individual believes there is room (or chance) for something beyond us to exist?
A "Noncommittal Individual" to say the least.
If you don't believe in Google, but have reason to believe that there's a possibility it exists (as a godlike entity) then I suppose so... but really this topic is a joke I made up after elaborate discussions about google at work #_#
Yes... elaborate discussions about google at work...
Don't ask >_>
Have you even started?
A few ideas for your class that may help you get started--
*Implement a class that contains a pointer to the template-argument type
*Overload the ->, *, =, and [] operators
*The constructor should take a pointer to the template argument
*overload the << operator for the standard outputstream and your class to return the address of the encapsulated pointer
*Enable const version methods/operations such that the smart pointer is treated like a const smart pointer (and obviously a smart pointer to a const would have the const implemented in the template parameter).
*Make the destructor of the smart pointer properly deallocate memory for the pointer assigned to it (for simplicity assume all pointers are created via new, but if needed you can force your smart pointer to accept types that implement a common class with expected methods to determine if an object is created via new or not - this would take more knowledge of object creation though, via new). I'm sure a proficient C++ programmer knows of a better way around this #_#
For convenience, it may be helpful to have a string name() method and a std::size_t size() method for your smart pointer class.
I'm sure there are plenty of other ways to spiff up the class for convenience, but really all you need to do is think about the functionality of a pointer and how your class can emulate a smart pointer.
A religion typically consists of a being (or a collection of beings) that exists.
Google isn't exactly a being, but it does exist. Some people even consider it a godlike entity.
For a typical god, you provide a ritual or some kind of prayer. This prayer typically takes a long time, and may not be answered.
For Google, you insert your prayer in the search form and click search (or conveniently click enter) and your prayer is answered within seconds.
A typical god provides a blessing to an individual. That blessing depends on the mood of the god.
For Google, the blessing is straightforward. Need an image? Search images. Need a calculation done? Insert some numbers and a few code words (like mul I believe). Conversions are also done.
A typical god will have a place of prayer carved from the most devout believers to enable individuals with the same faith to pray to that god.
www.google.com is the temple of Google.
A typical god has a natural born enemy (such as Jehova and his brother lucifer, or Zeus and Hades, etc).
Yahoo! is the devil, and let me explain why.
Yahoo, sadly, is the default site an individual is directed to when they accidentally click on an email link.
Yahoo's chatrooms are crappy, buggy and full of 1337speakers who think they are the gods of the universe (which …
Hey thx heaps guys.
though i am still unsure about the subString.
i am only new to coding and are unsure on how the operation actually works.
could someone please expand on the notes given lolcheers
nate
The logic is pretty simple.
A subString suggests that the argument String is either the String or a "chunk" of the String the argument is matching against.
The first test is therefore to see if the argument is less than the String to be matched against. If that fails there's no point in going on.
Now you need to test the consecutive sequence of characters between a range of character within the String to be matched against. If that consecutive sequence of characters matches the consecutive sequence of characters of the argument char array, then the subString exists (and the method returns true).
If no matches were found for all ranges of a character index i to the end of the String, then there is no subString occurrence of the argument String.
There's also a safety net involved in my algorithm - basically if the range of Array1-i is less than the argument String that is matching against it then there's the risk of a null pointer exception when iterating through the indices of the argument array in comparison to a char-index of the String it is matching against to the length of the argument char-array.
That's about it.
I've always wondered how GObjects had such significantly improved pixel-rendering over objects sketched out by the Graphics object in paint and paintComponent methods.
What approach should I take to receive the same effect for big images that are say 1024x960, when using simple Graphics? Is there some way to traverse the rendering scheme with different threads to make the job done faster, or is there a way to make the pixels seem "permanent" like they do for GObjects?
Hopefully the question isn't too unclear. It's just annoying to always get a flashy screen or flashy objects when using sketches in a Component that isn't a GCanvas and I'd like to figure out the rendering secret.
Thanks!
Edit: Oh man, talk about being tired and making a topic... Emulting is supposed to be Emulating @_@
Not working can mean a lot of things, especially with relational databases.
Not working as in, you are running a version of Java that may or may not initially support jdbc (versions before 6 I believe) ?
Not working as in, the program wont compile?
Not working as in, the program doesn't work the way you want it to?
So much for telling us "here is the code.. but it is not working.. why?" - please be more elaborate!
suppose in abstact class "InputStream" we can implement method read(byte[]) with it's reference. how does this method is being refferred by it's abstract class as there will be no instantiation to this abstact class.
I'm not sure if I'm understanding the question.
Do you mean how are you able to call read from an object of type InputStream if you cannot directly instantiate one? If so then please re-read my post, this is mentioned in there.
If you mean extending the abstract class then using read, you will have to override the read method with your own implementation of read. Your concrete class that extends from the abstract class should not be marked abstract, so that you will be able to instantiate your concrete class and still have the functionality of the extending class. Read my above post thoroughly - this is also mentioned.
Also, this might help-- CLICK!
An interface is a static context template that classes can implement. The methods within the interface have no body and must be of public access.
In addition, interfaces can also contain "constants" in which data is declared and defined.
An example--
public interface MyInterface{
public final int VALUE = 100; // constant
public void doSomething(); // method declaration within interface
}
--when a class implements an interface, the class also implements the methods the interface contains. However, the implementing class MUST define the methods implemented.
An example--
public class MyTestClass implements MyInterface{
public void doSomething(){
System.out.println(VALUE);
}
}
--notice that the class MyTestClass doesn't declare VALUE however it is defined in the interface and therefore MyTestClass implements the public-accessible VALUE also.
An Abstract class is much like both a class AND an interface, however moreso a class.
An Abstract class has the potential to have default methods and interface-like methods where the methods MUST be defined by concrete subclasses that extend from the abstract class.
Furthermore, the concept of Abstract is "not fully defined" so in that respect, abstract classes cannot be instantiated.
An example--
public abstract class MyAbstractClass{
protected abstract void subCommand();
public final void templateMethod(){
System.out.println("Performing a defined command...");
subCommand();
System.out.println("SubCommand finished!");
}
}
--do not be distracted by the protected and final modifiers. The key focus is the abstract void subCommand method. Notice that an abstract class is like an interface in which it can …
Challenge: Implement a Dictionary/Thesaurus API, word-checking and a word-suggestion (after 3 characters) sub-menu below the current location of the user's cursor.
Note: Before reading below, please note that I'm no longer a Console Gamer. These are opinions based on my previous experiences with games on different platforms.
Keep that in mind before an attempt to flame.
Now then...
---------------------------
I'd play Goldeneye 007 or Perfect Dark on Nintendo 64 over Halo3 on XBox 360 (or any Halo) because the gameplay in Goldeneye/Perfect Dark is much better (and sometimes "better" means simpler), though this is a hard point to prove without being seemingly biased towards a console.
I also prefer Smash Brothers (regular) over Smash Brothers melee (which has better graphics), which also has crappy controls IMO and the creators went overboard with the implementation of playable characters (major redundancy... why do you need Dr. Mario, AND Mario for example?).
One major comparison, that I know I will most likely end up getting majorly flamed, is FF7 over FF8 (or FF7 compared to all other supposedly better FF's due to graphics).
FF7 is far, far more superior than most FF's after it due to its gameplay, storyline and music.
Why would I want to play FF8 with every hero from the same orphanage, craptacular music and with the potential of leveling to 99 by killing monsters in the same exact area over and over at the near-beginning of the game?
FF8 did yield better graphics, but look at the cost. Crappy gameplay was definitely one of the major costs.
Why do I …
Do you know if there is anything with eclipse and the classpath ?
Well, it was just a guess since you failed to actually post any code which would have made a better answer possible...
To say the least, please post your code so we can be of more help.
For simplicity, I helped a bit with subString, though I haven't tested it thoroughly enough to track if it will always be true. I did however provide an explanation on what was done to come up with a method solution--
/**
Hi there.
i am trying to create an java class dealing with arrays though i am only new to programming.
i have created a class with a char array field though i am not sure how to initialise it in the constructor.
i am also trying to implement a few methods though a couple i am lost on:
•print(). This method prints the string it represents to the console.
•concat().This method takes a char array as a parameter. It returns a new char array, which is the concatenation of MyString and the input char array. E.g. if MyString represents “Memorise “, and the input parameter represents the “syntax”. This method will return “Memorise syntax”.
•subString().This method takes a char array as parameter. It returns true if the input char array is a sub-string of MyString. Otherwise it returns false.
any help in any way would be greatly appreciated.
Cheers Nate
below is what i have got so far, (though not sure if right)
*/
public class MyString
{
private char[] Array1;
//public int length; // unnecessary
public MyString(char[] Array1)// my constructor though think i am way off
{
this.Array1 = Array1;
}
public MyString(){
this(new char[0]); // initializing a char array with no elements, but reference-variable is not …
There are a lot of questions...
First, will resizing the screen be an issue at all? If not then you could make a custom track using GeneralPath and Graphics2D fairly easily.
You could do so even with resizing but it would be a bit harder.
What error are you getting when you use g.fillRoundRect() ?
The list goes on =P
Why not g.fillOval()?
Also, will repainting be an issue? How much detail will be displayed on your screen? Are you at all using images?
A lot of questions come to mind since this seems like an interesting project.
For the sake of argument, assume that this is how an object of Base is represented internally:
Base::{ vptr | p }
And an object of Derived is represented like so:
Derived::{ Base::{ vptr | p } | q }
It's fair to say the cast will work, and the result will be polymorphic because taking memory originally mapped as Derived and treating it like it's Base will have the same net effect. The vptr is in the same place (but points to a different table), so accessing foo through p is safe and meaningful.
Now let's move on to a different implementation that places the base class subobject at the end of an object. Base would still look like this:
Base::{ vptr | p }
But Derived now looks like this:
Derived::{ q | Base::{ vptr | p } }
So what happens when memory originally mapped as Derived is accessed through a pointer to Base that assumes the offset of vptr is where q actually resides? q isn't a pointer to a virtual table, so any number of things could happen, but polymorphic behavior is unlikely.
It's time for me to purchase the C++ Object Model to better understand Objects and how the data is mapped so I'll avoid blind casts that will cause problems.
Thank you Professor.
@vijayan121 - Sorry for the ignorant reply. When I don't understand something and there's no obvious risk in front of me I tend to do experimentation and research later. If it were …
Derived d; Base *p = reinterpret_cast< Base*>(&d);
> I found that this is also legal--
it will compile.
it will work correctly if and only if the anonymous base class sub-object is at an offset of zero in the derived class object.do not get lulled into a false sense of security. a reinterpret_cast is a C++ cast. but that does not mean that it gives you any additional protection regarding correctness compared to a C style cast, or the union technique that you posted in another thread. for a reinterpret_cast too, you need to know precisely what you are doing. and as a programmer, you have to take responsibility for its correctness.
Yes I understand that. I ended up having to do some research on why the cast the OP mentioned was legal, and I admit I still do not understand.
Notice that my post states through experimentation, meaning that I was merely trying to see how the (Base*) cast might be interpreted by the compiler, though I admit I did forget that ( Base* ) is a C-style cast and that I do not understand the way the compiler interprets it.
i was thinking about the boolean thing, i wouldn't have thought of using a queue. really i want to make a keyboard controlled (haha) keyboard, like a simple piano app. so the boolean would probably be the best thing to use.
Oh that's easy.
Key pressed (and held down) automically set flag off and also set numbers to produce the sound of the key.
Key release set flag on.
this might be an option
public static void pauze(){ while(!isContinue()){ //keep the duration small, so the game will be resumed shortly after // the user presses resume sleep(500); } } public static boolean isContinue(){ boolean returnVal = false; // this method checks in the rest of your code, whether or not your user pressed resume //returnVal = .... return returnVal; }
That's a very expensive method call. Your primary thread operation will have to wait for the calculation of isContinue() if you were to do it that way.
You may instead want to have a set method that sets the boolean expression in the loop to false so that the process can stop when it is desired for it to stop.
You know, I tried to make up for my dumb response earlier by developing a meta-program for this algorithm to see if it would speed it up some.
I spent the last 2.5 hours doing tests on the std max, a macro max and my own definition of max. None worked so I thought that resorting to a templatized enumerated result would be more efficient but I can't spend more time on this at the moment.
Does n have to be a factor of 3, or is n just some arbitrary number?
Through experimentation, I found that this is also legal--
#include <iostream>
class Base
{
public:
virtual void fn(){std::cout<<"fn base\n" << std::endl;}
virtual void myfn(){std::cout<<"myfn base\n" << std::endl;}
};
class Derived : private Base
{
private:
void fn(){std::cout<<"der\n" << std::endl;}
void myfn(){std::cout<<"myfn Derived\n" << std::endl;}
};
int main(){
Derived d;
Base *p = reinterpret_cast< Base*>(&d);
p->fn();
p->myfn();
return 0;
}
Hmm I'd personally set a trigger/flag for when the Thread should execute the sound-producing algorithm (like a boolean that is controlled by a listener like a key listener, mouse listener or action listener).
Either that or you can implement a sound-Command pattern where Sound Commands are pushed into a queue and read only when they're needed (which is probably more ideal for producing music, but a bit harder).
This worked for me--
import javax.sound.sampled.*;
public class test_sound {
private class MyThread extends Thread{
int seconds = 1, sampleRate = 8000;
double frequency = 200.0;
public MyThread(){
}
public MyThread(int seconds, int sampleRate, double frequency){
this.seconds = seconds;
this.sampleRate = sampleRate;
this.frequency = frequency;
}
public void run(){
while(true){
//int seconds = 1 ;
//int sampleRate = 8000 ;
//double frequency = 200.0 ;
double RAD = 2.0 * Math.PI ;
try {
AudioFormat af = new AudioFormat ( ( float ) sampleRate , 8 , 1 ,
true , true ) ;
DataLine.Info info = new DataLine.Info ( SourceDataLine.class , af );
SourceDataLine source = (SourceDataLine)AudioSystem.getLine(info);
source.open ( af ) ;
source.start ( ) ;
byte [ ] buf = new byte [ sampleRate * seconds ] ;
for ( int i = 0 ; i < buf.length ; i ++ ) {
buf [ i ] = ( byte ) ( Math.sin ( RAD * frequency / sampleRate
* i ) * 127.0 );
}
source.write ( buf , 0 , buf.length ) ;
source.drain ( ) ;
source.stop ( ) ;
source.close ( ) ;
} catch ( Exception e ) {
System.out.println ( e ) ;
}
}
}
}
public static void main ( String [ ] args ) {
test_sound tc = new test_sound();
Thread m1 = tc.new MyThread(2, 7000, 400);
Thread m2 = tc.new MyThread(3, 6000, 350);
m1.start();
sleep(750);
m2.start();
joinAll(m1, m2);
}
private static void sleep(long milli){
try{
Thread.sleep(milli);
}catch(Exception …
A few questions...
First, why do you declare two arrays and define them full of spaces then iterate them through loops to assign space characters to them when they already have that value?
You can reduce code-bloat by simply instantiating your arrays to have 12x12 characters.
Furthermore the initial value of a character should be the space character, so there's no need to allocate a static built-in type to each indice of the double array.
An example--
public class InitializeArrayTest{
public static void main(String... args){
char[][] dCharArray = new char[12][]; // creating a double array with 12 array of unknown length
for(int i = 0; i < 12; i++){
dCharArray[i] = new char[12]; // allocating arrays of length 12 to the arrays of the double array
}
for(int i = 0; i < dCharArray.length; i++){ // the length (or amount) of arrays stored in dCharArray
for(int j = 0; j < dCharArray[i].length; j++){ // length of the array at location dCharArray[i]
System.out.print(""+dCharArray[i][j] + ','); // prints the value to the screen as a character
}
System.out.println(); // enters a new line
}
}
}
--also I can see a potential problem in this chunk of code--
//...
if (array1[i-1][j-1] == 'X') neighbors += 1; // what happens when i and j are 0? -1,-1 is out of bounds!
if (array1[i-1][j] == 'X') neighbors += 1; // i = 0, -1, 0, out of bounds!
if (array1[i-1][j+1] == 'X') neighbors += 1; // i = …
I think you may need to join the main program to your threads so that the main program waits for the threads to finish then exits.
import javax.sound.sampled.* ;
public class test {
public static void main ( String [ ] args ) {
Thread p1 = new Player ( ) ;
Thread p2 = new Player ( 1000.0 ) ;
p1.start ( ) ;
p2.start();
joinAll(p1, p2);
}
private static void joinAll(Thread... args){
for(Thread element : args)
element.join();
}
}
Why not encapsulate what produces the sound in a thread and execute multiple versions of the thread (where upon initialization, you specify a String for the file to read to get the .wav file to play)?
Edit: Oh I just noticed you're producing sound based on numbers and not a file. In that case I suppose number arguments in the constructor for the thread object, store them and use them for the thread to execute a different sound.