PDA

View Full Version : Inserting Record into MySQL table using Java


UrbanTwitch
09-24-2009, 10:23 PM
Hi, I'm back!

code:
package mysqlconnection;

import java.sql.*;
import java.util.*;

public class dan {

public static void main(String[] args)throws Exception{
Class.forName("com.mysql.jdbc.Driver");

Properties props = new Properties();
props.put("user", "root");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/crafthub", props);

Statement stmt = connection.createStatement();

String sql = "INSERT INTO members (username, email) " +
"VALUES ('Foo Bar', 'Some Street')";

stmt.execute(sql);


PreparedStatement statement = con.prepareStatement(
"select * from members");

ResultSet result = statement.executeQuery();
while(result.next()) {
System.out.println(result.getString(2));
}

}

}

When I try to compile it.. I get this error:
C:\mysqlconnection\dan.java:14: cannot find symbol
symbol : variable connection
location: class mysqlconnection.dan
Statement stmt = connection.createStatement();
^
1 error

What's wrong? :S

jolly_nikki
09-25-2009, 12:32 AM
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/crafthub", props);

Statement stmt = connection.createStatement();


You have declared Connection object as con and not connection. So use

Statement stmt = con.createStatement();

ckeyrouz
09-25-2009, 12:42 AM
Hi again.

There is another error in your code.
When you need to execute a query to retrieve data you use the stmt.execute(query);

But if you need to add or modify or delete you use the stmt.executeUpate(query);

So you need to replace this line:
stmt.execute(sql);


with this line:
stmt.executeUpdate(sql);

UrbanTwitch
09-25-2009, 01:16 AM
When I try to compile.. I get this error:
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\>set CLASSPATH=%CLASSPATH%;C:\mysql-connector-java-5.1.9\mysql-connector-java
-5.1.9-bin.jar;

C:\>java mysqlconnection.dan
Guard
aaa

C:\>javac -cp C:\mysql-connector-java-5.1.9\mysql-connector-java-5.1.9-bin.jar
mysqlconnection\dan.java
mysqlconnection\dan.java:15: cannot find symbol
symbol : method updateStatement()
location: interface java.sql.Connection
Statement stmt = con.updateStatement();
^
1 error

C:\>

Current code:
package mysqlconnection;

import java.sql.*;
import java.util.*;

public class dan {

public static void main(String[] args)throws Exception{
Class.forName("com.mysql.jdbc.Driver");

Properties props = new Properties();
props.put("user", "root");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/crafthub", props);

Statement stmt = con.updateStatement();

String sql = "INSERT INTO members (username, email) " +
"VALUES ('Foo Bar', 'Some Street')";

stmt.executeUpdate(sql);


PreparedStatement statement = con.prepareStatement(
"select * from members");

ResultSet result = statement.executeQuery();
while(result.next()) {
System.out.println(result.getString(2));
}

}

}

Ack.. :\

ckeyrouz
09-25-2009, 01:18 AM
There is nothing in java named updateStatement();

replace this line:
Statement stmt = con.updateStatement();

with this line:
Statement stmt = con.createStatement();

UrbanTwitch
09-25-2009, 01:22 AM
It works! :D

But I get this error:

C:\>java mysqlconnection.dan
Exception in thread "main" java.sql.SQLException: Field 'ip' doesn't have a defa
ult value
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3558)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3490)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2109)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2637)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1647)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1566)
at mysqlconnection.dan.main(dan.java:20)

C:\>

The thing is I only want to insert data into TWO tables and leave the rest blank.. :\
package mysqlconnection;

import java.sql.*;
import java.util.*;

public class dan {

public static void main(String[] args)throws Exception{
Class.forName("com.mysql.jdbc.Driver");

Properties props = new Properties();
props.put("user", "root");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/crafthub", props);

Statement stmt = con.createStatement();

String sql = "INSERT INTO members (username, email) " +
"VALUES ('Foo Bar', 'Some Street')";

stmt.executeUpdate(sql);


PreparedStatement statement = con.prepareStatement(
"select * from members");

ResultSet result = statement.executeQuery();
while(result.next()) {
System.out.println(result.getString(2));
}

}

}

ckeyrouz
09-25-2009, 01:26 AM
It seems you have a field in the table members named ip.

It seems as well that this field is not null.

It seems as well that you have not set a default value.

So you should add it in the query as well like this:
String sql = "INSERT INTO members (username, email,ip) " +
"VALUES ('Foo Bar', 'Some Street','192.168.1.1')";

UrbanTwitch
09-25-2009, 01:29 AM
The same thing happened for bmonth, bday... basically its GOING to happen for all of the tables which have default set to NONE. :\

I guess I gotta fill ALL of the tables or something?

ckeyrouz
09-25-2009, 01:31 AM
Not for the fields that have default set to NONE, but for the fields that are allow null = false and they have the default set to none.

In other terms, for all the obligatory fields that have no default value you will get the same error.

UrbanTwitch
09-25-2009, 01:34 AM
So... null should be yes?

ckeyrouz
09-25-2009, 01:44 AM
depends on the business need.

But now to make your code work, put them to null yes.

UrbanTwitch
09-25-2009, 01:46 AM
OK thank you.
You, sir, are amazing.

Alright now, here is my code...
/**
DUNGEON CRAWL PROJECT
Programmer: Dan Jasnowski
Date: 9.24.2009
**/

import java.util.*;
import java.io.*;
import java.util.Date;
import java.util.Random;


public class game {
public static void main(String args[]) {

String name;

BufferedReader reader;


reader = new BufferedReader(new InputStreamReader
(System.in));
System.out.println("Welcome to...");
System.out.println("___ ___ _ _ _ ");
System.out.println("| \\/ | | | (_) | ");
System.out.println("| . . |_ _ ___| |_ _| | __");
System.out.println("| |\\/| | | | / __| __| | |/ /");
System.out.println("| | | | |_| \\__ \\ |_| | < ");
System.out.println("\\_| |_/\\__, |___/\\__|_|_|\\_\\");
System.out.println(" __/ | ");
System.out.println(" |___/ ");
System.out.println("What is your name?");

try{

name = reader.readLine();

//print the data entered by the user
System.out.println("Welcome to Mystik, " + name +". Your new adventure is about to unfold. \nPlease select a class.");

Random randomGenerator = new Random();

for (int idx = 1; idx <= 1; ++idx){
int randomInt = randomGenerator.nextInt(100);
log("Generated : " + randomInt);
}



}




catch (IOException ioe){

System.out.println("An unexpected error occured.");

}



}
private static void log(String aMessage){
System.out.println(aMessage);
}

}

Is there an EASIER more simpler way to generate a random number (from a range possibly?) and also... how do I check what a user types? Like if they typed... play then go to case play.. or typed fight then go to case fight

Get what I mean?

ckeyrouz
09-25-2009, 02:14 AM
Take a look at the scanner class:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html

and the Random class:
http://java.sun.com/j2se/1.4.2/docs/api/java/util/Random.html

There are all your answers.

Try to work a bit on them, post the code you get to and I will help.

UrbanTwitch
09-25-2009, 03:19 AM
ok, hold on.

ckeyrouz
09-25-2009, 03:29 AM
To print something on the screen you use System.out.

You want to listen to any input in the screen and if the input was play you do something bla bla bla.

Now in order to take a text that was entered by the user we use System.in.

Now the class Scanner does exactly what you want.

When you say Scanner scanner = new Scanner(System.in);
It means that the Scanner class interprets the System.in which is the text that has been input by the user.

In the link I have given you there is a clear example.

For your own sake try to work yourself a bit on it and I told you I will help but not do it for you.

UrbanTwitch
09-25-2009, 06:14 AM
Using equalsIgnorecase works fine for me.

Check out what I got so far!

/**
DUNGEON CRAWL PROJECT
Programmer: Dan Jasnowski
Date: 9.24.2009

TO DO TASK:

-- after user inputs name...
ROLL Dice
If user rolls 80 or above... get attacked.
roll ANOTHER dice...
if user rolls 50 or above.. get attacked by BAT
ELSE get attacked by ORC
if user rolls 79 or below... keep walking...
**/

import java.util.*;
import java.io.*;
import java.util.Date;
import java.util.Random;


public class game {
public static void main(String args[]) {



String globalCom = "What would you like to do?\nfight | move | buy | heal";

BufferedReader reader;

FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object


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

System.out.println("\t\t\tWelcome to...\n");
System.out.println("\t\t___ ___ _ _ _ ");
System.out.println("\t\t| \\/ | | | (_) | ");
System.out.println("\t\t| . . |_ _ ___| |_ _| | __");
System.out.println("\t\t| |\\/| | | | / __| __| | |/ /");
System.out.println("\t\t| | | | |_| \\__ \\ |_| | < ");
System.out.println("\t\t\\_| |_/\\__, |___/\\__|_|_|\\_\\");
System.out.println("\t\t __/ | ");
System.out.println("\t\t |___/ ");

File f1 = new File("name.txt");



InputStreamReader istream = new InputStreamReader(System.in) ;

BufferedReader bufRead = new BufferedReader(istream);



try{



if (f1.exists() == false) {
System.out.println("\n\nWhat is your name?");
String name = bufRead.readLine();
//print the data entered by the user
System.out.println("\nWelcome to Mystik, " + name +"...\n\nYou feel light headed as you wake up from a room with no doors. You feel cold and sleep yet you managed to stumble back on your feet. There is a trapdoor behind you... what do you?\n\n1. Open trap door \n2. Do nothing; starve to death; die of boredom.");
out = new FileOutputStream("name.txt");
p = new PrintStream( out );
p.println (name);
p.close();
}else{
FileInputStream fstream = new FileInputStream("name.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File
while ((strLine = br.readLine()) != null) {
String level = "12";
String gold = "23";
String room = "1";

// Print the content on the console
System.out.println ("Welcome back, "+strLine+". You are level "+level+" with "+gold+" gold and in room "+room+".");

}


in.close();
}

System.out.println(globalCom);
String choice = bufRead.readLine();





//monster: Bat
if (choice.equalsIgnoreCase("fight") == true) {
Random diceRoller = new Random();

int numb = diceRoller.nextInt(101);
String msg;
if (numb >= 80) {
msg = "The bat attacked you with its wings!";
} else {
msg = "The bat missed.";
}
System.out.println(msg);
}//end if typed FIGHT

if (choice.equalsIgnoreCase("buy") == true) {
//buy styff
System.out.println("What would you like to buy? \niron sword | heal potion");
String buy = bufRead.readLine();

if (buy.equalsIgnoreCase("iron") == true) {
System.out.println("up" +buy);
}else{
System.out.println("dxownx" +buy);;
}
//end stuff

}
} //end try

catch (IOException ioe){

System.out.println("An unexpected error occured.");

}//end catch errors

}//end main method


private static void battle(String[] arg) {
System.out.println("This is the battle case...");
}

} //end class header

/**
String str = "play";
if (str.equalsIgnoreCase(name) == true) {
System.out.println("\n\nYou typed in play!\n\n");

}
**/

Just compile and run! :)

