Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am writing this code in Netbeans for a java class, but I am having a few errors and would really appreciate some help. The assignment is:
Design and implement a stringed musical instrument class using the following guidelines:
Data fields for your instrument should include number of strings, an array of string names representing string names (e.g. E,A,D,G), and boolean fields to determine if the instrument is tuned, and if the instrument is currently playing. You are welcome to add additional data fields if you like.
A constructor method that set the tuned and currently playing fields to false.
Other methods
to tune the instrument
to start the instrument playing, and
to stop the instrument from playing.
Other methods as you see fit (Add at least one unique method).
Create a UML class diagram using a diagram tool (e.g. PPT, Visio) of your choice. Prepare the diagrams and place them in a word document along with a brief description of each of your classes.
Create Java classes for your instruments. Be sure that your code matches your design specifications and some minimal functionality is included. For example, if you called the violin.play() method, you should at least print that the violin is playing. Similar functionality should be supplied when you stop playing, tune or call any of your methods. For example:
public void playviolin() {
System.out.println("The violin is now playing.");
}
Write the output from your Instrument class methods to a text file that a user entered from the command line arguments (e.g. java Mynamep3tst myfilename.txt). This allows your program to accept filenames from the user via a command line argument.
Finally, create a Java test class that simulates using your instrument class. In your test class be you should at a minimum: a) Construct 10 instances of your instrument, b) tune your instruments, c) Start playing your instrument, d) Call your unique method, and e) Stop playing your instruments. (Hint: Arrays and Loops will make your job easier and result in more efficient code!)
So here is my code currently:
package andrewrubinfinalproject;
/**
*
* #author Andy
*/
public class AndrewRubinFinalProject {
public static void main(String[] args) {
//fields to determine if the instrument is isTuned,
private boolean isTuned;
//and if the instrument is currently isPlaying.
private boolean isPlaying;
private String name;
private int numberOfStrings = 4; // number of strings
private String nameofStringsInInstrument[] = {"E", "C", "D", "A"}; //an array of string names
//A constructor method that set the isTuned and currently isPlaying fields to false.
public AndrewRubinFinalProject() {
this.isTuned = false;
this.isPlaying = false;
}
public String getNameOfInstrument() {
return name;
}
public void setNameOfInstrument(String nameOfInstrument) {
this.name = nameOfInstrument;
}
// Other methods
public boolean isPlaying() {
return isPlaying;
}
public void setPlaying(boolean playing) {
this.isPlaying = playing;
}
public boolean isTuned() {
return isTuned;
}
public void setTuned(boolean isTuned) {
this.isTuned = isTuned;
}
public void startPlayInstrument() {
System.out.println("The Instrument is now Playing.");
isPlaying = true;
}
public void stopPlayInstrument() {
System.out.println("The Instrument is not Playing anymore.");
isPlaying = false;
}
public void startTuneInstrument() {
System.out.println("The Instrument is Tuned.");
isTuned = true;
}
public void stopTuneInstrument() {
System.out.println("The Instrument is not Tuned.");
isTuned = false;
}
public int getNumberOfStrings() {
return this.numberOfStrings ;
}
public String[] getStringNames() {
return nameofStringsInInstrument;
}
}
You didn't close your main method. You should insert } before you begin to write other methods.
It's a bad habit to use magic numbers in your code, such as private int numberOfStrings = 4;, what if you change the array? You'll have to change this number too.
Instead, it's better to use .length that returns the size of the array.
It seems your assignment is given to check your OOP concepts.
See the code below, I've given a little touch to your code.
package andrewrubinfinalproject;
/**
*
* #author Andy
*/
public class AndrewRubinFinalProject {
//fields to determine if the instrument is isTuned,
private boolean isTuned;
//and if the instrument is currently isPlaying.
private boolean isPlaying;
private String name;
private int numberOfStrings = 4; // number of strings
private String nameofStringsInInstrument[] = {"E", "C", "D", "A"}; //an array of string names
//A constructor method that set the isTuned and currently isPlaying fields to false.
public AndrewRubinFinalProject() {
this.isTuned = false;
this.isPlaying = false;
}
public String getNameOfInstrument() {
return this.name;
}
public void setNameOfInstrument(String nameOfInstrument) {
this.name = nameOfInstrument;
}
// Other methods
public boolean isPlaying() {
return this.isPlaying;
}
public void setPlaying(boolean playing) {
this.isPlaying = playing;
}
public boolean isTuned() {
return this.isTuned;
}
public void setTuned(boolean isTuned) {
this.isTuned = isTuned;
}
public void startPlayInstrument() {
System.out.println("The Instrument is now Playing.");
this.isPlaying = true;
}
public void stopPlayInstrument() {
System.out.println("The Instrument is not Playing anymore.");
this.isPlaying = false;
}
public void startTuneInstrument() {
System.out.println("The Instrument is Tuned.");
this.isTuned = true;
}
public void stopTuneInstrument() {
System.out.println("The Instrument is not Tuned.");
this.isTuned = false;
}
public int getNumberOfStrings() {
return this.numberOfStrings ;
}
public String[] getStringNames() {
return this.nameofStringsInInstrument;
}
}
The problem is with the positioning of your main method.
First write a class as in the above code.
Then in your main method, make an instance of AndrewRubinFinalProject class by calling the constructor.
public static void main(String[] args){
AndrewRubinFinalProject andrewsObject= new AndrewRubinFinalProject();
// you can call any method in your class with respect to andrewsObject
// e.g.
// andrewsObject.setNameOfInstrument("Violin");
// String x= andrewsObject.getNameOfInstrument()
}
What you must know is that the main method does not necessarily be in the class you are writing. It can be somewhere else in your program.
First you should make at least 2 classes. One is Instrument with all its fields and methods. And another is your main project class that contains main() method and created and uses instruments.
The code that you posted will not be compiled as you opened and not closed the main method.
When first starting out in Object Oriented Programming, write up a small description of the problem, or at least think about it in terms that have enough detail.
Initially, the nouns should become your classes. Abstract groups of nouns might be good candidates for interfaces, and the verbs should become methods belonging to the class that is "closest" to the verb. By closest, I mean that performing the verb will require more access to the attributes in the class.
Related
I'm new to Java programming, sorry if this is a dumb question.
I find it hard to word this question properly, but I have an assignment to create a aircraft class that can make aircraft land, takeoff etc. And need to test it using Testclass. When the new object are entered it automatically assigns a unique ID to the aircraft in the constructor.
I can do this using a instance method fine as it has a return value which is returned to to Testclass. The question wants me to do this in the constructor itself, however, the constructor never returns anything. So the variable never gets sent to the Testclass. I clearly am not understanding OOP properly. Even when I try to just use a getter method to get the ID created in the constructor it gives me the initialized variable before the the constructor has worked on this. This is the code I have so far and its completely wrong I know but if someone could point me in the right direction or tell me how to word this question better it would be a massive help.
// I need to enter 3 aircraft into the system in the testclass
public class Aircraft {
private int aircraftID;
private static int lastID;
private String airportcode;
private int ID = 100;
private int count;
public Aircraft(int a, int b, int c){
// Constructor
// Assign ID
this.ID = a;
lastID = ID;
ID++;
this.ID =b;
lastID = ID;
ID++;
}
}
OK, you want to create an Aircraft that has an automatically-assigned unique identifier, and can take off and land. That implies you need a field for tracking the identifier, a field for tracking whether it's in the air (or not), and methods for the take off and land operations. You also need a static field for generating the unique identifiers. (Note that this implementation isn't thread safe.)
private class Aircraft {
private static int staticId = 0;
private int uniqueId = 0;
private boolean onGround = true; // Aircraft start on the ground in this implementation
public Aircraft(){
this.uniqueId = staticId; // putting this line first makes uniqueId zero-indexed in effect
staticId++;
}
public void land(){
onGround = true;
}
public void takeoff(){
onGround = false;
}
public boolean isFlying(){
return !onGround; // If it's not on the ground, it's flying
}
public int getUniqueId(){
return uniqueId;
}
}
Unit tests checks all of the methods and expected functionality of the class in question:
import org.junit.Test;
import static org.junit.Assert.*;
import Aircraft;
class Testclass {
private final Aircraft aircraft = new Aircraft();
#Test
public void hasId(){
aircraft.getUniqueId() >= 0;
}
#Test
public void canLand(){
assertTrue(aircraft.land());
}
#Test
public void canTakeOff(){
assertTrue(aircraft.takeOff());
}
#Test
public void checkFlightOperationsAreTrackedCorrectly(){
aircraft.land();
assertFalse(aircraft.isFlying());
aircraft.takeOff();
assertTrue(aircraft.isFlying());
}
}
As pointed out a constructor does not return anything (the simplified version is that with new it returns an object instance). I am kinda guessing at what you are trying to acomplish, but I'll have a go anyways. It seems to me that you are trying to cram the construction of 3 objects into one constructor - which is why your constructor has 3 parameters. Also you are playing havoc with the IDs.
I have removed all the variables that I didnt quite understand, leaving only ID that increments with each instantiated Aircraft. The #Override is mainly just for show.
public class Aircraft {
private int aircraftID;
private static int lastID = 0;
#Override
public String toString(){
return "Aircraft_" + this.aircraftID;
}
public Aircraft() {
lastID++;
this.aircraftID = lastID;
}
}
I took the liberty and wrote the TestClass just to see if we have the same thing in mind. Again the printAircraft() method is for show.
public class TestClass {
private List<Aircraft> aircrafts;
public TestClass(){
aircrafts = new ArrayList<>();
}
public void addAircraft(Aircraft a){
aircrafts.add(a);
}
public void printAircraft(){
Iterator<Aircraft> it = aircrafts.iterator();
while(it.hasNext()){
System.out.println(it.next().toString());
}
}
}
and to test it, we create and instance of TestClass add 3 Aircraft instances and print out the contents
public static void main(String[] args) {
TestClass tc = new TestClass();
tc.addAircraft(new Aircraft());
tc.addAircraft(new Aircraft());
tc.addAircraft(new Aircraft());
tc.printAircraft();
}
This would be the case if you are to write the TestClass. If that is given, it would help to know what it looks like - maybe that would help us understand better.
I am relatively new to java and I have been assigned a project. I need to make a rather complicated(for a newbie) battleship game.
Here, I try to call switch cases in class Player from class Tile. Since I've read that one can't directly have access to a switch case, I have made the methods caseSea(), caseShip() e.t.c.
When trying to call them in class Player I get a 'void' type not allowed here error, which I understand but have no idea how to fix!
Any help would be appreciated thanks!
Here is class Tile created to represent one block of a 2D array that will become the battleground board:
public class Tile
{
private int x,y;
static boolean hidden;
public Action tile_action;
public enum Action
{
Sea,
Ship,
Hit,
Miss
}
Action action;
public Tile(Action action)
{
this.action=action;
this.x = x;
this.y = y;
this.tile_action = action;
}
public static void caseSea()
{
System.out.println("~");
}
public static void caseShip()
{
if(hidden == true)
System.out.println("~");
else
System.out.println("s");
}
public static void caseHit()
{
System.out.println("X");
}
public static void caseMiss()
{
System.out.println("O");
}
public static void draw(Action action)
{
switch(action)
{
case Sea:
caseSea();
break;
case Ship:
caseShip();
break;
case Hit:
caseHit();
break;
case Miss:
caseMiss();
break;
}
}
}
Also here is class Player which contains the call to the switch case:
import java.util.Scanner;
public class Player
{
String username; //Variable declaration
static int shotcount;
static int misscount;
static int hitcount;
static int repeatshot;
private int HitPosition[][] = new int[10][10];
public Player(String username)
{
this.username = username;
}
private void placeAllShips()
{
//super.placeAllShips();
}
public void fire(int pos[],int board,boolean hit)
{
if(hit == true)
{
HitPosition[pos[0]][pos[1]] = Tile.draw(Tile.caseHit());
shotcount++;
hitcount++;
}
else
{
HitPosition[pos[0]][pos[1]] = Tile.draw(Tile.caseMiss());
shotcount++;
misscount++;
}
}
}
I get the error that I mention above, in Tile.draw(Tile.caseHit()) and Tile.draw(Tile.caseMiss())
Heh, since this is a relatively simple issue I wanted to stick to comments, but I feel I need to make my voice since the other answers are simply wrong.
What the other guys are suggesting is changing the return type of the methods, and that indeed can work but not with the code you have.
They would ultimately be called twice, and thats not what you want.
The call order would be
caseHit()
pass the caseHit()'s value to draw()
enter a switch inside the draw() method with the Hit enum value and ultimately call caseHit() again.
This is not what you want to do. All you wanna do is call the draw() method with the right argument, which in this case is one of the Action enum values.
So ultimately there is a very easy way to fix your code without much changes and this is changing
Tile.draw(Tile.caseHit());
to
Tile.draw(Tile.Action.Hit);
(and by analogy the other calls of this method)
With Tile.draw(Tile.caseHit()) you are trying to call the caseHit() method and sending the return value of that method as a parameter to the draw() method. The problem is that the caseHit() method isn't returning anything as it has a void return type.
You could fix this by making the caseHit() method return an Action:
public static Action caseHit() {
return Action.Hit;
}
I have this class:
class Inventory {
boolean smallknife = false;
boolean SRLockerkey = false;
void checkinv () {
System.out.println("You have the following items in your inventory: ");
System.out.println(smallknife);
System.out.println(SRLockerkey);
}
}
The Inventory test class
class InvTester {
public static void main(String args[]) {
Inventory TestInv = new Inventory();
System.out.println("This program tests the Inventory");
SKTrue.truth(TestInv.smallknife);
TestInv.checkinv();
}
}
and this class with a method to try to change the inventory
class SKTrue {
static boolean truth(boolean smallknife) {
return true;
}
}
class SKTrue {
static void truth(boolean smallknife) {
smallknife = true;
}
}
I would like to avoid using TestInv.smallknife = SKTrue.truth(TestInv.smallknife) and still change the variable but with a method. Is there a way that this can be done? I want that the truth method does the variable changing and I don't want to do the pass by reference part in the Inventory Test class. Thanks. Is there a way to do this in Java? (I also tried the second version which I think makes more sense)
Assuming you don't want to reference the variables directly (i.e. TestInv.smallknife = blah), the best practice in Java is to declare the variables as private and access them by getters/setters, e.g.:
class Inventory {
private boolean smallknife;
public boolean isSmallknife() {
return smallknife;
}
public void setSmallknife(boolean smallknife) {
this.smallknife = smallknife;
}
}
Now, you can do this:
Inventory TestInv = new Inventory();
TestInv.setSmallknife(SKTrue.truth(blah));
It is called Encapsulation, you can read more about it here.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm tryin to develop a small text-based fighting game and I'm using eclipse to help me out. I have two classes a Hero and Villian.
Hero Code so far:
public class Hero
{
// instance variables - replace the example below with your own
private int Health;
private int Punch;
private int Kick;
private int Special;
/**
* Constructor for objects of class Hero
*/
public Hero()
{
// initialise instance variables
Health = 100;
Punch = -30;
Kick = -25;
Special = -55;
}
Villian Code so far:
public class Villian
{
// instance variables - replace the example below with your own
private int Health;
private int Punch;
private int Kick;
private int Special;
/**
* Constructor for objects of class Villian
*/
public Villian()
{
// initialise instance variables
Health = 100;
Punch = -25;
Kick = -30;
Special = -50;
}
I want to make it turn-based as well so that when the hero attacks, it's the villian's turn. But I'm having trouble trying to construct a suitable method for the attacks. Can someone please help me with this?
The best way to solve this problem is to use inheritance.
You want to have one class called Entity which holds everything all things need on the game field:
public abstract class Entity {
private int Health;
private int attackDmg;
public Entity(int health, int attackDamage) {
this.health = health;
this.attackDamage = attackDamage;
}
}
Then the two classes you currently have simply inherent everything from Entity:
public class Hero extends Entity {
public Hero() {
super(100, 30);
}
}
and Villian:
public class Villian extends Entity {
public Villian() {
super(100, 20);
}
}
Now you probably want to have some methods that makes the Entity take damage. Because everybody should be able to take damage it comes into the Entity class. Also you probably want to have an attack method, that tells you how much damage the entities does:
public abstract class Entity {
// [...]
public void takeDamage(int damage) {
health -= dmg;
}
public void attack() {
return attackDamage;
}
}
Now you can write in your controller class (that handles all of the turn based logic):
player.takeDamage(villian.attack()); (Given that playeris your Playerand villian your Villian).
Of course this only is a small example, you could also make a method that take a String as an argument, which represents the method of the attack (like "kick" or "punch") and then return different amounts depending on the attack type.
Further infos to inheritance:
http://www.tutorialspoint.com/java/java_inheritance.htm and http://beginnersbook.com/2013/05/java-inheritance-types/
You might also be interested in a game making tutorial:
http://www.gametutorial.net/
You might take a variable like flag and set its value to 1 when hero's turn and its value to 0 when villan's turn
if(flag==1)
{
villans turn;
flag=0;
}
else if(flag==0)
{
heros turn;
flag=1;
}
This works
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.