How to get my program to print out? - java

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.

Related

Method to get an enumvalue with an inputString

I'm studying Enums in Java and I have a question that isn't working well on my code.
I did my Enum with seconds and some names, and, later, I did a method that looks for it inside the Enum class.
The idea is to start a counter (that's why I'm using the integer values on Enum) given the name of the operation.
The code is:
public enum Calculator {
plus(30), minus(21), divide(21), times(30);
public int seconds;
public int getSeconds() {
return seconds;
}
Calculator(int seconds) {
this.seconds = seconds;
}
private String name;
Calculator(String name) {
this.name = name();
}
public static Calculator contains(String name) {
for (Calculator ss : Calculator.values()) {
if (ss.name.equalsIgnoreCase(name)) {
System.out.println(name + " input " + ss.name + " enum");
return ss;
}
}
throw new NullPointerException("Invalid name");
}
}
And I have another class that invokes this method.
The following invoker is:
public static void calcInput(String name) {
try {
Calculator.contains(name);
} catch(NullPointerException e){
System.out.println("Invalid parameter, " + e );
}
The thing is that, any input I use, a right or wrong one, it is answering me a NullPointerException. Where am I commiting the mistake?
Thanks in advance!
I'm going to walk through your code and make some comments. Then I will show you some changes you could make.
public enum Calculator {
// convention is to name enum values as constants: UPPER_CASE_WITH_UNDERSCORES
plus(30), minus(21), divide(21), times(30);
// you should not make instance fields public, but private
// because they should not be accessed directly by any other class (in general)
public int seconds;
// methods, like this 'getter' belong below all constructors
public int getSeconds() {
return seconds;
}
Calculator(int seconds) {
this.seconds = seconds;
}
private String name;
// this constructor is never used by your enum values (plus, minus, divide, times)
// if it were used, the name parameter in the line below this one is never used for anything
Calculator(String name) {
// you are trying to set your name field to the name() of the enum value.
// even though this would work, this is not very useful
// since calling MY_ENUM_VALUE.name() already gives you its name
this.name = name();
}
// a method like 'contains' usually returns a boolean value to indicate if this instance does or does not
// contain the parameter you provided. Having a 'contains' method which returns a Calculdator instance is
// confusing to say the least. A better name (judging from the method implementation) would be 'forName'
// then you could do:
// Calculator bla = Calculator.forName("Minus");
// System.out.println(bla == Calulcator.minus);
// which would print "true"
public static Calculator contains(String name) {
for (Calculator ss : Calculator.values()) {
if (ss.name.equalsIgnoreCase(name)) {
System.out.println(name + " input " + ss.name + " enum");
return ss;
}
}
// Opinions are mixed on whether you should throw NullPointerExceptions from your application code
// I personally choose to throw IllegalArgumentException in cases like this
throw new NullPointerException("Invalid name");
}
}
Here is a new version of the code which might do what you expect. I don't understand what the 'seconds' values have to do with the calculator operations though.
public enum Calculator {
PLUS(30),
MINUS(21),
DIVIDE(21),
TIMES(30);
private int seconds;
Calculator(int seconds) {
this.seconds = seconds;
}
public int getSeconds() {
return seconds;
}
public static Calculator forName(String name) {
return valueOf(name.toUpperCase());
}
}
The app class:
public class App {
public static void main(String[] args) {
Calculator calculator = Calculator.forName("Minus");
System.out.println(calculator + " seconds = " + calculator.getSeconds());
}
}
The output is:
MINUS seconds = 21

Calling different classes with an if statement in java?

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();
}

Issues using String data type in my constructor, application file not running properly

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) {

Java Postcard Class and printer

I am trying to make a class and a separate printer class for post cards. The idea is to make a postcard that can take user inputs for sender, recipient, and occasion. Then add in something that allows us to send the same postcard to another friend. This is my post card class
public class Postcard
{
private String message;
//define other variables that you need in this class
private String sender;
private String recipiant;
private String occasion;
private String print;
// Methods go here
public Postcard()
{
String message = "Happy holidays too ";
String sender = "Michael";
String recipiant = "";
String occasion = "";
}
public void setmessage(String m)
{
this.message = m;
}
public void setSender(String s)
{
this.sender = s;
}
public void setRecipiant(String r)
{
this.recipiant = r;
}
public void setOccasion(String o)
{
this.occasion = o;
}
public String print()
{
print = message + sender + recipiant + occasion;
return print;
}
}
and this is the post card print class
import java.util.Scanner;
public class PostcardPrinter
{
public static void main(String[] args)
{
String text = "Happy Holiday to ";//write your msg here
Postcard myPostcard = new Postcard(); // use the constructor method
//use the mutator method to set the name of the recipient
Scanner op = new Scanner(System.in);
String recipant = op.nextLine();
String sender = op.nextLine();
String occassion = op.nextLine();
myPostcard.print();
//write the code to send the same msg to another friend
System.out.println("Do you want to send another? Type 'yes' or 'no' ");
String choice = op.nextLine();
while (choice != no)
{
String text = "Happy Holiday to ";
Postcard myPostcard = new Postcard();
Scanner op = new Scanner(System.in);
String recipant = op.nextLine();
String sender = op.nextLine();
String occassion = op.nextLine();
}
}
}
Error's appear in the while loop saying that varriable no doesn't exist and when commented out, nothing happens. Virtual machine is running, but nothing happens. Any help would be greatly appreciated
The line:
while (choice != no)
Is looking for a variable called no, not a string constant. You want:
while (!choice.equals("no"))
Or, the case-insenstive method:
while (!choice.equalsIgnoreCase("no"))
One thing to point out - since the value of choice never changes once inside the loop, you'll basically be looping forever. You'll probably want to ask again after each iteration of the loop. You can probably just set the initial value of choice to an empty string, then immediately start the loop when the program begins. This would allow you to remove the redundant code above the loop.

Java-How do I call a class with a string?

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.

Categories