What do you think?

ckeyrouz
09-25-2009, 07:24 AM
Nicey.

Keep up the good work.

UrbanTwitch
09-25-2009, 03:08 PM
Question: I know how to save, load, a file but when I load a file it reads ALL of its contents. I just want a way for a file to load a LINE for example...

Line1: Hi
Line2: Boo
Line3: Bye

I want it to load line 3 and and display Bye.

Is this possible?
I searched. :\ no luck

ckeyrouz
09-25-2009, 04:35 PM
Add this method to your class:(outside the public static void main but inside the class)

public static void readLinesFromFile(int start, int end)
{
BufferedReader in = new BufferedReader (new FileReader("name.txt"));

String info = "";

for (int i = 0; i < start; i++) { info = in.readLine(); }
for (int i = start; i < end + 1; i++)
{
info = in.readLine();
System.out.println(info);
}

in.close();
}


and then call it this way from within the public static void main

game.readLinesFromFile(3,3);


Note that I did not test the method.

UrbanTwitch
09-25-2009, 06:19 PM
Weird... now the "Welcome back..." is displayed 3 times.

Why? because in my name.txt I have
Dan
Test1
Test5456

/**
DUNGEON CRAWL PROJECT
Programmer: Dan Jasnowski
Date: 9.24.2009

TO DO TASK:

-- after user inputs name...
ROLL Dice
If user rolls 80 or above... get attacked.
roll ANOTHER dice...
if user rolls 50 or above.. get attacked by BAT
ELSE get attacked by ORC
if user rolls 79 or below... keep walking...
**/

import java.util.*;
import java.io.*;
import java.util.Date;
import java.util.Random;


public class game {
BufferedReader reader;
public static void readLinesFromFile(int start, int end)
{
try {
BufferedReader in = new BufferedReader (new FileReader("name.txt"));

String info = "";

for (int i = 0; i < start; i++) { info = in.readLine(); }
for (int i = start; i < end + 1; i++)
{
info = in.readLine();
System.out.println("Stuff: "+info);
}

in.close();
}
catch (IOException ioe){

System.out.println("An unexpected error occured.");

}//end catch errors
}

public static void main(String args[]) {



String globalCom = "What would you like to do?\nfight | move | buy | heal";

BufferedReader reader;

FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object


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

System.out.println("\t\t\tWelcome to...\n");
System.out.println("\t\t___ ___ _ _ _ ");
System.out.println("\t\t| \\/ | | | (_) | ");
System.out.println("\t\t| . . |_ _ ___| |_ _| | __");
System.out.println("\t\t| |\\/| | | | / __| __| | |/ /");
System.out.println("\t\t| | | | |_| \\__ \\ |_| | < ");
System.out.println("\t\t\\_| |_/\\__, |___/\\__|_|_|\\_\\");
System.out.println("\t\t __/ | ");
System.out.println("\t\t |___/ ");

File f1 = new File("name.txt");



InputStreamReader istream = new InputStreamReader(System.in) ;

BufferedReader bufRead = new BufferedReader(istream);



try{



if (f1.exists() == false) {
System.out.println("\n\nWhat is your name?");
String name = bufRead.readLine();
//print the data entered by the user
System.out.println("\nWelcome to Mystik, " + name +"...\n\nYou feel light headed as you wake up from a room with no doors. You feel cold and sleep yet you managed to stumble back on your feet. There is a trapdoor behind you... what do you?\n\n1. Open trap door \n2. Do nothing; starve to death; die of boredom.");
out = new FileOutputStream("name.txt");
p = new PrintStream( out );
p.println (name);
p.close();
}else{
FileInputStream fstream = new FileInputStream("name.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File
while ((strLine = br.readLine()) != null) {
String level = "12";
String gold = "23";
String room = "1";

// Print the content on the console
System.out.println ("Welcome back, "+strLine+". You are level "+level+" with "+gold+" gold and in room "+room+".");

}


in.close();
}

System.out.println(globalCom);
String choice = bufRead.readLine();


game.readLinesFromFile(2,2);


//monster: Bat
if (choice.equalsIgnoreCase("fight") == true) {
Random diceRoller = new Random();

int numb = diceRoller.nextInt(101);
String msg;
if (numb >= 80) {
msg = "The bat attacked you with its wings!";
} else {
msg = "The bat missed.";
}
System.out.println(msg);
}//end if typed FIGHT

if (choice.equalsIgnoreCase("buy") == true) {
//buy styff
System.out.println("What would you like to buy? \niron sword | heal potion");
String buy = bufRead.readLine();

if (buy.equalsIgnoreCase("iron") == true) {
System.out.println("up" +buy);
}else{
System.out.println("dxownx" +buy);
}
//end stuff

}
} //end try

catch (IOException ioe){

System.out.println("An unexpected error occured.");

}//end catch errors

}//end main method


private static void battle(String[] arg) {
System.out.println("This is the battle case...");
}





} //end class header

/**
String str = "play";
if (str.equalsIgnoreCase(name) == true) {
System.out.println("\n\nYou typed in play!\n\n");

}
**/

:\ what is wronggg

ckeyrouz
09-25-2009, 07:06 PM
You need to work on your code formatting for better readability.

It should be well aligned and well indented.

Other than that you are doing a good job.

Welcome to the world of Java.

UrbanTwitch
09-25-2009, 08:34 PM
I edited my post :)

ckeyrouz
09-25-2009, 09:18 PM
Yes because of this.
Tell me what you want to do and I will help you solve it.

UrbanTwitch
09-25-2009, 09:27 PM
OK.
Paste this in TextPad
/**
DUNGEON CRAWL PROJECT
Programmer: Dan Jasnowski
Date: 9.24.2009

TO DO TASK:

-- after user inputs name...
ROLL Dice
If user rolls 80 or above... get attacked.
roll ANOTHER dice...
if user rolls 50 or above.. get attacked by BAT
ELSE get attacked by ORC
if user rolls 79 or below... keep walking...
**/

import java.util.*;
import java.io.*;
import java.util.Date;
import java.util.Random;


