|
Hey all,
let me start off by saying that I'm not totally sure of whether or not I'm phrasing my question right, but here goes. I'm trying to make a trading card game, and I want to make it expandable (not to mention I don't want to hard code the cards into the game). I was brainstorming the best way to have different cards (represented as objects) and let them have different actions in their methods (for example, onPlay() and onDiscard() will have different implementations for different cards). What I want to be able to do is, on initiation, have the program load these cards into an array of AbstractCard (which all card objects will implement), from which the game can use as its database of cards. At first, I thought of storing the actions in a text file, and then having the card determine its action based on what was saved in the text file. However, I quickly realized how messy that would be, and had a different idea. Perhaps I could create a different class for each card, and compile them all separately and put them in a location on the hard drive. The program would then check that directory and load all the compiled classes it finds there, declare objects from them, and put them in the AbstractCard array (to me, this sounds similar to what a plug-in system does).
So, my question(s) is(are), is this a good way of going about this? If so, how should I implement it? With regards to the implementation, this sounds kind of like reflection, but I have no experience in that area and so am not sure how to go about doing that.
Thanks,
Chuck Murphy
|
|
|
|
|
Inheritance is your friend! This is the classic example of using it.
Start with your nice basic abstract class:
abstract class Card
{
private String description;
Card(String description)
{
this.description = description;
}
abstract void onPlay();
abstract void onDiscard();
}
Then for each type of card you need, have another class:
class RealCard extend Card
{
RealCard()
{
super("This is a real card");
}
void onPlay()
{
}
void onDiscard()
{
}
}
That is the better way to design things.
The second part of how to store the objects is covered by a simple enough idea - serialization. Get your card classes right and hard code them to start with, then worry about the persistaance; it should be relatively easy.
Panic, Chaos, Destruction.
My work here is done.
|
|
|
|
|
Well, you see, I'm already doing that, I'm just looking for how to offer users the ability to create their own cards and add them to the game, without needing to get the source, add some classes, and recompile the game. Also, assume here that these users are trusted, I know someone could stick some malicious code in one of these user-created cards if I follow this method
Here's some psuedo-code:
LinkedList<AbstractCard> lstAllCards = new LinkedList<AbstractCard>();
for each file in directory "user_cards/"
{
if file is a java class
{
AbstractCard newCard = file.instantiate()
lstAllCards.add(newCard);
}
}
From what I've read of reflection, the way to do this might be to try this:
AbstractCard newCard = Class.forName(fileName).newInstance();
Also, after reading this, I may want to have the card list be a LinkedList<Class>, not a LinkedList<AbstractCard>, so that I can instantiate new cards at will without having to refer back to these initial instances. Am I on the right track?
EDIT: angle brackets weren't showing up for the generics, replaced them with "& lt;" and "& gt";
|
|
|
|
|
I have searched high and low (and yes - even in the jCIFS library) on how to share a directory/folder in Java. I have seen it done in C# (the language I am more familiar with), but have not been able to figure out how to do it in Java. Please, Java experts please help me out and point me in the right direction!
|
|
|
|
|
I don't think you can because this is OS-specific behaviour. You could use JNI to call a Windows API or shell out to run NET SHARE, but I as far as I am aware you can't do it directly from within Java.
|
|
|
|
|
Oh no! Thank you so much for replying. The project I am working on has to work on multiple platforms (Window, Mac, Linux, Unix, etc).
I guess we might have to do it differently for each platform we connect to - I forgot to mention that I wanted to do it remotely. I am able to create a directory using the jCIFS library.
Do you know of a way to remotely determine what OS is running on machine we connect to - that is another issue I have yet to determine if is possible.
|
|
|
|
|
I'm working on a servelet project. I use database connection (jdbc odbc) when I try to access data into database, I get HTTP status 500 error
java.lang.NullPointerException
checkpps.doGet(checkpps.java:61)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
line 61 in my code is : statement = link.createStatement();
any body could help me please???
|
|
|
|
|
At the risk of stating the obvious, link is null. More than that I cannot say, because I don't know what link is or how you get hold of it.
|
|
|
|
|
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class checkpps extends HttpServlet{
private Statement statement;
private Connection link;
private String URL = "jdbc:odbc:quiz";
String name;
public void init() throws ServletException
{
super.init();
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
link = DriverManager.getConnection("jdbc:odbc:quiz","sara", "sara");
}
catch (ClassNotFoundException e1){
System.out.println("driver not found");
}
catch (SQLException e2){
System.out.println("error in connection");
}
}
public void doGet ( HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
res.setContentType ("text/html");
PrintWriter out= res.getWriter();
String city = req.getParameter("city");
String ppsnum = req.getParameter("ppsno");
try {
statement = link.createStatement();
ResultSet result = statement.executeQuery("SELECT * FROM player");
while(result.next())
{
out.println("<p>" + result.getString("ppsno"));
}
}
catch (SQLException e)
{
System.out.println("error statement");
}
}
public void destroy()
{
try {
link.close();
}
catch (Exception e) {
System.out.println("error on closing!!");
e.printStackTrace();
System.exit(1);
}
}
}
as you see in my code, I'm trying to connect to database (MS Access) and link is my connection name. seems my connection has problem for some reason but still couldn't solve it. I have created DSN by the way.
any help?
modified on Wednesday, November 11, 2009 8:51 AM
|
|
|
|
|
Which MSOffice you are using. And r you sure that you have selected the correct driver type.
|
|
|
|
|
Hey Everyone
I am learning Java and would like to know how to get started on writing a piece of code that takes a collection of objects (which are answers from a form) and save it in a file (xml or .txt)
the FORM can be design from any visual editor (Flex, SWING, HTML, JSP etc...)
but once the form has been filled out, I want to save all the answers in a xml or .txt file
Any help would be greatly appreciated
thanks
|
|
|
|
|
public void saveAnswers()
{
try
{
FileWriter fw = new FileWriter("Questions.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println(textBox1.getText());
pw.println(textBox2.getText());
pw.println(textBox3.getText());
pw.println(textBox4.getText());
pw.flush();
}
}catch(Exception e)
{
System.out.println(e);
}
}
|
|
|
|
|
Hi all,
Actually, i have developed a java application that connects with Ms Access database. now i want to deploy this application. is there a way i can bundle my database inside the jar. if not please suggest some appropriate way ( a step by step procedure)
thanx
regards
Adeel
|
|
|
|
|
Is there a Java validator out there that can validate against the proposed W3C XSD v1.1 specification? I am currently validating against an XSD v1.0, but would like to add a number of assert statements and conditional attributes. If it helps, my current validation against XSD v1.0 is performed as follows (assume xsdFullPath and xmlFullPath are already defined):
parserFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
parserFactory.setNamespaceAware(true);
parserFactory.setXIncludeAware( true);
parserFactory.setFeature('http://apache.org/xml/features/xinclude/fixup-base-uris',false);
parserFactory.setFeature('http://apache.org/xml/features/xinclude/fixup-language' ,false);
parser = parserFactory.newDocumentBuilder();
parser.setErrorHandler(org.xml.sax.helpers.DefaultHandler());
document = parser.parse(xmlFullPath);
xmldom = javax.xml.transform.dom.DOMSource(document);
factory = javax.xml.validation.SchemaFactory.newInstance(...
javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
schemaFile = javax.xml.transform.stream.StreamSource(xsdFullPath);
schema = factory.newSchema(schemaFile);
validator = schema.newValidator();
validator.validate(xmldom); Thanks,
Sounds like somebody's got a case of the Mondays
-Jeff
|
|
|
|
|
I have a simple question, I developed a java application, which runs on Oracle application server and Oracle database. This application depends on multiple JSPs on which multiple users can access a single JSP in the same time, some problems occurs due to the excessive usage of this application and I have some questions about them:
1. Is there any danger or disadvantages in connecting to the database using the jdbc directly from the JSP ?!!
2. An error occurs almost once a week (most probably at the point of time when an excessive usage happens). This error stops the users from submitting or accessing the some JSPs. I ran the following query on the DB to find any locked items:
SELECT o.owner, o.object_name, o.object_type, o.last_ddl_time, o.status,l.session_id, l.oracle_username, l.locked_mode
FROM dba_objects o, gv$locked_object l
WHERE o.object_id = l.object_id;
I found that the table I use to select from in the halted JSPs is a result of this query.
In order to solve this problem temporarily, i use the sql developer to add a record to this table and commit, i find that the problem is solved and the halted jsps involved are running.
These are the exceptions that appears in the log files of the application server right after I press commit:
a.java.lang.IllegalStateException: Session was invalidated (all the time)
b.java.sql.SQLException: Closed Connection (some times)
I do not know exactly where to start debugging, since i use synchronization in all of my code. Also I made sure that each user accessing the same JSP has a separate connection.
Thanks in advance
|
|
|
|
|
Errors im getting:
cannot find symbol constructor method Token. but i do have a constructor in Token class
cannot find symbol variable tokenCode. i clearly use it alll over and i think i initialized it properly so whats wrong?
cannot find symbol variable scantest.i have that in same folder where all classes are in why wont it read it?
scanner class in which i need help fixing the above errors
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.*;
public class scanner implements CompilerConstants {
private char c;
private BufferedReader source;
public int token;
private String attr = "";
private
public scanner(BufferedReader buffer) {
source = buffer;
getChar();
}
public void getChar()
{
c = (char)(source.read());
}
public boolean lookup(String word)
{
boolean check = false;
for(int i=0; i < RESERVEDWORD.length;i++)
if(word==(RESERVEDWORD[i]))
{
check = true;
}
return check;
}
public Token nextToken() throws IOException
{
attr = "";
while(c!=EOFCHAR);
{
while (Character.isWhitespace(c))
{
getChar();
}
if (Character.isLetter(c))
{
while(Character.isLetterOrDigit(c))
{
attr = attr + c;
getChar();
}
return new Token(lookup(attr), attr);
}
else if (Character.isDigit(c)) {
while(Character.isDigit(c))
{
attr = attr + c;
getChar();
}
return new Token(NUMBER, attr);
}
else {
switch (c) {
case '<' : getChar();
if(c=='>')
{
getChar();
return new Token(NE, null);
}
else if (c=='=')
{
getChar();
return new Token(LE, null);
}
return new Token(LT, null);
case '>' : getChar();
if(c=='<')
{
getChar();
return new Token(NE, null);
}
else if (c=='=')
{
getChar();
return new Token(GE, null);
}
return new Token(GT, null);
case '=' : getChar();
return new Token(EQ, null);
case '|' : getChar();
return new Token(OR, null);
case '+' : getChar();
return new Token(PLUS, null);
case '-' : getChar();
return new Token(MINUS, null);
case '*' : getChar();
return new Token(TIMES, null);
case '/' : getChar();
return new Token(DIVIDE, null);
case '[' : getChar();
return new Token(LEFTSQ, null);
case ']' : getChar();
return new Token(RIGHTSQ, null);
case '(' : getChar();
return new Token(LEFTPAREN, null);
case ')' : getChar();
return new Token(RIGHTPAREN, null);
case ',' : getChar();
return new Token(COMMA, null);
case EOFCHAR : getChar();
return new Token(EOF, null);
}
}
return Token(tokenCode, attr);
}
}
public static void main(String[] args)
{
BufferedReader source = new BufferedReader(new FileReader(scantest.echo));
}
}
Token class
public class Token implements CompilerConstants {
private int tokenCode;
private String attribute;
public Token(int tc, String att)
{
tokenCode = tc;
attribute = att;
}
public int getToken()
{
return tokenCode;
}
public String tokenAttribute()
{
return attribute;
}
public String toString(){
String tokenString = tokenCode + " ";
switch (tokenCode) { case AND: return (tokenString + "/n AND");
case IDENTIFIER: return (tokenString + "/n IDENTIFIER" + attribute);
case OR: return (tokenString + "/n OR");
case NOT: return (tokenString + "/n NOT");
case ARRAY: return (tokenString + "/n ARRAY");
case BEGIN: return (tokenString + "/n BEGIN ");
case BOOLEAN: return (tokenString + "/n BOOLEAN ");
case DO: return (tokenString + "/n DO ");
case ELSE: return (tokenString + "/n ELSE");
case END: return (tokenString + "/n END");
case FOR: return (tokenString + "/n FOR");
case FROM: return (tokenString + "/n FROM");
case IF: return (tokenString + "/n IF");
case INTEGER: return (tokenString + "/n INTEGER");
case PROCEDURE: return (tokenString + "/n PROCEDURE");
case PROGRAM: return (tokenString + "/n PROGAM");
case READ: return (tokenString + "/n READ");
case START: return (tokenString + "/n START");
case THEN: return (tokenString + "/n THEN");
case TO: return (tokenString + "/n TO");
case TRUE: return (tokenString + "/n TRUE");
case WHILE: return (tokenString + "/n WHILE");
case WRITE: return (tokenString + "/n WRITE");
case WRITELN: return (tokenString + "/n WRITELN");
case NUMBER: return (tokenString + "/n NUMBER" + attribute);
case STRING: return (tokenString + "/n STRING" + attribute);
case LT: return (tokenString + "/n LT");
case LE: return (tokenString + "/n LE");
case GT: return (tokenString + "/n GT");
case GE: return (tokenString + "/n GE");
case EQ: return (tokenString + "/n EQ");
case NE: return (tokenString + "/n NE");
case PLUS: return (tokenString + "/n PLUS");
case MINUS: return (tokenString + "/n MINUS");
case TIMES: return (tokenString + "/n TIMES");
case DIVIDE: return (tokenString + "/n DIVIDE");
case LEFTSQ: return (tokenString + "/n LEFTSQ");
case RIGHTSQ: return (tokenString + "/n RIGHTSQ");
case LEFTPAREN: return (tokenString + "/n LEFTPAREN");
case COLONEQUAL: return (tokenString + "/n COLONEQUAL");
case COMMA: return (tokenString + "/n COMMA");
case EOF: return (tokenString + "/n EOF");
}
return tokenString;
}
}
CompilerConstants class
public interface CompilerConstants {
public static final int AND = 1;
public static final int ARRAY = 2;
public static final int BEGIN = 3;
public static final int BOOLEAN = 4;
public static final int DO = 5;
public static final int ELSE = 6;
public static final int END = 7;
public static final int FALSE = 8;
public static final int FOR = 9;
public static final int FROM = 10;
public static final int IF = 11;
public static final int INTEGER = 12;
public static final int NOT = 13;
public static final int OR = 14;
public static final int PROCEDURE = 15;
public static final int PROGRAM = 16;
public static final int READ = 17;
public static final int START = 18;
public static final int THEN = 19;
public static final int TO = 20;
public static final int TRUE = 21;
public static final int WHILE = 22;
public static final int WRITE = 23;
public static final int WRITELN = 24;
public static final int IDENTIFIER = 30;
public static final int NUMBER = 31;
public static final int STRING = 32;
public static final int LT = 33;
public static final int LE = 34;
public static final int GT = 35;
public static final int GE = 36;
public static final int EQ = 37;
public static final int NE = 38;
public static final int PLUS = 39;
public static final int MINUS = 40;
public static final int TIMES = 41;
public static final int DIVIDE = 42;
public static final int LEFTSQ = 43;
public static final int RIGHTSQ = 44;
public static final int LEFTPAREN = 45;
public static final int RIGHTPAREN = 46;
public static final int COLONEQUAL = 47;
public static final int COMMA = 48;
public static final int EOF = 99;
public static final char EOFCHAR = (char)(-1);
public static final String[] RESERVEDWORD = {"","and","array","begin","boolean",
"do","else","end","false","for","from","if","integer","not","or",
"procedure","program","read","start","then","to","true","while",
"write","writeln"};
public static final boolean DEBUG = true;
}
|
|
|
|
|
Here goes error by error:
symbol : constructor Token(boolean,java.lang.String)
location: class Token
return new Token(lookup(attr), attr);
The constructor for Token has the signature Token(int, java.lang.String) . Your code for lookup returns a boolean .
symbol : variable tokenCode
location: class scanner
return Token(tokenCode, attr);
It's amazing that a private member variable from a different class is inaccessable. Yes, tokenCode is never declared in the class scanner . BTW it would be better to rename the class to Scanner ; naming conventions and all that.
symbol : variable scantest
location: class scanner
BufferedReader source = new BufferedReader(new FileReader(scantest.echo));
What is scantest ? If it should be a variable declare it, if it's a static class then it doesn't appear to be a part of the project.
I found all your errors just by reading the post, I didn't compile it. Subsequently I copied into a netbean project and built to check I was right. Which I am.
Panic, Chaos, Destruction.
My work here is done.
|
|
|
|
|
Thanks i fixed my errors. Do you know how it would be a good way to start a parser class that will work with my code?
This is what i have so far
public class Parser implements Scanner {
public Parser() {
}
public int match(expectedToken)
{
if(Token = expectedToken)
{
nextToken()
}
else if(Token != expectedToken)
{
}
break;
}
public static void type() throws IOException
{
debugStart(type);
simpleType();
if(Token, tokenCode==ARRAY)
{
match(ARRAY);
match (LEFTSQ);
match (RIGHTSQ);
match(NUMBER);
}
debugEnd(type);
}
}
modified on Tuesday, November 10, 2009 3:58 PM
|
|
|
|
|
import java.util.Random;
/**
* Write a description of class PokerHand here.
*
* @author David Singleton
* @version 11/08/09
*/
public class PokerHand
{
public PokerHand()
{
this.arrDeck = new int[5];
// this.hand = new int[5];
//
}
// private ArrayList<string> coins;
public static void main(String[] args)
{
}
public boolean haveCard(int cardValue)
{
// Visit each array box and compare card to the number in the box
// If the card martches the array box value then return true
// If the card does not match any array values in the entire array then
// return false.
// Use a while loop to visit each array box
if(arrDeck.length > 0)
{
for (int i=0; i < this.arrDeck.length; ++i)
{
if (this.arrDeck[i] == cardValue)
{
return true;
}
return false;
}
}
public void displayCards()
{
System.out.println("The Card Values Are: ");
for(int i=0; i<=arrDeck.length; i++)
{
System.out.println(arrDeck[i] +"/n");
}
}
public void dealCards(boolean inHand)
{
// syntax error "illegal start of expression"
// public int randomPokerCard()
Random randomGenerator = new Random();
int randomInt = 0;
for(int i = 0; i
|
|
|
|
|
sweetbab wrote: PokerHand class can someone help me solve this code?
Solve what exactly? You need to explain what this is supposed to do, and what errors are occurring.
[edit]I notice that main() does not actually do anything!
The variable arrDeck is not declared anywhere.
The statement for(int i = 0; i { has obviously been pasted incorrectly, so I'm not sure what the test or termination parts should be.
I would suggest you correct these errors and repost your question with some more detail.
[/edit]
modified on Sunday, November 8, 2009 7:14 AM
|
|
|
|
|
Hi everybody,
I am doing an application using java.It requires a module to send sms to people concerned. So kindly give or help me with the algorithm or coding to send sms from computer.
Thank you.
|
|
|
|
|
Implementing this should be easier Youtube[^]. Before you ask how to send an email look in this forum you will find the answer.
|
|
|
|
|
this is the code i have. when i run this applet, it doesn't do anything!
[quote]
//Ravi Shah
//Assignment 7: Java applet for a small airline company
//to make reservations.
//CIS 226
//11/05/09
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Air_Reservation extends JApplet implements ActionListener
{
boolean seats[];
JButton FirstClassButton;
JButton EconomyButton;
JTextField BoardingPassField;
public Air_Reservation()
{
seats = new boolean[1];
}
public void init()
{
Container container = getContentPane();
container.setLayout(new FlowLayout());
FirstClassButton = new JButton("First Class");
FirstClassButton.addActionListener(this);
container.add(FirstClassButton);
EconomyButton = new JButton("Economy");
EconomyButton.addActionListener(this);
container.add(EconomyButton);
BoardingPassField = new JTextField(20);
BoardingPassField.setEditable(false);
container.add(BoardingPassField);
}
public void actionPerformed1(ActionEvent actionEvent)
{
boolean FirstClass = actionEvent.getSource() == FirstClassButton;
int seat = 0;
if(seat == -1 )
{
String ok = JOptionPane.showInputDialog(null, (new StringBuilder("Are you OK with ")).append(FirstClass ? "Economy" : "FirstClass").append(" (click OK or Cancel)").toString());
if(ok != null)
{
FirstClass = !FirstClass;
}
}
if(seat > 0)
{
BoardingPassField.setText((new StringBuilder("Boarding Pass: Seat ")).append(seats).append(FirstClass ? " FirstClass" : " Economy").toString());
} else
if(seat < -1)
{
BoardingPassField.setText("Next flight leaves in 3 hours");
} else
{
BoardingPassField.setText("All the seats have been reserved");
EconomyButton.setEnabled(false);
}
}
public int reserve(boolean firstClass)
{
int start = 1;
int end = 5;
boolean full = false;
if(firstClass)
{
start = 6;
end = 10;
}
for(int i = 1; i <= 10; i++)
{
if(i >= start && i <= end)
{
seats[i] = true;
return i;
}
}
return end;
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
[/quote]
|
|
|
|
|
Programmers are really amazing!
|
|
|
|
|
I think you are in the wrong place
|
|
|
|
|