I am programming an TBAP (Texted base adventure program) just because. I just started it, and I am already having issues with it. What I want to do is have a main class that introduces the program, in output text. At the end of the class it asks "Where would you like to go on your adventures?" It has five options 3 of them are separate adventures of two of them are inventory classes. Right now I am stuck on the my first adventure class. I have an int variable called path. If path == 1, you go to fantasy island class go on your adventure. Is there any to call that adventure with an if statement? I made a constructor and getters and setters with my variables name and path.
Summerproject class:
package summerproject;
import java.util.Scanner;
import static summerproject.Fanastyisland.name;
import static summerproject.Fanastyisland.path;
public class Summerproject {
private static int path;
private static String name;
public Summerproject (int path, String name)
{
this.path = path;
this.name = name;
}
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public int getPath() {
return path;
}
public void setPath(int path) {
this.path = path;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Welcome to the adventure text program! You are the choosen one to save the universe");
System.out.println("Press any key to continue...");
try
{
System.in.read();
}
catch(Exception e)
{}
System.out.println("Welcome. You are the choose one, a legend,a becon of hope to save the universe from the forces of evil.");
System.out.println("Only with you skills and your great power can you destroy the evil doing world.");
System.out.println("Please enter heros name");
name = in.next();
System.out.println("Okay " + name + ", lets begin our adventure!!");
System.out.println("The world can be saved, there is hope. But in order to save the world, \n "
+ "+ you must complete 9 tasks in three diffrent places in three diffrent periods of time. The past, the present and the future.");
System.out.println("Press any key to continue...");
try
{
System.in.read();
}
catch(Exception e)
{}
System.out.println("The three places are the past in the year 1322 in Fantasy island");
System.out.println("The present is the evil little town of Keene N.H.");
System.out.println("And the future to the year 2567 in Space!");
System.out.println("Where would you like to go on your adventures?");
System.out.println(" 1). Fantasy Island");
System.out.println(" 2). Keene");
System.out.println(" 3). Outer space");
System.out.println(" 4). Buy wepons or potions!");
System.out.println(" 5). Sell wepons!");
path = in.nextInt();
if (path == 1)
{
}
}
}
here is my fantasy island class:
package summerproject;
import java.util.Scanner;
import static summerproject.Fanastyisland.name;
import static summerproject.Fanastyisland.path;
public class Fanastyisland extends Summerproject {
public static String name;
public static int path;
public Fanastyisland (String name, int path)
{
super(path,name);
name = name;
path = path;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPath() {
return path;
}
public void setPath(int Path) {
this.path = path;
}
public static void main(String[] args)
//this is where the fantasy island adventure begins.
{
System.out.println("Welcome to fantasy island!!")
}
}
Like I said, I want to call the sub classes with an if statement and I don't know how to do that. If I type in one 1, I want to go to the fantasy island class. I haven't programmed the adventure yet, I will get to it once it is fixed, I just want the output for now to be "Welcome to fantasy island!" when I type 1. Any help would be great! Thank you!
Something like this:
Summerproject adventure = null;
switch (path) {
case 1:
adventure = new FantasyIsland (...);
break;
case 2:
adventure = new Keene (...);
break;
...
default:
System.out.println ("Illegal choice(" & path & "): try again");
}
if (adventure != null) {
adventure.play ();
...
You could just create a common interface
public interface Adventures{
public void start();
}
Every adventure could implement this interface and override the start method
public class AdventureA implements Adventures {
#Override
public void start() {
// Do whatever you want
}
}
You summerproject could simply have a class variable with the type of the interface.
public class Summerproject {
private static int path;
private static String name;
private Adventure adventure;
...
}
Afterwards in the if statements you could just assign this adventure and call the start method.
if (path == 1)
{
adventure = new AdventureA();
adventure.start();
}
Related
public class BookstoreRun {
public static void main(String[] args) {
BookstoreMenu bm = new BookstoreMenu();
bm.mainMenu();
}
}
Here's the menu class:
public class BookstoreMenu {
private Scanner sc = new Scanner(System.in);
private BookstoreController bc = new BookstoreController();
public void mainMenu() {
System.out.println("1. SignUp");
System.out.println("2. Check members list");
System.out.println("Select menu : ");
int menu = sc.nextInt();
switch (menu) {
case 1: {
bc.createAccount();
break;
} case 2:
default:
System.out.println("...");
}
}
}
This is controller class where I made methods:
public class BookstoreController {
private Scanner sc = new Scanner(System.in);
public void createAccount() {
System.out.println("Let's get started");
System.out.print("Your name : ");
String[] strArray = new String[0];
String name = sc.nextLine();
strArray = saveId(strArray, name);
System.out.print(name + ", Nice to meet you!");
System.out.println(Arrays.toString(strArray));
}
public String[] saveId(String[] originArr, String name) {
String[] newArr = new String[originArr.length + 1];
System.arraycopy(originArr, 0, newArr, 0, originArr.length);
newArr[originArr.length] = name;
return newArr;
}
}
I'm trying to make a menu with just two options. The first option is Sign Up through createAccount(); and once I finish signing up, I want to go back to the menu class and choose option 2.
I was thinking I could approach the information of strArray in BookstoreController class by typing bc.~ under case 2 of the switch in the BookstoreMenu class, but I failed.
My question is: Is it possible to approach the value which was made in the local area of another class?
No you cannot. Welcome to the world of Object Oriented Programming OOP & design. One of the more important ideas of OOP is that you encapsulate data and then access it through method calls (or, for other languages, properties).
In this case you should return an Account class from createAccount(). Then you can have a method there to the strArray. That variable should be a field in the Account class and be renamed to something that reflects its purpose, rather than the types it is made up of (string and arrays).
Now, in modern Java, we store objects like accounts in lists, not arrays. Lists can be grown at your leisure. I've put the list into a field of the controller, so it can be maintained in the right controlled location.
Here is some example:
public class BookstoreRun {
public static void main(String[] args) {
BookstoreMenu bm = new BookstoreMenu();
bm.mainMenu(new Scanner(System.in), System.out);
}
}
public class BookstoreMenu {
private BookstoreController bc = new BookstoreController();
public void mainMenu(Scanner sc, PrintStream out) {
while (true) {
// this is a "try with resources", using a localized scanner
int menu;
out.println("1. SignUp");
out.println("2. Check members list");
out.println("9. Quit");
out.println("Select menu : ");
menu = sc.nextInt();
// either menu has been assigned, or an exception has been thrown, so we can now use it
switch (menu) {
case 1:
bc.createAccount(sc, out);
break;
case 2:
bc.displayAccounts(out);
break;
// always leave yourself an exit option
case 9:
out.println("Bye");
System.exit(0);
// the default should display an error or warning
default:
out.println("Unknown option, try again");
}
}
}
}
public class BookstoreController {
// the list of accounts that is initially empty, but may grow
private List<Account> accounts = new ArrayList<Account>();
public void createAccount(Scanner sc, PrintStream out) {
out.println("Let's get started");
out.println("Your name : ");
String name = sc.nextLine();
out.println(name + ", nice to meet you!");
Account account = new Account(name);
accounts.add(account);
}
public void displayAccounts(PrintStream out) {
for (Account account : accounts) {
out.println(account);
}
}
}
// this is the additional "data class"
public class Account {
private String name;
// constructor that assigns the name to the field
public Account(String name) {
this.name = name;
}
// a method to retrieve the property name
public String name() {
return name;
}
// this is what is called when it is printed using println (converted to string)
#Override
public String toString() {
return String.format("Account %s", name);
}
}
Having trouble trying to get my program to work for my AP Computer Science class. Comments have been made inside the code to show my problem. Thanks guys/gals.
Java Class
import java.util.*;
public class Allosaur extends Dinosaur
{
private boolean hungry;
private String response, answer;
private String Allosaur;
// Prompt asks for 3 constructors: A Default constructor, a constructor with just a name, and a constructor with a name and hunger "response"
public Allosaur()
{
}
public Allosaur(String name)
{
Allosaur=name;
}
public Allosaur(String name, boolean hungry)
{
Allosaur=name;
this.hungry=hungry;
}
// Used this method to "find out" whether the dinosaur is hungry or not
public boolean getHunger()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Are you hungry? ");
response = keyboard.next();
if(response.equals("Yes"))
hungry = true;
else if(!response.equals("Yes"))
hungry= false;
return hungry;
}
// Asks us to print out "RRRRRRR" if the dinosaur is NOT hungry and "HUNGRRRRRRRY" if the dinosaur IS hungry
public String roar()
{
if(hungry == true)
answer = "HUNGRRRRRRRY";
else if(hungry == false)
answer = "RRRRRRR";
return answer;
}
//When I use the toString() method in my driver class, none of these pop up, why?
public String toString()
{
String Dino = super.toString();
Dino = "The Dinosaur's name is: " + Allosaur;
Dino += "Is the Dinosaur hungry? :" + getHunger() + "\n" + roar();
return Dino;
}
}
And here is my Driver Class:
public class DinosaurMain extends Allosaur
{
public static void main(String[] args)
{
Allosaur Dino = new Allosaur("Jacob");
Dino.toString();
}
}
I'm very confused as to why nothing will show up when I run the program.
Nothing shows up after the String input is requested because you're simply doing the call in DinosaurMain as Dino.toString(). This just makes the String representation for your object. It doesn't print that String representation out. If you were to change it to System.out.println(Dino.toString()); you would see the result.
I am learning Java and currently attempting to combine if statements and multiple class files.
It is a simple I/O program with a twist, if userName = JDoe I want the program to say something other than the standard saying.
From main.java:
import java.util.Scanner;
import java.lang.String;
class main {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
UInput uInput = new UInput();
System.out.println("What is your name: ");
uInput.setName(input.nextLine());
uInput.saying();
}
}
class ifMain {
public static void main(String[] args){
String userName = "JDoe";
if (test.matches("JDoe")) {
System.out.println("You smell!");
} else {
UInput.saying();
}
}
}
From UInput.java:
public class UInput {
private String userName;
public void setName(String name){
userName = name;
}
public String getName(){
return userName;
}
public void saying(){
System.out.printf("Hello %s", getName());
}
}
However, in class ifMain{}, IntelliJ is saying "Variable userName never used", what am I missing?
See comments:
class ifMain {
public static void main(String[] args){
String userName = "JDoe"; // <=== Declared here
if (test.matches("JDoe")) { // <=== Not used here
System.out.println("You smell!");
} else {
UInput.saying();
}
}
}
The local variable userName is never used in the main method of the ifMain class.
You probably meant:
if (test.matches(userName)) {
Side note: The overwhelming convention in Java is that class names start with an uppercase character. So IfMain, not ifMain.
Your program wouldn't even compile in first place. I believe that you are new to Java. But still, look at this code.
class ifMain {//Please change the class name to CamelCase convention
public static void main(String[] args){
String userName = "JDoe";
if (test.matches("JDoe")) {// Compile error. Variable test is not declared.
System.out.println("You smell!");
} else {
UInput.saying();
}
}
}
Are you trying in a notepad and executing it? You can try using eclipse/NetBeans/IntelliJ IDEs in that case to help you better.
So i've been messing around with String data types in the constructor of my class file, and while everything compiles correctly, when I run the application file, the program doesn't give the desired result. I kept it short to see if it would work, so my class file is as follows:
public class StringPractice
{
private String color;
private String brand;
public StringPractice() {
String color = "";
String brand = "";
}
public StringPractice(String clor, String brnd) {
setColor(clor);
setBrand(brnd);
}
public void setColor(String clor) {
if (clor.equalsIgnoreCase("Red")) {
color = clor;
}
else {
System.out.println("We dont't carry that color");
}
}
public void setBrand(String brnd) {
if (brnd.equalsIgnoreCase("Gibson")) {
brand = brnd;
}
else {
System.out.println("We do not carry that brand");
}
}
public String getColor() {
return color;
}
public String getBrand() {
return brand;
}
public void display() {
System.out.println("Our brands are: " + brand + "Our colors are: " + color);
}
My application file is as follows:
import java.util.Scanner;
public class UseStringPractice
{
public static void main(String[] args)
{
String brand = "";
String color = "";
Scanner keyboard = new Scanner(System.in);
StringPractice Guitar1;
System.out.println("Please enter the brand you would like");
brand = keyboard.next();
System.out.println("Please enter the color you would like");
color = keyboard.next();
Guitar1 = new StringPractice(brand, color);
Guitar1.display();
}
}
What am I doing incorrectly? Am I using the wrong methods to parse the information from scanner? Or am I using equalsIgnoreCase incorrectly? This is my first attempt at implementing these methods, so I may be wayyy off for all I know. When I run the application class, my result is that of the trailing else clause, or, "We do not carry those brands" or "We don't carry that color". Then, in my display statement, the variable names are replaced with "null". This is all for practice so any insight would be fantastic. Thanks!
Your arguments being passed to your constructor should be flipped.
In your application:
Guitar1 = new StringPractice(brand, color);
but in your code:
public StringPractice(String clor, String brnd) {
I am a beginner programmer and this is my first question on this forum.
I am writing a simple text adventure game using BlueJ as a compiler, and I am on a Mac. The problem I ran into is that I would like to make my code more self automated, but I cannot call a class with a string. The reason I want call the class and not have it all in an if function is so that I may incorporate more methods.
Here is how it will run currently:
public class textadventure {
public method(String room){
if(room==street){street.enterRoom();}
}
}
public class street{
public enterRoom(){
//do stuff and call other methods
}
}
The if statement tests for every class/room I create. What I would like the code to do is automatically make the string room into a class name that can be called. So it may act like so:
Public method(string room){
Class Room = room;
Room.enterRoom();
}
I have already looked into using Class.forName, but all the examples were too general for me to understand how to use the function. Any help would be greatly appreciated, and if there is any other necessary information (such as more example code) I am happy to provide it.
-Sebastien
Here is the full code:
import java.awt.*;
import javax.swing.*;
public class Player extends JApplet{
public String textOnScreen;
public void start(){
room("street1");
}
public void room(String room){
if(room=="street1"){
textOnScreen=street1.enterRoom();
repaint();
}
if(room=="street2"){
textOnScreen=street2.enterRoom();
repaint();
}
}
public void paint(Graphics g){
g.drawString(textOnScreen,5,15);
}
}
public abstract class street1
{
private static String textToScreen;
public static String enterRoom(){
textToScreen = "You are on a street running from North to South.";
return textToScreen;
}
}
public abstract class street2
{
private static String textToScreen;
public static String enterRoom(){
textToScreen = "You are on another street.";
return textToScreen;
}
}
Seeing as you are rather new to programming, I would recommend starting with some programs that are simpler than a full-fledged adventure game. You still haven't fully grasped some of the fundamentals of the Java syntax. Take, for example, the HelloWorld program:
public class HelloWorld {
public static void main(String[] args) {
String output = "Hello World!"
System.out.println(output);
}
}
Notice that public is lowercased. Public with a capital P is not the same as public.
Also notice that the String class has a capital S.* Again, capitalization matters, so string is not the same as String.
In addition, note that I didn't have to use String string = new String("string"). You can use String string = "string". This syntax runs faster and is easier to read.
When testing for string equality, you need to use String.equals instead of ==. This is because a == b checks for object equality (i.e. a and b occupy the same spot in memory) and stringOne.equals(stringTwo) checks to see if stringOne has the same characters in the same order as stringTwo regardless of where they are in memory.
Now, as for your question, I would recommend using either an Enum or a Map to keep track of which object to use.
For example:
public class Tester {
public enum Location {
ROOM_A("Room A", "You are going into Room A"),
ROOM_B("Room B", "You are going into Room B"),
OUTSIDE("Outside", "You are going outside");
private final String name;
private final String actionText;
private Location(String name, String actionText) {
this.name = name;
this.actionText = actionText;
}
public String getActionText() {
return this.actionText;
}
public String getName() {
return this.name;
}
public static Location findByName(String name) {
name = name.toUpperCase().replaceAll("\\s+", "_");
try {
return Enum.valueOf(Location.class, name);
} catch (IllegalArgumentException e) {
return null;
}
}
}
private Location currentLocation;
public void changeLocation(String locationName) {
Location location = Location.findByName(locationName);
if (location == null) {
System.out.println("Unknown room: " + locationName);
} else if (currentLocation != null && currentLocation.equals(location)) {
System.out.println("Already in room " + location.getName());
} else {
System.out.println(location.getActionText());
currentLocation = location;
}
}
public static void main(String[] args) {
Tester tester = new Tester();
tester.changeLocation("room a");
tester.changeLocation("room b");
tester.changeLocation("room c");
tester.changeLocation("room b");
tester.changeLocation("outside");
}
}
*This is the standard way of formating Java code. Class names are PascalCased while variable names are camelCased.
String className=getClassName();//Get class name from user here
String fnName=getMethodName();//Get function name from user here
Class params[] = {};
Object paramsObj[] = {};
Class thisClass = Class.forName(className);// get the Class
Object inst = thisClass.newInstance();// get an instance
// get the method
Method fn = thisClass.getDeclaredMethod(fnName, params);
// call the method
fn.invoke(inst, paramsObj);
The comments below your question are true - your code is very rough.
Anyway, if you have a method like
public void doSomething(String str) {
if (str.equals("whatever")) {
// do something
}
}
Then call it like
doSomething("whatever");
In Java, many classes have attributes, and you can and will often have multiple instances from the same class.
How would you identify which is which by name?
For example
class Room {
List<Monster> monsters = new ArrayList <Monster> ();
public Room (int monstercount) {
for (int i = 0; i < monstercount; ++i)
monsters.add (new Monster ());
}
// ...
}
Monsters can have attributes, and if one of them is dead, you can identify it more easily if you don't handle everything in Strings.