public class game {
BufferedReader reader;
public static void readLinesFromFile(int start, int end)
{
try {
BufferedReader in = new BufferedReader (new FileReader("name.txt"));

String info = "";

for (int i = 0; i < start; i++) { info = in.readLine(); }
for (int i = start; i < end + 1; i++)
{
info = in.readLine();
System.out.println("Stuff: "+info);
}

in.close();
}
catch (IOException ioe){

System.out.println("An unexpected error occured.");

}//end catch errors
}

public static void main(String args[]) {



String globalCom = "What would you like to do?\nfight | move | buy | heal";

BufferedReader reader;

FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object


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

System.out.println("\t\t\tWelcome to...\n");
System.out.println("\t\t___ ___ _ _ _ ");
System.out.println("\t\t| \\/ | | | (_) | ");
System.out.println("\t\t| . . |_ _ ___| |_ _| | __");
System.out.println("\t\t| |\\/| | | | / __| __| | |/ /");
System.out.println("\t\t| | | | |_| \\__ \\ |_| | < ");
System.out.println("\t\t\\_| |_/\\__, |___/\\__|_|_|\\_\\");
System.out.println("\t\t __/ | ");
System.out.println("\t\t |___/ ");

File f1 = new File("name.txt");



InputStreamReader istream = new InputStreamReader(System.in) ;

BufferedReader bufRead = new BufferedReader(istream);



try{



if (f1.exists() == false) {
System.out.println("\n\nWhat is your name?");
String name = bufRead.readLine();
//print the data entered by the user
System.out.println("\nWelcome to Mystik, " + name +"...\n\nYou feel light headed as you wake up from a room with no doors. You feel cold and sleep yet you managed to stumble back on your feet. There is a trapdoor behind you... what do you?\n\n1. Open trap door \n2. Do nothing; starve to death; die of boredom.");
out = new FileOutputStream("name.txt");
p = new PrintStream( out );
p.println (name);
p.close();
}else{
FileInputStream fstream = new FileInputStream("name.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File
while ((strLine = br.readLine()) != null) {
String level = "12";
String gold = "23";
String room = "1";

// Print the content on the console
System.out.println ("Welcome back, "+strLine+". You are level "+level+" with "+gold+" gold and in room "+room+".");

}


in.close();
}

System.out.println(globalCom);
String choice = bufRead.readLine();


game.readLinesFromFile(1,1);


//monster: Bat
if (choice.equalsIgnoreCase("fight") == true) {
Random diceRoller = new Random();

int numb = diceRoller.nextInt(101);
String msg;
if (numb >= 80) {
msg = "The bat attacked you with its wings!";
} else {
msg = "The bat missed.";
}
new game();
System.out.println(msg);
}//end if typed FIGHT

if (choice.equalsIgnoreCase("buy") == true) {
//buy styff
System.out.println("What would you like to buy? \niron sword | heal potion");
String buy = bufRead.readLine();

if (buy.equalsIgnoreCase("iron") == true) {
System.out.println("up" +buy);
}else{
System.out.println("dxownx" +buy);
}
//end stuff

}
} //end try

catch (IOException ioe){

System.out.println("An unexpected error occured.");

}//end catch errors

}//end main method


private static void battle(String[] arg) {
System.out.println("This is the battle case...");
}





} //end class header

/**
String str = "play";
if (str.equalsIgnoreCase(name) == true) {
System.out.println("\n\nYou typed in play!\n\n");

}
**/

Run it.. then exit.
Then go to name.txt and edit the file.
Add more lines with text ie.
Name
etgsg
sfsdgsdg

Run game.java and you will see that it shows ALL of the lines like Welcome.. blah blah for EVERY line written..

See what I mean?

ckeyrouz
09-25-2009, 09:59 PM
I know that already.

I will rephrase my question:
what is the required output?

How do you want your class to output the message?

UrbanTwitch
09-25-2009, 10:01 PM
I just want it to say Welcome ONCE... the name is one Line 0. (well 1.. but you know.)
But I am having a hard time doing it. :\

jolly_nikki
09-25-2009, 10:10 PM
Add System.out.println("Welcome back, "); outside the while loop.

System.out.println("Welcome back, ");
while ((strLine = br.readLine()) != null) {
String level = "12";
String gold = "23";
String room = "1";

// Print the content on the console
System.out.println (strLine+". You are level "+level+" with "+gold+" gold and in room "+room+".");

}

UrbanTwitch
09-25-2009, 10:40 PM
OK, I got that sorta.. I just took off the while loop.

/**
DUNGEON CRAWL PROJECT
Programmer: Dan Jasnowski
Date: 9.24.2009

TO DO TASK:

-- after user inputs name...
ROLL Dice
If user rolls 80 or above... get attacked.
roll ANOTHER dice...
if user rolls 50 or above.. get attacked by BAT
ELSE get attacked by ORC
if user rolls 79 or below... keep walking...
**/

import java.util.*;
import java.io.*;
import java.util.Date;
import java.util.Random;


public class game {
BufferedReader reader;
public static void readLinesFromFile(int start, int end)
{
try {
BufferedReader in = new BufferedReader (new FileReader("name.txt"));

String info = "";

for (int i = 0; i < start; i++) { info = in.readLine(); }
for (int i = start; i < end + 1; i++)
{
info = in.readLine();
System.out.println("Stuff: "+info);
}

in.close();
}
catch (IOException ioe){

System.out.println("An unexpected error occured.");

}//end catch errors
}

public static void main(String args[]) {



String globalCom = "What would you like to do?\nfight | move | buy | heal";

BufferedReader reader;

FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object


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

System.out.println("\t\t\tWelcome to...\n");
System.out.println("\t\t___ ___ _ _ _ ");
System.out.println("\t\t| \\/ | | | (_) | ");
System.out.println("\t\t| . . |_ _ ___| |_ _| | __");
System.out.println("\t\t| |\\/| | | | / __| __| | |/ /");
System.out.println("\t\t| | | | |_| \\__ \\ |_| | < ");
System.out.println("\t\t\\_| |_/\\__, |___/\\__|_|_|\\_\\");
System.out.println("\t\t __/ | ");
System.out.println("\t\t |___/ ");

File f1 = new File("name.txt");



InputStreamReader istream = new InputStreamReader(System.in) ;

BufferedReader bufRead = new BufferedReader(istream);



try{



if (f1.exists() == false) {
System.out.println("\n\nWhat is your name?");
String name = bufRead.readLine();
//print the data entered by the user
System.out.println("\nWelcome to Mystik, " + name +"...\n\nYou feel light headed as you wake up from a room with no doors. You feel cold and sleep yet you managed to stumble back on your feet. There is a trapdoor behind you... what do you?\n\n1. Open trap door \n2. Do nothing; starve to death; die of boredom.");
out = new FileOutputStream("name.txt");
p = new PrintStream( out );
p.println (name);
p.close();
}else{
FileInputStream fstream = new FileInputStream("name.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File
strLine = br.readLine();
String level = "12";
String gold = "23";
String room = "1";


System.out.println ("Welcome back, "+strLine+". You are level "+level+" with "+gold+" gold and in room "+room+".");

in.close();
}

System.out.println(globalCom);
String choice = bufRead.readLine();


game.readLinesFromFile(2,2);


//monster: Bat
if (choice.equalsIgnoreCase("fight") == true) {
Random diceRoller = new Random();

int numb = diceRoller.nextInt(101);
String msg;
if (numb >= 80) {
msg = "The bat attacked you with its wings!";
} else {
msg = "The bat missed.";
}
new game();
System.out.println(msg);
}//end if typed FIGHT

if (choice.equalsIgnoreCase("buy") == true) {
//buy styff
System.out.println("What would you like to buy? \niron sword | heal potion");
String buy = bufRead.readLine();

if (buy.equalsIgnoreCase("iron") == true) {
System.out.println("up" +buy);
}else{
System.out.println("dxownx" +buy);
}
//end stuff

}
} //end try

catch (IOException ioe){

System.out.println("An unexpected error occured.");

}//end catch errors

}//end main method


private static void battle(String[] arg) {
System.out.println("This is the battle case...");
}





} //end class header

/**
String str = "play";
if (str.equalsIgnoreCase(name) == true) {
System.out.println("\n\nYou typed in play!\n\n");

}
**/
How do I make this
game.readLinesFromFile(2,2);
a variable or string so I can display it using System.out.println?
argh, i know why because in the readLinesFromFile case.. its already doing System.out.println... :\
darnnnn =(

ckeyrouz
09-25-2009, 11:26 PM
this is your function :

public static void readLinesFromFile(int start, int end)
{
try {
BufferedReader in = new BufferedReader (new FileReader("name.txt"));

String info = "";

for (int i = 0; i < start; i++) { info = in.readLine(); }
for (int i = start; i < end + 1; i++)
{
info = in.readLine();
System.out.println("Stuff: "+info);
}

in.close();
}


replace it with:


public static void readLinesFromFile(int start, int end)
{
String info = "";
try {
BufferedReader in = new BufferedReader (new FileReader("name.txt"));



for (int i = 0; i < start; i++) { info = in.readLine(); }
for (int i = start; i < end + 1; i++)
{
info += in.readLine();
System.out.println("Stuff: "+info);
}

in.close();
}
catch (IOException ioe)
{

System.out.println("An unexpected error occured.");

}//end catch errors
finally
{
return info;
}
}

UrbanTwitch
09-25-2009, 11:44 PM
C:\Documents and Settings\student\Desktop\Java\Dungeon Crawl\game.java:50: cannot return a value from method whose result type is void
return info;
^
:S

ckeyrouz
09-26-2009, 12:49 AM
sorry about that.
Change the method declaration from void to String.

so replace this:
public static void readLinesFromFile(int start, int end)
with this:
public static String readLinesFromFile(int start, int end)

UrbanTwitch
09-26-2009, 01:14 AM
OK good, but still.. how do I turn
readLinesFromFile(2,2);
Into a string?

I tried
String test1 = readLinesFromFile(2,2);
but no go.. :\

the error
C:\Users\Dan\Documents\Java\game.java:90: ';' expected
String test 1 = readLinesFromFile(2,2);

ckeyrouz
09-26-2009, 08:41 PM
Lost track about things.
Post your latest code, please.

UrbanTwitch
09-26-2009, 08:49 PM
OK run this:
/**
DUNGEON CRAWL PROJECT
Programmer: Dan Jasnowski
Date: 9.24.2009

TO DO TASK:

-- after user inputs name...
ROLL Dice
If user rolls 80 or above... get attacked.
roll ANOTHER dice...
if user rolls 50 or above.. get attacked by BAT
ELSE get attacked by ORC
if user rolls 79 or below... keep walking...
**/

import java.util.*;
import java.io.*;
import java.util.Date;
import java.util.Random;


public class game {
BufferedReader reader;
public static String readLinesFromFile(int start, int end)
{
String info = "";
try {
BufferedReader in = new BufferedReader (new FileReader("stats.txt"));



for (int i = 0; i < start; i++) { info = in.readLine(); }
for (int i = start; i < end + 1; i++)
{

System.out.println(info);
}

in.close();
}
catch (IOException ioe)
{

System.out.println("An unexpected error occured.");

}//end catch errors
finally
{
return info;
}
}
public static void main(String args[]) {



String globalCom = "What would you like to do?\nfight | move | buy | heal";
int hp = 100;
BufferedReader reader;

FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object


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

System.out.println("\t\t\tWelcome to...\n");
System.out.println("\t\t___ ___ _ _ _ ");
System.out.println("\t\t| \\/ | | | (_) | ");
System.out.println("\t\t| . . |_ _ ___| |_ _| | __");
System.out.println("\t\t| |\\/| | | | / __| __| | |/ /");
System.out.println("\t\t| | | | |_| \\__ \\ |_| | < ");
System.out.println("\t\t\\_| |_/\\__, |___/\\__|_|_|\\_\\");
System.out.println("\t\t __/ | ");
System.out.println("\t\t |___/ ");

File f1 = new File("stats.txt");



InputStreamReader istream = new InputStreamReader(System.in) ;

BufferedReader bufRead = new BufferedReader(istream);



try{


if (f1.exists() == false) {
System.out.println("\n\nWhat is your name?");
String name = bufRead.readLine();
//print the data entered by the user
System.out.println("\nWelcome to Mystik, " + name +"...\n\nYou feel light headed as you wake up from a room with no doors. You feel cold and sleepy yet you manage to stumble onto your feet.");
System.out.println("\nYou then go through the trapdoor and discover a long and trecherous road...");
out = new FileOutputStream("stats.txt");
p = new PrintStream( out );
p.println (name);
p.println("500");
p.println("1");
p.println("1");
p.println("1");
p.close();
}else{

String username = readLinesFromFile(1,1);
String gold = readLinesFromFile(2,2);
String lvl = readLinesFromFile(3,3);
String exp = readLinesFromFile(4,4);
String room = readLinesFromFile(5,5);

System.out.println(" \nWelcome back, "+username+"!\n");
System.out.println("Gold: "+gold);
System.out.println("Current Level:" +lvl);
System.out.println("EXP: "+exp);
System.out.println("Room "+room+"\n");


}

System.out.println(globalCom);
String choice = bufRead.readLine();





//BATTLE

if (choice.equalsIgnoreCase("fight") == true) {
Random diceRoller = new Random();

int numb = diceRoller.nextInt(101);
int type = diceRoller.nextInt(50);
int gobhit = diceRoller.nextInt(10);
int bathit = diceRoller.nextInt(5);
int ogrehit = diceRoller.nextInt(20);

String msg=null;
String monster=null;
System.out.println(type);

if (type > 3) {
monster = "goblin";
if (numb >= 10) {
msg = "The goblin swung at you with it's claws and hit you for ";
} else{
msg = "The goblin's attack missed.";
}

}else {

msg ="You did not encounter anything...";
}


/**else if(type < 20) {
monster = "bat";
if (numb >= 10) {
msg = "The bat attacked you with its wings!";
int newhp =hp-bathit;
System.out.println(msg+"\nCurrent HP:" +newhp);
} else {
msg = "The bat missed.";
}
}else {
monster = "ogre";
if (numb >= 10) {
msg = "The ogre hit you hard with its club";
int newhp =hp-ogrehit;
System.out.println(msg+"\nCurrent HP:" +newhp);
} else {
msg = "The ogre missed.";
}
}**/



if(monster == "goblin" && numb >= 10) {
int newhp =hp-gobhit;
System.out.println(msg+ gobhit+"\nCurrent HP: " +newhp);
if (newhp > 95) {
battle();
}
}else{
System.out.println(msg+"\nYour HP is still "+hp);
int newhp =hp;
}



}//end if typed FIGHT

//buy stuff
if (choice.equalsIgnoreCase("buy") == true) {

System.out.println("What would you like to buy? \niron sword | heal potion");
String buy = bufRead.readLine();

if (buy.equalsIgnoreCase("iron") == true) {
System.out.println("up" +buy);
}else{
System.out.println("dxownx" +buy);
}
}
//end stuff
} //end try

catch (IOException ioe){

System.out.println("An unexpected error occured.");

}//end catch errors

}//end main method


private static void battle() {
System.out.println("This is the battle case...");
}





} //end class header

/**
String str = "play";
if (str.equalsIgnoreCase(name) == true) {
System.out.println("\n\nYou typed in play!\n\n");

}
**/

When you run it you will see that the things
String username = readLinesFromFile(1,1);
String gold = readLinesFromFile(2,2);
String lvl = readLinesFromFile(3,3);
String exp = readLinesFromFile(4,4);
String room = readLinesFromFile(5,5);
Are displayed twice.
One when they are being delcared as strings and another time when they are in the system.out.println...

how do I make so they only show in the system.out.println?

ckeyrouz
09-26-2009, 09:10 PM
I have organized a bit your code and corrected few things.
/**
DUNGEON CRAWL PROJECT
Programmer: Dan Jasnowski
Date: 9.24.2009

TO DO TASK:

-- after user inputs name...
ROLL Dice
If user rolls 80 or above... get attacked.
roll ANOTHER dice...
if user rolls 50 or above.. get attacked by BAT
ELSE get attacked by ORC
if user rolls 79 or below... keep walking...
**/

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Random;


public class Game
{
public String readLinesFromFile(int start, int end)
{
String info = "";
BufferedReader in;
try
{
in = new BufferedReader (new FileReader("stats.txt"));
for (int i = 0; i < start; i++) { info = in.readLine(); }
for (int i = start; i < end + 1; i++)
{

System.out.println(info);
}
in.close();
}
catch (IOException ioe)
{
System.out.println("An unexpected error occured." + ioe.getMessage());
}//end catch errors
return info;
}

public void printIntro()
{
System.out.println("\t\t\tWelcome to...\n");
System.out.println("\t\t___ ___ _ _ _ ");
System.out.println("\t\t| \\/ | | | (_) | ");
System.out.println("\t\t| . . |_ _ ___| |_ _| | __");
System.out.println("\t\t| |\\/| | | | / __| __| | |/ /");
System.out.println("\t\t| | | | |_| \\__ \\ |_| | < ");
System.out.println("\t\t\\_| |_/\\__, |___/\\__|_|_|\\_\\");
System.out.println("\t\t __/ | ");
System.out.println("\t\t |___/ ");
}

public static void main(String args[])
{
Game game = new Game();
String globalCom = "What would you like to do?\nfight | move | buy | heal";
int hp = 100;

FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object

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

game.printIntro();

File f1 = new File("stats.txt");
InputStreamReader istream = new InputStreamReader(System.in) ;
BufferedReader bufRead = new BufferedReader(istream);

try
{
if (f1.exists() == false)
{
System.out.println("\n\nWhat is your name?");
String name = bufRead.readLine();
//print the data entered by the user
System.out.println("\nWelcome to Mystik, " + name +"...\n\nYou feel light headed as you wake up from a room with no doors. You feel cold and sleepy yet you manage to stumble onto your feet.");
System.out.println("\nYou then go through the trapdoor and discover a long and trecherous road...");
out = new FileOutputStream("stats.txt");
p = new PrintStream( out );
p.println (name);
p.println("500");
p.println("1");
p.println("1");
p.println("1");
p.close();
}
else
{
FileInputStream fstream = new FileInputStream("stats.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File
strLine = br.readLine();
System.out.println(" \nWelcome back, "+strLine+"!\n");
System.out.printf("Gold: " + game.readLinesFromFile(2,2));
System.out.printf("Current Level: "+ game.readLinesFromFile(3,3));
System.out.printf("EXP: " + game.readLinesFromFile(4,4));
System.out.printf("Room " + game.readLinesFromFile(5,5));
System.out.println("\n");
in.close();
}

System.out.println(globalCom);
String choice = bufRead.readLine();

//BATTLE

if (choice.equalsIgnoreCase("fight"))
{
Random diceRoller = new Random();

int numb = diceRoller.nextInt(101);
int type = diceRoller.nextInt(50);
int gobhit = diceRoller.nextInt(10);
int bathit = diceRoller.nextInt(5);
int ogrehit = diceRoller.nextInt(20);

String msg=null;
String monster=null;
System.out.println(type);

if (type > 3)
{
monster = "goblin";
if (numb >= 10)
{
msg = "The goblin swung at you with it's claws and hit you for ";
}
else
{
msg = "The goblin's attack missed.";
}
}
else
{
msg ="You did not encounter anything...";
}


/**else if(type < 20) {
monster = "bat";
if (numb >= 10) {
msg = "The bat attacked you with its wings!";
int newhp =hp-bathit;
System.out.println(msg+"\nCurrent HP:" +newhp);
} else {
msg = "The bat missed.";
}
}else {
monster = "ogre";
if (numb >= 10) {
msg = "The ogre hit you hard with its club";
int newhp =hp-ogrehit;
System.out.println(msg+"\nCurrent HP:" +newhp);
} else {
msg = "The ogre missed.";
}
}**/
//if(monster == "goblin" && numb >= 10) this is wrong
if(monster.equalsIgnoreCase("goblin") && numb >= 10)
{
hp = hp-gobhit;
System.out.println(msg+ gobhit+"\nCurrent HP: " +hp);
if (hp > 95)
{
battle();
}
}
else
{
System.out.println(msg+"\nYour HP is still "+hp);
}
}//end if typed FIGHT

//buy stuff
if (choice.equalsIgnoreCase("buy") == true)
{
System.out.println("What would you like to buy? \niron sword | heal potion");
String buy = bufRead.readLine();

if (buy.equalsIgnoreCase("iron") == true)
{
System.out.println("up" +buy);
}
else
{
System.out.println("dxownx" +buy);
}
}
//end stuff
} //end try
catch (IOException ioe)
{
System.out.println("An unexpected error occured.");
}//end catch errors
}//end main method


private static void battle()
{
System.out.println("This is the battle case...");
}

} //end class header

/**
String str = "play";
if (str.equalsIgnoreCase(name) == true) {
System.out.println("\n\nYou typed in play!\n\n");

}
**/

try it now.

UrbanTwitch
09-26-2009, 09:42 PM
OK, working... sorta.
I get this:
Welcome to...

___ ___ _ _ _
| \/ | | | (_) |
| . . |_ _ ___| |_ _| | __
| |\/| | | | / __| __| | |/ /
| | | | |_| \__ \ |_| | <
\_| |_/\__, |___/\__|_|_|\_\
__/ |
|___/
Daniel

Welcome back, Daniel

500
Gold: 500

8
Current Level: 8

1024
EXP: 1024

1
Room 1

What would you like to do?
fight | move | buy | heal


Contents inside stats.txt
Daniel
500
8
1024
1

What a weird bug... and thanks for beautifying my code. :)

Oh, my code..
/**
DUNGEON CRAWL PROJECT
Programmer: Dan Jasnowski
Date: 9.24.2009

TO DO TASK:

-- after user inputs name...
ROLL Dice
If user rolls 80 or above... get attacked.
roll ANOTHER dice...
if user rolls 50 or above.. get attacked by BAT
ELSE get attacked by ORC
if user rolls 79 or below... keep walking...
**/

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Random;


public class game
{
public String readLinesFromFile(int start, int end)
{
String info = "";
BufferedReader in;
try
{
in = new BufferedReader (new FileReader("stats.txt"));
for (int i = 0; i < start; i++) { info = in.readLine(); }
for (int i = start; i < end + 1; i++)
{
System.out.println(info);
}
in.close();
}
catch (IOException ioe)
{
System.out.println("An unexpected error occured." + ioe.getMessage());
}//end catch errors
return info;
}

public void printIntro()
{
System.out.println("\t\t\tWelcome to...\n");
System.out.println("\t\t___ ___ _ _ _ ");
System.out.println("\t\t| \\/ | | | (_) | ");
System.out.println("\t\t| . . |_ _ ___| |_ _| | __");
System.out.println("\t\t| |\\/| | | | / __| __| | |/ /");
System.out.println("\t\t| | | | |_| \\__ \\ |_| | < ");
System.out.println("\t\t\\_| |_/\\__, |___/\\__|_|_|\\_\\");
System.out.println("\t\t __/ | ");
System.out.println("\t\t |___/ ");
}

public static void main(String args[])
{
game game = new game();
String globalCom = "What would you like to do?\nfight | move | buy | heal";
int hp = 100;

FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object

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

game.printIntro();

File f1 = new File("stats.txt");
InputStreamReader istream = new InputStreamReader(System.in) ;
BufferedReader bufRead = new BufferedReader(istream);

try
{
if (f1.exists() == false)
{
System.out.println("\n\nWhat is your name?");
String name = bufRead.readLine();
//print the data entered by the user
System.out.println("\nWelcome to Mystik, " + name +"...\n\nYou feel light headed as you wake up from a room with no doors. You feel cold and sleepy yet you manage to stumble onto your feet.");
System.out.println("\nYou then go through the trapdoor and discover a long and trecherous road...");
out = new FileOutputStream("stats.txt");
p = new PrintStream( out );
p.println (name);
p.println("500");
p.println("1");
p.println("1");
p.println("1");
p.close();
}
else
{
FileInputStream fstream = new FileInputStream("stats.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File
strLine = br.readLine();
System.out.println(" \nWelcome back, " + game.readLinesFromFile(1,1)+"\n");
System.out.println("
Gold: " + game.readLinesFromFile(2,2)+"\n");
System.out.println("Current Level: "+ game.readLinesFromFile(3,3) +"\n");
System.out.println("EXP: " + game.readLinesFromFile(4,4)+"\n");
System.out.println("Room " + game.readLinesFromFile(5,5)+"\n");

in.close();
}

System.out.println(globalCom);
String choice = bufRead.readLine();

//BATTLE

if (choice.equalsIgnoreCase("fight"))
{
Random diceRoller = new Random();

int numb = diceRoller.nextInt(101);
int type = diceRoller.nextInt(50);
int gobhit = diceRoller.nextInt(10);
int bathit = diceRoller.nextInt(5);
int ogrehit = diceRoller.nextInt(20);

String msg=null;
String monster=null;
System.out.println(type);

if (type > 3)
{
monster = "goblin";
if (numb >= 10)
{
msg = "The goblin swung at you with it's claws and hit you for ";
}
else
{
msg = "The goblin's attack missed.";
}
}
else
{
msg ="You did not encounter anything...";
}


/**else if(type < 20) {
monster = "bat";
if (numb >= 10) {
msg = "The bat attacked you with its wings!";
int newhp =hp-bathit;
System.out.println(msg+"\nCurrent HP:" +newhp);
} else {
msg = "The bat missed.";
}
}else {
monster = "ogre";
if (numb >= 10) {
msg = "The ogre hit you hard with its club";
int newhp =hp-ogrehit;
System.out.println(msg+"\nCurrent HP:" +newhp);
} else {
msg = "The ogre missed.";
}
}**/
//if(monster == "goblin" && numb >= 10) this is wrong
if(monster.equalsIgnoreCase("goblin") && numb >= 10)
{
hp = hp-gobhit;
System.out.println(msg+ gobhit+"\nCurrent HP: " +hp);
if (hp > 95)
{
battle();
}
}
else
{
System.out.println(msg+"\nYour HP is still "+hp);
}
}//end if typed FIGHT

//buy stuff
if (choice.equalsIgnoreCase("buy") == true)
{
System.out.println("What would you like to buy? \niron sword | heal potion");
String buy = bufRead.readLine();

if (buy.equalsIgnoreCase("iron") == true)
{
System.out.println("up" +buy);
}
else
{
System.out.println("dxownx" +buy);
}
}
//end stuff
} //end try
catch (IOException ioe)
{
System.out.println("An unexpected error occured.");
}//end catch errors
}//end main method


private static void battle()
{
System.out.println("This is the battle case...");
}

} //end class header

/**
String str = "play";
if (str.equalsIgnoreCase(name) == true) {
System.out.println("\n\nYou typed in play!\n\n");

}
**/

ckeyrouz
09-26-2009, 09:45 PM
replace your function with this:
public String readLinesFromFile(int start, int end)
{
String info = "";
BufferedReader in;
try
{
in = new BufferedReader (new FileReader("stats.txt"));
for (int i = 0; i < start; i++) { info = in.readLine(); }
for (int i = start; i < end + 1; i++)
{
info = in.readLine();
}
in.close();
}
catch (IOException ioe)
{
System.out.println("An unexpected error occured." + ioe.getMessage());
}//end catch errors
return info;
}

UrbanTwitch
09-26-2009, 09:47 PM
OK I did, now i get this when I compile:

C:\Users\Dan\Documents\Java\game.java:110: unclosed string literal
System.out.println("
^
C:\Users\Dan\Documents\Java\game.java:110: ';' expected
System.out.println("
^
C:\Users\Dan\Documents\Java\game.java:111: illegal start of expression
Gold: " + game.readLinesFromFile(2,2)+"\n");
^
C:\Users\Dan\Documents\Java\game.java:111: ';' expected
Gold: " + game.readLinesFromFile(2,2)+"\n");
^
C:\Users\Dan\Documents\Java\game.java:111: illegal character: \92
Gold: " + game.readLinesFromFile(2,2)+"\n");
^
C:\Users\Dan\Documents\Java\game.java:111: unclosed string literal
Gold: " + game.readLinesFromFile(2,2)+"\n");
^
6 errors


:S

ckeyrouz
09-26-2009, 09:51 PM
this is the class I have and it is compiling:
/**
DUNGEON CRAWL PROJECT
Programmer: Dan Jasnowski
Date: 9.24.2009

TO DO TASK:

-- after user inputs name...
ROLL Dice
If user rolls 80 or above... get attacked.
roll ANOTHER dice...
if user rolls 50 or above.. get attacked by BAT
ELSE get attacked by ORC
if user rolls 79 or below... keep walking...
**/

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Random;


public class Game
{
public String readLinesFromFile(int start, int end)
{
String info = "";
BufferedReader in;
try
{
in = new BufferedReader (new FileReader("stats.txt"));
for (int i = 0; i < start; i++) { info = in.readLine(); }
for (int i = start; i < end + 1; i++)
{
info = in.readLine();
}
in.close();
}
catch (IOException ioe)
{
System.out.println("An unexpected error occured." + ioe.getMessage());
}//end catch errors
return info;
}

public void printIntro()
{
System.out.println("\t\t\tWelcome to...\n");
System.out.println("\t\t___ ___ _ _ _ ");
System.out.println("\t\t| \\/ | | | (_) | ");
System.out.println("\t\t| . . |_ _ ___| |_ _| | __");
System.out.println("\t\t| |\\/| | | | / __| __| | |/ /");
System.out.println("\t\t| | | | |_| \\__ \\ |_| | < ");
System.out.println("\t\t\\_| |_/\\__, |___/\\__|_|_|\\_\\");
System.out.println("\t\t __/ | ");
System.out.println("\t\t |___/ ");
}

public static void main(String args[])
{
Game game = new Game();
String globalCom = "What would you like to do?\nfight | move | buy | heal";
int hp = 100;

FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object

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

game.printIntro();

File f1 = new File("stats.txt");
InputStreamReader istream = new InputStreamReader(System.in) ;
BufferedReader bufRead = new BufferedReader(istream);

try
{
if (f1.exists() == false)
{
System.out.println("\n\nWhat is your name?");
String name = bufRead.readLine();
//print the data entered by the user
System.out.println("\nWelcome to Mystik, " + name +"...\n\nYou feel light headed as you wake up from a room with no doors. You feel cold and sleepy yet you manage to stumble onto your feet.");
System.out.println("\nYou then go through the trapdoor and discover a long and trecherous road...");
out = new FileOutputStream("stats.txt");
p = new PrintStream( out );
p.println (name);
p.println("500");
p.println("1");
p.println("1");
p.println("1");
p.close();
}
else
{
FileInputStream fstream = new FileInputStream("stats.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File
strLine = br.readLine();
System.out.println(" \nWelcome back, "+strLine+"!\n");
System.out.printf("Gold: " + game.readLinesFromFile(2,2));
System.out.printf("Current Level: "+ game.readLinesFromFile(3,3));
System.out.printf("EXP: " + game.readLinesFromFile(4,4));
System.out.printf("Room " + game.readLinesFromFile(5,5));
System.out.println("\n");
in.close();
}

System.out.println(globalCom);
String choice = bufRead.readLine();

//BATTLE

if (choice.equalsIgnoreCase("fight"))
{
Random diceRoller = new Random();

int numb = diceRoller.nextInt(101);
int type = diceRoller.nextInt(50);
int gobhit = diceRoller.nextInt(10);
int bathit = diceRoller.nextInt(5);
int ogrehit = diceRoller.nextInt(20);

String msg=null;
String monster=null;
System.out.println(type);

if (type > 3)
{
monster = "goblin";
if (numb >= 10)
{
msg = "The goblin swung at you with it's claws and hit you for ";
}
else
{
msg = "The goblin's attack missed.";
}
}
else
{
msg ="You did not encounter anything...";
}


/**else if(type < 20) {
monster = "bat";
if (numb >= 10) {
msg = "The bat attacked you with its wings!";
int newhp =hp-bathit;
System.out.println(msg+"\nCurrent HP:" +newhp);
} else {
msg = "The bat missed.";
}
}else {
monster = "ogre";
if (numb >= 10) {
msg = "The ogre hit you hard with its club";
int newhp =hp-ogrehit;
System.out.println(msg+"\nCurrent HP:" +newhp);
} else {
msg = "The ogre missed.";
}
}**/
//if(monster == "goblin" && numb >= 10) this is wrong
if(monster.equalsIgnoreCase("goblin") && numb >= 10)
{
hp = hp-gobhit;
System.out.println(msg+ gobhit+"\nCurrent HP: " +hp);
if (hp > 95)
{
battle();
}
}
else
{
System.out.println(msg+"\nYour HP is still "+hp);
}
}//end if typed FIGHT

//buy stuff
if (choice.equalsIgnoreCase("buy") == true)
{
System.out.println("What would you like to buy? \niron sword | heal potion");
String buy = bufRead.readLine();

if (buy.equalsIgnoreCase("iron") == true)
{
System.out.println("up" +buy);
}
else
{
System.out.println("dxownx" +buy);
}
}
//end stuff
} //end try
catch (IOException ioe)
{
System.out.println("An unexpected error occured.");
}//end catch errors
}//end main method


private static void battle()
{
System.out.println("This is the battle case...");
}

} //end class header

/**
String str = "play";
if (str.equalsIgnoreCase(name) == true) {
System.out.println("\n\nYou typed in play!\n\n");

}
**/

UrbanTwitch
09-26-2009, 09:56 PM
Alright, thanks! :-D

Now onto my battle.
/**
Simple Battle Class
DAN
Dungeon C
**/

import java.util. * ;
import java.io. * ;
import java.util.Random;

public class oldgewdbattle {

public static void main(String[] args) {
battle(); //does battle
}

public static void battleDone() { // battle finish method
System.out.println("\n\nBattle has finished.\n\n");
}

public static void battle() {

Random diceRoller = new Random();
Random monsterRoller = new Random();
Random getMonster = new Random();
int total_rounds = 0;
int monster_hp = 100;
int my_hp = 100;

int typeMonster = getMonster.nextInt(10);
if (typeMonster > 7) {
String monster = "Ogre";

}else {
String monster = "Goblin";
}


while (monster_hp > 1 || my_hp > 1) { // while either monster or user's hp is 1 or higher... do this
int my_hit = diceRoller.nextInt(20); // what you hit




if (typeMonster > 7) {
int monster_hit = monsterRoller.nextInt(50); // ogre hit
}else {
int monster_hit = monsterRoller.nextInt(20); //goblin hit
}

int mon_hp = monster_hp - my_hit;
int new_hp = my_hp - monster_hit;

if (mon_hp <= 0) { // if monster's hp is below zero.. set to zero
mon_hp = 0;
}


if (new_hp <= 0) { // if user's hp is below zero.. set to zero
new_hp = 0;
}



//display monster messages
if (new_hp > 1) {
System.out.println(monster+" hit for " + monster_hit + "\nYOUR Old HP: " + monster_hp + "\nYOUR New HP: " + mon_hp + "\n\n----\n");
}

//end monster messages


if (mon_hp > 1) {
System.out.println("YOU hit for " + my_hit + "\nMONSTER's Old HP: " + my_hp + "\nMONSTER's New HP: " + new_hp + "\n\n----\n");
}


if (new_hp <= 0) {
new_hp = 0;
System.out.println("Your Final HP " + mon_hp + ". You killed the monster! It took " + total_rounds + " times for you to kill it.");
}


if (mon_hp <= 0) {
mon_hp = 0;
System.out.println("Monster's Final HP " + new_hp + ". You died! It took " + total_rounds + " times to defeat you.");
}


if (mon_hp <= 0 || new_hp <= 0) {
battleDone();
break;
}


monster_hp = mon_hp;
my_hp = new_hp;
total_rounds++; // add new round to total rounds

} //end while
} //end battle method
} //end public class
The code I get when I try to compile:
C:\Users\Dan\Documents\Java\oldgewdbattle.java:52: cannot find symbol
symbol : variable monster_hit
location: class oldgewdbattle
int new_hp = my_hp - monster_hit;

C:\Users\Dan\Documents\Java\oldgewdbattle.java:67: cannot find symbol
symbol : variable monster
location: class oldgewdbattle
System.out.println(monster+" hit for " + monster_hit + "\nYOUR Old HP: " + monster_hp + "\nYOUR New HP: " + mon_hp + "\n\n----\n");

C:\Users\Dan\Documents\Java\oldgewdbattle.java:67: cannot find symbol
symbol : variable monster_hit
location: class oldgewdbattle
System.out.println(monster+" hit for " + monster_hit + "\nYOUR Old HP: " + monster_hp + "\nYOUR New HP: " + mon_hp + "\n\n----\n");

3 errors
I honestly don't know how it cant see the monster_hit.. i mean its right there.. :S

ckeyrouz
09-26-2009, 10:03 PM
Here is the corrected code:
/**
Simple Battle Class
DAN
Dungeon C
**/

import java.util.Random;

public class oldgewdbattle
{

public static void main(String[] args)
{
battle(); //does battle
}

public static void battleDone()
{ // battle finish method
System.out.println("\n\nBattle has finished.\n\n");
}

public static void battle()
{
Random diceRoller = new Random();
Random monsterRoller = new Random();
Random getMonster = new Random();
int total_rounds = 0;
int monster_hp = 100;
int my_hp = 100;

int typeMonster = getMonster.nextInt(10);
String monster;
if (typeMonster > 7)
{
monster = "Ogre";
}
else
{
monster = "Goblin";
}

while (monster_hp > 1 || my_hp > 1)
{ // while either monster or user's hp is 1 or higher... do this
int my_hit = diceRoller.nextInt(20); // what you hit
int monster_hit = 0;
if (typeMonster > 7)
{
monster_hit = monsterRoller.nextInt(50); // ogre hit
}
else
{
monster_hit = monsterRoller.nextInt(20); //goblin hit
}

int mon_hp = monster_hp - my_hit;
int new_hp = my_hp - monster_hit;

if (mon_hp <= 0)
{ // if monster's hp is below zero.. set to zero
mon_hp = 0;
}
if (new_hp <= 0)
{ // if user's hp is below zero.. set to zero
new_hp = 0;
}

//display monster messages
if (new_hp > 1)
{
System.out.println(monster+" hit for " + monster_hit + "\nYOUR Old HP: " + monster_hp + "\nYOUR New HP: " + mon_hp + "\n\n----\n");
}

//end monster messages

if (mon_hp > 1)
{
System.out.println("YOU hit for " + my_hit + "\nMONSTER's Old HP: " + my_hp + "\nMONSTER's New HP: " + new_hp + "\n\n----\n");
}

if (new_hp <= 0)
{
new_hp = 0;
System.out.println("Your Final HP " + mon_hp + ". You killed the monster! It took " + total_rounds + " times for you to kill it.");
}

if (mon_hp <= 0)
{
mon_hp = 0;
System.out.println("Monster's Final HP " + new_hp + ". You died! It took " + total_rounds + " times to defeat you.");
}

if (mon_hp <= 0 || new_hp <= 0)
{
battleDone();
break;
}
monster_hp = mon_hp;
my_hp = new_hp;
total_rounds++; // add new round to total rounds

} //end while
} //end battle method
} //end public class

It can't see some variables because they are created inside if s and something like that.

If you need a variable to be used all over your program then make them global.

In fact this is what I did:
Made some of your variables global.
organized the code.

UrbanTwitch
09-26-2009, 10:15 PM
Yeah! I thinking of doing it in global variables but I wasn't sure of it.

Also... sometimes when I run the code.. I get this
Your Final HP 0. You killed the monster! It took 9 times for you to kill it.
Goblin's Final HP 0. You died! It took 9 times to defeat you.


Battle has finished.
We both die?

Again, thanks for the formatting.

ckeyrouz
09-26-2009, 10:49 PM
try replacing this line:
while (monster_hp > 1 || my_hp > 1)

with this line:
while (monster_hp > 1 && my_hp > 1)

UrbanTwitch
09-26-2009, 10:52 PM
OK. I am having trouble with Buffers...

So far I have this.
/**
DUNGEON CRAWL PROJECT
Programmer: Dan Jasnowski
Date: 9.24.2009

TO DO TASK:

-- after user inputs name...
ROLL Dice
If user rolls 80 or above... get attacked.
roll ANOTHER dice...
if user rolls 50 or above.. get attacked by BAT
ELSE get attacked by ORC
if user rolls 79 or below... keep walking...
**/

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Random;


public class game
{
public String readLinesFromFile(int start, int end)
{
String info = "";
BufferedReader in;
try
{
in = new BufferedReader (new FileReader("stats.txt"));
for (int i = 0; i < start; i++) { info = in.readLine(); }
for (int i = start; i < end + 1; i++)
{
info = in.readLine();
}
in.close();
}
catch (IOException ioe)
{
System.out.println("An unexpected error occured." + ioe.getMessage());
}//end catch errors
return info;
}

public void printIntro()
{
System.out.println("\t\t\tWelcome to...\n");
System.out.println("\t\t___ ___ _ _ _ ");
System.out.println("\t\t| \\/ | | | (_) | ");
System.out.println("\t\t| . . |_ _ ___| |_ _| | __");
System.out.println("\t\t| |\\/| | | | / __| __| | |/ /");
System.out.println("\t\t| | | | |_| \\__ \\ |_| | < ");
System.out.println("\t\t\\_| |_/\\__, |___/\\__|_|_|\\_\\");
System.out.println("\t\t __/ | ");
System.out.println("\t\t |___/ ");
}

public static void main(String args[])
{
game game = new game();
String globalCom = "What would you like to do?\nfight | buy | stats";
int hp = 100;

FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object

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

game.printIntro();

File f1 = new File("stats.txt");
InputStreamReader istream = new InputStreamReader(System.in) ;
BufferedReader bufRead = new BufferedReader(istream);

try
{
if (f1.exists() == false)
{
System.out.println("\n\nWhat is your name?");
String name = bufRead.readLine();
//print the data entered by the user
System.out.println("\nWelcome to Mystik, " + name +"...\n\nYou feel light headed as you wake up from a room with no doors. You feel cold and sleepy yet you manage to stumble onto your feet.");
System.out.println("\nYou then go through the trapdoor and discover a long and trecherous road...");
out = new FileOutputStream("stats.txt");
p = new PrintStream( out );
p.println (name);
p.println("500");
p.println("1");
p.println("1");
p.println("1");
p.close();
}
else
{
FileInputStream fstream = new FileInputStream("stats.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File
strLine = br.readLine();
System.out.println(" \nWelcome back, " + game.readLinesFromFile(0,0));
System.out.println("Gold: " + game.readLinesFromFile(1,1));
System.out.println("Current Level: "+ game.readLinesFromFile(2,2));
System.out.println("EXP: " + game.readLinesFromFile(3,3));
System.out.println("Room " + game.readLinesFromFile(4,4));
System.out.println("\n");
in.close();
}

System.out.println(globalCom);
String choice = bufRead.readLine();

//BATTLE

if (choice.equalsIgnoreCase("fight") || fightAgain.equalsIgnoreCase("Y"))
{
battle();
}//end if typed FIGHT


//buy stuff
if (choice.equalsIgnoreCase("buy") == true)
{
System.out.println("What would you like to buy? \niron sword | heal potion");
String buy = bufRead.readLine();

if (buy.equalsIgnoreCase("iron") == true)
{
System.out.println("up" +buy);
}
else
{
System.out.println("dxownx" +buy);
}
}
//end stuff
} //end try
catch (IOException ioe)
{
System.out.println("An unexpected error occured.");
}//end catch errors
}//end main method


public static void battleDone(){ // battle finish method
InputStreamReader istream = new InputStreamReader(System.in) ;
BufferedReader bufRead = new BufferedReader(istream);
System.out.println("\n\nBattle has finished.\n\nFight again?\nY/N");
try {
String fightAgain = bufRead.readLine();
}
catch (IOException ioe)
{
System.out.println("An unexpected error occured.");
}//end catch errors
}







public static void battle(){

Random diceRoller = new Random();

int count = 0;
int monhp = 100;
int numb = 100;


while (monhp > 1 || numb > 1) { // while either monster or user's hp is 1 or higher... do this
int nit = diceRoller.nextInt(20); // what you hit
int otherx = diceRoller.nextInt(20); // what a goblin hits
int nf = monhp-nit;
int nx = numb-otherx;


if (nf <= 0) { // if monster's hp is below zero.. set to zero
nf = 0;
}
if (nx <= 0 ) { // if user's hp is below zero.. set to zero
nx = 0;
}

if (nx > 1) {
System.out.println("MONSTER hit for "+nit+"\nYOUR Old HP: "+monhp+"\nYOUR New HP: " + nf +"\n\n----\n");
}
if (nf > 1) {
System.out.println("YOU hit for "+otherx+"\nMONSTER's Old HP: "+numb+"\nMONSTER's New HP: " + nx+"\n\n----\n");
}

if (nx <= 0 ) {
nx = 0;
System.out.println("Your Final HP "+ nf+". You killed the monster! It took "+count+" times for you to kill it.");
}

if (nf <= 0) {
nf = 0;
System.out.println("Monster's Final HP "+ nx +". You died! It took "+count+" times to defeat you.");
}


if (nf <= 0 || nx <= 0) {
battleDone();
break;
}

monhp = nf;
numb = nx;
count++; // add new round to total rounds



} //end while

} //end battle method

} //end class header
When I try to compile it.. I get this:
C:\Users\Dan\Documents\Java\game.java:123: cannot find symbol
symbol : variable fightAgain
location: class game
if (choice.equalsIgnoreCase("fight") || fightAgain.equalsIgnoreCase("Y"))
^
1 error

Tool completed with exit code 1
Uh... the try{ } isn't helping me =\

(I do appreciate all your help.)

PS -
while (monster_hp > 1 && my_hp > 1)
didn't work. But let's worry about that last because when both enemies kill each other on a turn... its like.. rare. :P

ckeyrouz
09-26-2009, 10:58 PM
Buddy you have added a new variable to your code.
The variable fightAgain does not exist in the version I have.

Check where you have added it and put it as global and do not declare another variable with the same name inside any if or else of your code.

UrbanTwitch
09-26-2009, 11:00 PM
But this fightAgain.equalsIgnoreCase("Y")
is suppose to be related to this:public static void battleDone(){ // battle finish method
InputStreamReader istream = new InputStreamReader(System.in) ;
BufferedReader bufRead = new BufferedReader(istream);
System.out.println("\n\nBattle has finished.\n\nFight again?\nY/N");
try {
String fightAgain = bufRead.readLine();
}
catch (IOException ioe)
{
System.out.println("An unexpected error occured.");
}//end catch errors
}

See where it says String fightAgain = bufRead.readLine();
It's asking if they wanna fight again.

-------
whoops here's new code:
/**
DUNGEON CRAWL PROJECT
Programmer: Dan Jasnowski
Date: 9.24.2009

TO DO TASK:

-- after user inputs name...
ROLL Dice
If user rolls 80 or above... get attacked.
roll ANOTHER dice...
if user rolls 50 or above.. get attacked by BAT
ELSE get attacked by ORC
if user rolls 79 or below... keep walking...
**/

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Random;


public class game
{
public String readLinesFromFile(int start, int end)
{
String info = "";
BufferedReader in;
try
{
in = new BufferedReader (new FileReader("stats.txt"));
for (int i = 0; i < start; i++) { info = in.readLine(); }
for (int i = start; i < end + 1; i++)
{
info = in.readLine();
}
in.close();
}
catch (IOException ioe)
{
System.out.println("An unexpected error occured." + ioe.getMessage());
}//end catch errors
return info;
}

public void printIntro()
{
System.out.println("\t\t\tWelcome to...\n");
System.out.println("\t\t___ ___ _ _ _ ");
System.out.println("\t\t| \\/ | | | (_) | ");
System.out.println("\t\t| . . |_ _ ___| |_ _| | __");
System.out.println("\t\t| |\\/| | | | / __| __| | |/ /");
System.out.println("\t\t| | | | |_| \\__ \\ |_| | < ");
System.out.println("\t\t\\_| |_/\\__, |___/\\__|_|_|\\_\\");
System.out.println("\t\t __/ | ");
System.out.println("\t\t |___/ ");
}

public static void main(String args[])
{
game game = new game();
String globalCom = "What would you like to do?\nfight | buy | stats";
int hp = 100;

FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object

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

game.printIntro();

File f1 = new File("stats.txt");
InputStreamReader istream = new InputStreamReader(System.in) ;
BufferedReader bufRead = new BufferedReader(istream);

try
{
if (f1.exists() == false)
{
System.out.println("\n\nWhat is your name?");
String name = bufRead.readLine();
//print the data entered by the user
System.out.println("\nWelcome to Mystik, " + name +"...\n\nYou feel light headed as you wake up from a room with no doors. You feel cold and sleepy yet you manage to stumble onto your feet.");
System.out.println("\nYou then go through the trapdoor and discover a long and trecherous road...");
out = new FileOutputStream("stats.txt");
p = new PrintStream( out );
p.println (name);
p.println("500");
p.println("1");
p.println("1");
p.println("1");
p.close();
}
else
{
FileInputStream fstream = new FileInputStream("stats.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File
strLine = br.readLine();
System.out.println(" \nWelcome back, " + game.readLinesFromFile(0,0));
System.out.println("Gold: " + game.readLinesFromFile(1,1));
System.out.println("Current Level: "+ game.readLinesFromFile(2,2));
System.out.println("EXP: " + game.readLinesFromFile(3,3));
System.out.println("Room " + game.readLinesFromFile(4,4));
System.out.println("\n");
in.close();
}

System.out.println(globalCom);
String choice = bufRead.readLine();

//BATTLE

if (choice.equalsIgnoreCase("fight") || fightAgain.equalsIgnoreCase("Y"))
{
battle();
}//end if typed FIGHT


//buy stuff
if (choice.equalsIgnoreCase("buy") == true)
{
System.out.println("What would you like to buy? \niron sword | heal potion");
String buy = bufRead.readLine();

if (buy.equalsIgnoreCase("iron") == true)
{
System.out.println("up" +buy);
}
else
{
System.out.println("dxownx" +buy);
}
}
//end stuff
} //end try
catch (IOException ioe)
{
System.out.println("An unexpected error occured.");
}//end catch errors
}//end main method


public static void battleDone(){ // battle finish method
InputStreamReader istream = new InputStreamReader(System.in) ;
BufferedReader bufRead = new BufferedReader(istream);
System.out.println("\n\nBattle has finished.\n\nFight again?\nY/N");
try {
String fightAgain = bufRead.readLine();
}
catch (IOException ioe)
{
System.out.println("An unexpected error occured.");
}//end catch errors
}


public static void battle(){

Random diceRoller = new Random();

int count = 0;
int monhp = 100;
int numb = 100;


while (monhp > 1 || numb > 1) { // while either monster or user's hp is 1 or higher... do this
int nit = diceRoller.nextInt(20); // what you hit
int otherx = diceRoller.nextInt(20); // what a goblin hits
int nf = monhp-nit;
int nx = numb-otherx;


if (nf <= 0) { // if monster's hp is below zero.. set to zero
nf = 0;
}
if (nx <= 0 ) { // if user's hp is below zero.. set to zero
nx = 0;
}

if (nx > 1) {
System.out.println("MONSTER hit for "+nit+"\nYOUR Old HP: "+monhp+"\nYOUR New HP: " + nf +"\n\n----\n");
}
if (nf > 1) {
System.out.println("YOU hit for "+otherx+"\nMONSTER's Old HP: "+numb+"\nMONSTER's New HP: " + nx+"\n\n----\n");
}

if (nx <= 0 ) {
nx = 0;
System.out.println("Your Final HP "+ nf+". You killed the monster! It took "+count+" times for you to kill it.");
}

if (nf <= 0) {
nf = 0;
System.out.println("Monster's Final HP "+ nx +". You died! It took "+count+" times to defeat you.");
}


if (nf <= 0 || nx <= 0) {
battleDone();
break;
}

monhp = nf;
numb = nx;
count++; // add new round to total rounds



} //end while

} //end battle method

} //end class header
(the one that won't compile)

ckeyrouz
09-26-2009, 11:10 PM
Once again you are not taking care of the global variables.
/**
DUNGEON CRAWL PROJECT
Programmer: Dan Jasnowski
Date: 9.24.2009

TO DO TASK:

-- after user inputs name...
ROLL Dice
If user rolls 80 or above... get attacked.
roll ANOTHER dice...
if user rolls 50 or above.. get attacked by BAT
ELSE get attacked by ORC
if user rolls 79 or below... keep walking...
**/

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Random;


public class Game
{
private static String fightAgain;
public String readLinesFromFile(int start, int end)
{
String info = "";
BufferedReader in;
try
{
in = new BufferedReader (new FileReader("stats.txt"));
for (int i = 0; i < start; i++) { info = in.readLine(); }
for (int i = start; i < end + 1; i++)
{
info = in.readLine();
}
in.close();
}
catch (IOException ioe)
{
System.out.println("An unexpected error occured." + ioe.getMessage());
}//end catch errors
return info;
}

public void printIntro()
{
System.out.println("\t\t\tWelcome to...\n");
System.out.println("\t\t___ ___ _ _ _ ");
System.out.println("\t\t| \\/ | | | (_) | ");
System.out.println("\t\t| . . |_ _ ___| |_ _| | __");
System.out.println("\t\t| |\\/| | | | / __| __| | |/ /");
System.out.println("\t\t| | | | |_| \\__ \\ |_| | < ");
System.out.println("\t\t\\_| |_/\\__, |___/\\__|_|_|\\_\\");
System.out.println("\t\t __/ | ");
System.out.println("\t\t |___/ ");
}

public static void main(String args[])
{
Game game = new Game();
String globalCom = "What would you like to do?\nfight | buy | stats";
int hp = 100;

FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object

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

game.printIntro();

File f1 = new File("stats.txt");
InputStreamReader istream = new InputStreamReader(System.in) ;
BufferedReader bufRead = new BufferedReader(istream);

try
{
if (f1.exists() == false)
{
System.out.println("\n\nWhat is your name?");
String name = bufRead.readLine();
//print the data entered by the user
System.out.println("\nWelcome to Mystik, " + name +"...\n\nYou feel light headed as you wake up from a room with no doors. You feel cold and sleepy yet you manage to stumble onto your feet.");
System.out.println("\nYou then go through the trapdoor and discover a long and trecherous road...");
out = new FileOutputStream("stats.txt");
p = new PrintStream( out );
p.println (name);
p.println("500");
p.println("1");
p.println("1");
p.println("1");
p.close();
}
else
{
FileInputStream fstream = new FileInputStream("stats.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File
strLine = br.readLine();
System.out.println(" \nWelcome back, " + game.readLinesFromFile(0,0));
System.out.println("Gold: " + game.readLinesFromFile(1,1));
System.out.println("Current Level: "+ game.readLinesFromFile(2,2));
System.out.println("EXP: " + game.readLinesFromFile(3,3));
System.out.println("Room " + game.readLinesFromFile(4,4));
System.out.println("\n");
in.close();
}

System.out.println(globalCom);
String choice = bufRead.readLine();

//BATTLE

if (choice.equalsIgnoreCase("fight") || fightAgain.equalsIgnoreCase("Y"))
{
battle();
}//end if typed FIGHT


//buy stuff
if (choice.equalsIgnoreCase("buy") == true)
{
System.out.println("What would you like to buy? \niron sword | heal potion");
String buy = bufRead.readLine();

if (buy.equalsIgnoreCase("iron") == true)
{
System.out.println("up" +buy);
}
else
{
System.out.println("dxownx" +buy);
}
}
//end stuff
} //end try
catch (IOException ioe)
{
System.out.println("An unexpected error occured.");
}//end catch errors
}//end main method


public static void battleDone(){ // battle finish method
InputStreamReader istream = new InputStreamReader(System.in) ;
BufferedReader bufRead = new BufferedReader(istream);
System.out.println("\n\nBattle has finished.\n\nFight again?\nY/N");
try {
fightAgain = bufRead.readLine();
}
catch (IOException ioe)
{
System.out.println("An unexpected error occured.");
}//end catch errors
}


public static void battle(){

Random diceRoller = new Random();

int count = 0;
int monhp = 100;
int numb = 100;


while (monhp > 1 || numb > 1) { // while either monster or user's hp is 1 or higher... do this
int nit = diceRoller.nextInt(20); // what you hit
int otherx = diceRoller.nextInt(20); // what a goblin hits
int nf = monhp-nit;
int nx = numb-otherx;


if (nf <= 0) { // if monster's hp is below zero.. set to zero
nf = 0;
}
if (nx <= 0 ) { // if user's hp is below zero.. set to zero
nx = 0;
}

if (nx > 1) {
System.out.println("MONSTER hit for "+nit+"\nYOUR Old HP: "+monhp+"\nYOUR New HP: " + nf +"\n\n----\n");
}
if (nf > 1) {
System.out.println("YOU hit for "+otherx+"\nMONSTER's Old HP: "+numb+"\nMONSTER's New HP: " + nx+"\n\n----\n");
}

if (nx <= 0 ) {
nx = 0;
System.out.println("Your Final HP "+ nf+". You killed the monster! It took "+count+" times for you to kill it.");
}

if (nf <= 0) {
nf = 0;
System.out.println("Monster's Final HP "+ nx +". You died! It took "+count+" times to defeat you.");
}


if (nf <= 0 || nx <= 0) {
battleDone();
break;
}

monhp = nf;
numb = nx;
count++; // add new round to total rounds



} //end while

} //end battle method

} //end class header

You are defining the variable in another method.

Can I suggest that you really try to correct your problems before Posting.

I don't have a problem helping you no matter how long it takes.

But the point that you are making the same problem continuously and/or in different forms means that you are not benefiting from help that was given to you.

You compile it runs, you go and change, there is a problem, you post.

Work harder.

UrbanTwitch
09-27-2009, 12:28 AM
Sorry. :(

Question: Is there a way to make it so the script starts back at the main method public static void main(String args[])
{?

--- edit i just answered my own question!
put it in a method than call back to it! :D

question: is there a way to terminate the console? like type quit and it will exit/close?(i tried google)

ckeyrouz
09-27-2009, 01:22 AM
To exit a java application that is running you have two ways:
manual (Ctrl +C)
Programmatical way (System.exit(0))


Use any of them.

UrbanTwitch
09-27-2009, 02:11 AM
Thank you so much.
Here is my RPG so far.
/**
DUNGEON CRAWL PROJECT
Programmer: Dan Jasnowski
Date: 9.24.2009

Massive thanks to...
ckeyrouz
notk0

TO DO
ADD EXP IF WON
ADD GOLD IF WON
check for monster types
--

Add health 20+ when health potion bought

---

If user's hp is zero... end the game and lose some hp and gold.

--

weapons system...
**/

import java.io.*;
import java.util.*;

public class game
{
private static String fightAgain;
private static String globalCom = "What would you like to do?\nfight | buy | stats | quit";
private static File f1 = new File("stats.txt");

public String readLinesFromFile(int start, int end)
{


String info = "";
BufferedReader in;
try
{
in = new BufferedReader (new FileReader("stats.txt"));
for (int i = 0; i < start; i++) { info = in.readLine(); }
for (int i = start; i < end + 1; i++)
{
info = in.readLine();
}
in.close();
}
catch (IOException ioe)
{
System.out.println("An unexpected error occured." + ioe.getMessage());
}//end catch errors
return info;
}



public static void printIntro()
{

game game = new game();


System.out.println("\t\t\tWelcome to...\n");
System.out.println("\t\t___ ___ _ _ _ ");
System.out.println("\t\t| \\/ | | | (_) | ");
System.out.println("\t\t| . . |_ _ ___| |_ _| | __");
System.out.println("\t\t| |\\/| | | | / __| __| | |/ /");
System.out.println("\t\t| | | | |_| \\__ \\ |_| | < ");
System.out.println("\t\t\\_| |_/\\__, |___/\\__|_|_|\\_\\");
System.out.println("\t\t __/ | ");
System.out.println("\t\t |___/ ");
try
{
if (f1.exists() == true)
{
System.out.println(" \nWelcome back, " + game.readLinesFromFile(0,0));
System.out.println("Gold: " + game.readLinesFromFile(1,1));
System.out.println("HP: " + game.readLinesFromFile(5,5)+"/" + game.readLinesFromFile(6,6));
System.out.println("Current Level: "+ game.readLinesFromFile(2,2));
System.out.println("EXP: " + game.readLinesFromFile(3,3));
System.out.println("Room " + game.readLinesFromFile(4,4));
System.out.println("\n");
}
}
finally {}
}

public static void main(String args[]) // MAIN METHOD *******************************************************
{


printIntro();

/**
try {
BufferedWriter game = new BufferedWriter(new FileWriter("outfilename.txt"));
game.write("aString");
game.close();
} catch (IOException e) {
}
**/

doMain();

}//end main method

private static void doMain(){
game game = new game();


FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object

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




InputStreamReader istream = new InputStreamReader(System.in) ;
BufferedReader bufRead = new BufferedReader(istream);



try
{

if (f1.exists() == false)
{
System.out.println("\n\nWhat is your name?");
String name = bufRead.readLine();
//print the data entered by the user
System.out.println("\nWelcome to Mystik, " + name +"...\n\nYou feel light headed as you wake up from a room with no doors. You feel cold and sleepy yet you manage to stumble onto your feet.");
System.out.println("\nYou then go through the trapdoor and discover a long and trecherous road...\n\n");
out = new FileOutputStream("stats.txt");
p = new PrintStream( out );
p.println(name);
p.println("500"); // gold
p.println("1"); // level
p.println("1"); // exp
p.println("1"); // room
p.println("100"); // current hp
p.println("100"); // max hp
p.close();
}
if (f1.exists() == true ) {
int hp = Integer.parseInt(game.readLinesFromFile(5,5));
}

System.out.println(globalCom);
String choice = bufRead.readLine();



if (choice.equalsIgnoreCase("fight"))
{
battle();
}else if (choice.equalsIgnoreCase("stats")) {
System.out.println("\n----------------------------------------");
System.out.println("|\tCharacter name: " + game.readLinesFromFile(0,0)+"\t |");
System.out.println("|\tGold: " + game.readLinesFromFile(1,1)+" \t |");
System.out.println("|\tHP: " + game.readLinesFromFile(5,5)+"/" + game.readLinesFromFile(6,6)+"\t\t |");
System.out.println("|\tCurrent Level: "+ game.readLinesFromFile(2,2)+" \t |");
System.out.println("|\tEXP: " + game.readLinesFromFile(3,3)+" \t |");
System.out.println("|\tCurrent Room " + game.readLinesFromFile(4,4)+" \t |");
System.out.println("----------------------------------------\n\n");
System.out.println(globalCom);
String statin = bufRead.readLine();
if (statin.equalsIgnoreCase("buy") == true)
{
buyItems();
}else if (statin.equalsIgnoreCase("fight") == true)
{
battle();
}

}else if (choice.equalsIgnoreCase("buy") == true )
{

buyItems();
}else {
quit();

}


//buy stuff

//end stuff
} //end try
catch (IOException ioe)
{
System.out.println("An unexpected error occured.");
}//end catch errors
}

public static void quit() {

InputStreamReader istream = new InputStreamReader(System.in) ;
BufferedReader bufRead = new BufferedReader(istream);

System.out.println("Do you really want to quit? Type Y to quit...");
try {
String ansquit = bufRead.readLine();

if (ansquit.equalsIgnoreCase("Y") == true)
{
System.out.println("\nSee ya next time!\n");
}else{
doMain();
}
}
catch (IOException ioe) {
System.out.println("An unexpected error occured.");
}//end catch errors
}

public static void buyItems() { // BUY METHOD *******************************************************



game gold = new game();

FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object


String uname = gold.readLinesFromFile(0,0);
String get_gold = gold.readLinesFromFile(1,1);
String lvl = gold.readLinesFromFile(2,2);
String exp = gold.readLinesFromFile(3,3);
String room = gold.readLinesFromFile(4,4);
String currenthp = gold.readLinesFromFile(5,5);
String maxhp = gold.readLinesFromFile(6,6);

int newgold = Integer.parseInt(get_gold);
int getHp = Integer.parseInt(currenthp);


InputStreamReader istream = new InputStreamReader(System.in) ;
BufferedReader bufRead = new BufferedReader(istream);

System.out.println("What would you like to buy? \n1. iron sword \n2. heal potion \n3. schtuff");
try {


String buy = bufRead.readLine();

if (buy.equalsIgnoreCase("iron sword") == true)
{

out = new FileOutputStream("stats.txt");
if (newgold >= 1) {
System.out.println("You bought an iron sword!");
p = new PrintStream( out );
int newf = newgold-100;
p.println(uname);
p.println(newf);
p.println(lvl);
p.println(exp);
p.println(room);
p.println(currenthp);
p.println(maxhp);
p.close();
doMain();
}else{
System.out.println("\n\nInsufficent funds!");
doMain();
}
}
else if (buy.equalsIgnoreCase("heal potion") == true)
{
out = new FileOutputStream("stats.txt");
if (newgold >= 1) {

int hpheal = 20;
int healed_hp = hpheal+getHp;
int newf = newgold-20;

System.out.println("After buying the heal potion, you drink it.\n\nYou were healed for "+hpheal);
p = new PrintStream( out );

p.println(uname);
p.println(newf);
p.println(lvl);
p.println(exp);
p.println(room);
p.println(healed_hp);
p.println(maxhp);
p.close();
doMain();
}else{
System.out.println("\n\nInsufficent funds!");
doMain();
}
doMain();
}
else if (buy.equalsIgnoreCase("schtuff") == true)
{
System.out.println("You bought schtuff... You just wasted money becauase you didn't get in back in return!");
doMain();
}else if (buy.equalsIgnoreCase("quit"))
{
quit();
}else{
System.out.println("You didn't type anything or typed in them item wrong. Therefor you haven't bought anything.");
doMain();
}
}catch (IOException ioe)
{
System.out.println("An unexpected error occured.");
}//end catch errors
}

public static void battleDone(){ // battle finish method
InputStreamReader istream = new InputStreamReader(System.in) ;
BufferedReader bufRead = new BufferedReader(istream);
System.out.println("\n\nBattle has finished.\n\nFight again?\nY/N");
try {
fightAgain = bufRead.readLine();
}

catch (IOException ioe)
{
System.out.println("An unexpected error occured.");
}//end catch errors
if (fightAgain.equalsIgnoreCase("Y"))
{
battle();
}else if (!fightAgain.equalsIgnoreCase("Y"))
{
doMain();
}//end if typed FIGHT
}


public static void battle()
{
Random diceRoller = new Random();
Random monsterRoller = new Random();
Random getMonster = new Random();
int total_rounds = 0;
int monster_hp = 100;
int my_hp = 100;

game gold = new game();

FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object


String uname = gold.readLinesFromFile(0,0);
String get_gold = gold.readLinesFromFile(1,1);
String lvl = gold.readLinesFromFile(2,2);
String exp = gold.readLinesFromFile(3,3);
String room = gold.readLinesFromFile(4,4);
String currenthp = gold.readLinesFromFile(5,5);
String maxhp = gold.readLinesFromFile(6,6);

int typeMonster = getMonster.nextInt(10);
String monster;
if (typeMonster > 5)
{
monster = "Ogre";
}
else
{
monster = "Goblin";
}

while (monster_hp > 1 || my_hp > 1)
{ // while either monster or user's hp is 1 or higher... do this
int my_hit = diceRoller.nextInt(20); // what you hit
int monster_hit = 0;
if (typeMonster > 5)
{
monster_hit = monsterRoller.nextInt(50); // ogre hit
}
else
{
monster_hit = monsterRoller.nextInt(20); //goblin hit
}

int mon_hp = monster_hp - my_hit;
int new_hp = my_hp - monster_hit;

if (mon_hp <= 0)
{ // if monster's hp is below zero.. set to zero
mon_hp = 0;
}
if (new_hp <= 0)
{ // if user's hp is below zero.. set to zero
new_hp = 0;
}

//display monster messages
if (new_hp > 1)
{
System.out.println(monster+" hit for " + monster_hit + "\nYOUR Old HP: " + monster_hp + "\nYOUR New HP: " + mon_hp + "\n\n----\n");
}

//end monster messages

if (mon_hp > 1)
{
System.out.println("YOU hit for " + my_hit + "\n"+monster+"'s Old HP: " + my_hp + "\n"+monster+"'s New HP: " + new_hp + "\n\n----\n");
}

if (new_hp <= 0)
{
new_hp = 0;
System.out.println("Your Final HP " + mon_hp + ". You killed the monster! It took " + total_rounds + " times for you to kill it.");
}

if (mon_hp <= 0)
{
mon_hp = 0;
System.out.println("Monster's Final HP " + new_hp + ". You died! It took " + total_rounds + " times to defeat you.");
}

if (mon_hp <= 0 || new_hp <= 0)
{
int getHp = Integer.parseInt(currenthp);
int finalHp = mon_hp;
try {


out = new FileOutputStream("stats.txt");

p = new PrintStream( out );
p.println(uname);
p.println(get_gold);
p.println(lvl);
p.println(exp);
p.println(room);
p.println(finalHp);
p.println(maxhp);
p.close();
}catch (IOException ioe)
{
System.out.println("An unexpected error occured.");
}//end catch errors
System.out.println("Final HP "+finalHp);
battleDone();
break;
}
monster_hp = mon_hp;
my_hp = new_hp;
total_rounds++; // add new round to total rounds

} //end while
} //end battle method



} //end class header

What it can do:
Features

Choose randomly between Ogre and Goblin
Save/Load your stats
Show stats
Buy items


What I plan to do:
For the battle system, I plan on taking the EXP and adding on to it.
If they die, they have to start all over.
When they gain enough EXP, they gain one level and their HP increases.

For the buy, if they buy a heal potion, their current HP increases. I may have to create a new line staying the current HP and total HP.

Also add a new line for equipabbles... if they have the iron sword equipped... you will be able to do more damage.

Yep, this going to be fun!

Thanks!
I have no more questions...