return value for Methods - java

I am writing a program for my assignment, but for my defaultFan and toString methods I am getting an error stating "invalid method declaration; return type required. However I am unsure what how to resolve this. I tried putting void in front of the two methods and it worked but then I get errors stating I cannot assign variables to final variables slow, medium, and fast. I am not sure if this is correct. How would I fix this?
I also have a hard time using test programs. My professor wants us to use a test program that creates 2 fan objets; the first assign maximum speed, radius 10, color yellow and on status. and the second assign medium speed, radius 5 color blue and off status, and to display the fan objects by invoking their toString methods. Would it be possible for someone to explain how test programs work, and how I would go about creating one for this program. Here is my code:
public class fan {
private final int slow = 1;
private final int medium = 2;
private final int fast = 3;
private int speed;
private boolean fanOn;
private double radius;
private String color;
public void defaultFan( )
{
int speed = 1;
boolean fanOn = false;
double radius = 5;
String color = "blue";
}
public fan(final int slow, final int medium, final int fast, int
speed, boolean fanOn, double radius, String color) {
this.slow = slow;
this.medium = medium;
this.fast = fast;
this.speed = speed;
this.fanOn = fanOn;
this.radius = radius;
this.color = color;
}
public final int getSlow(){
return slow;
}
public final int getMedium() {
return medium;
}
public final int getFast() {
return fast;
}
public int getSpeed() {
return speed;
}
public boolean getfanOn() {
return fanOn;
}
public double getradius() {
return radius;
}
public String getcolor() {
return color;
}
public void setSlow(final int slow) {
this.slow = slow;
}
public void setMedium(final int medium) {
this.medium = medium;
}
public void setFast(final int fast) {
this.fast = fast;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public void setFanOn(boolean fanOn) {
this.fanOn = fanOn;
}
public void setRadius(double radius) {
this.radius = radius;
}
public void setColor(String color) {
this.color = color;
}
public void toString() {
if(fanOn = true ) {
System.out.println("The speed of the fan is " + speed + ", the color
of the the fan is " + color + ", and the radius of the fan is " +
radius + ".");
}
else {
System.out.println("The fan is off but the color is " + color +"
and the radius is " + radius + ".");
}
}
}

The variables slow, medium, and fast are final; you set each of them in their declaration, and you need not and cannot reinitialize them. You need to remove them from your constructor:
public fan(int speed, boolean fanOn, double radius, String color) {
this.speed = speed;
this.fanOn = fanOn;
this.radius = radius;
this.color = color;
}
Now, get rid of the setSlow and getSlow methods, etc. Keep the others.
You would want to invoke the constructor with code like:
fan myFan = new fan(/* medium */ 2, true, 10.0, "blue");
// But see 4 and 5 below.
The variables slow, medium, and fast are not tied to any specific instance of fan. So, you want to declare these like so:
public static final int SLOW = 1;
public static final int MEDIUM = 2;
public static final int FAST = 3;
// The constructor call becomes:
fan myFan = new fan(fan.MEDIUM, true, 10.0, "blue");
Typically, classes in Java have capitalized names. Call the class Fan. Replace all instances of fan with Fan.
The toString method should not be so chatty. Typically, people write these methods to help them debug their code, not to provide friendly access to users. Just report the values of the instance variables, which do not include SLOW, MEDIUM, or FAST. Don't use conditional logic.
Your toString method actually overrides the basic one in Object. Java will nag you until you add the #Override annotation. For fun, write your toString code, use it, and then comment the code out. See what happens to the output. You'll see why you need to override the method in Object.
#Override
public String toString() {
return "Fan" + "[speed: " + speed +
",on: " + fanOn +
",radius: " + radius +
",color: " + color + "]";
}
For future work, consider using Java's own Color class instead of a String. Also, consider writing a Java enum of your own named Speed instead of using those three constants.
Ask yourself what someone using the code would want the code to do, both if everything goes right, and if things go wrong or the class is used incorrectly. For example, perhaps the Fan class should obey these rules:
If I construct a Fan, and I ask it for its speed, I get the speed I put in.
Ditto for whether it's on, its radius, and its color.
If I take a Fan, and call a set method on one of its instance variables, and I then query the variable with a get method, I obtain the value I put in.
If I construct a Fan with a negative radius or with null for its color, the constructor fails, throwing an IllegalArgumentException. Your class may not have covered that yet.
Similarly, if I call myFan.setRadius(-10.0), the set method throws the same exception and myFan is left untouched.
If I try to set the speed of a Fan to something other than SLOW, MEDIUM, or FAST, this should fail too. Remember the advice about enums? This is a good reason why.
There are many frameworks to help with software testing; sadly, people don't do it enough in practice. But look up JUnit; your IDE almost certainly has ways to help you create JUnit tests.

Write your toString method like this
public String toString() {
String description = "";
if (fanOn = true) {
description += "The speed of the fan is " + speed
+ ", the color of the the fan is " + color
+ ", and the radius of the fan is " + radius + ".";
} else {
description += "The fan is off but the color is " + color
+ " and the radius is " + radius + ".";
}
return description;
}
I am not sure what you want to do with slow/medium/fast(seems a redundancy with speed). But if you want to modify it, don't declare it as final.
private int slow = 1;
private int medium = 2;
private int fast = 3;
You need a constructor for your test program. (by the way, you should name your class Fan)
public fan(int speed, double radius, String color, boolean fanOn ) {
this.speed = speed;
this.radius = radius;
this.color = color;
this.fanOn = fanOn;
}
Your test program should look like this.
public static void main(String args[]) {
fan fan1 = new fan(100, 100, "red", true);
fan fan2 = new fan(200, 200, "green", false);
}

public void toString()
This is causing the error. Knowingly or Unknowingly, you're trying to override the Object.toString() method, and that's the reason its showing that error. You either need to change the return type of your toString() method to String or change the method name to something else, to avoid conflict with Object.toString().
Apart from the major issue mentioned above, you've a few other bugs as well in your code, which could be resolved with a good IDE.

And for your final question: there are any number of tutorials on testing in Java. Search for JUnit. Here's an example tutorial.

Related

Integer not updating although method should force it

So, I'm creating a text based game in Java and the currency is jellybeans. I have an issue, though. Whenever I set the currency to add 5, it doesn't, and returns 0. Here's the code
public class Util{
public int Jellybeans = 0;
public void jellybeans(int Amount){
Jellybeans = Jellybeans + Amount;
}
public int getJellybeans(){
return Jellybeans;
}
}
public class Tutorial{
Util util = new Util();
private int jellybeanCount = util.getJellybeans();
private void dialog(){
//unrelated irrelevant stuff
util.jellybeans(5);
Util.printAnimatedText("You now have " + jellybeanCount + "
jellybeans!")'
}
}
Any help would be greatly appreciated, this is probably a basic issue but I'm not sure
You're invoking the getJellybeans() in the wrong place. What you need to do is:
Util util = new Util();
private int jellybeanCount;
private void dialog(){
util.jellybeans(5);
jellybeanCount = util.getJellybeans(); // here
Util.printAnimatedText("You now have " + jellybeanCount + "
jellybeans!")'
}
Why is that?
Because when you create the Util object at the beginning, the Jellybeans field is yet empty (or particularly equals ZERO). So when you invoke the getJellybeans(), the field is still has no 5 yet and returns its initial value ZERO.
But the after setting the value of the field to 5 util.jellybeans(5);, you then HAVE a field with a value in it other than zero. You can get now.
Edit
If you really want to have a jellybean counter, and encapsulate it, you should do a few extra things:
public class Util{
private int Jellybeans = 0; //make this variable private, so you only expose it and edit it via getters and setters
public void jellybeans(int Amount){
Jellybeans = Jellybeans + Amount;
}
public int getJellybeans(){
return Jellybeans;
}
}
Util util = new Util();
//private int jellybeanCount = util.getJellybeans(); // this is not needed
private void dialog(){
//unrelated irrelevant stuff
util.jellybeans(5);
Util.printAnimatedText("You now have " + util.getJellybeans() + "
jellybeans!")' // here you use the getter, so you have full control of the state of util class
}
this way, you encapsulate the behavior of your object inside the Util class, that's way you have a class, with an instance variable in the first place.
You are not calling the getJellybeans() methods after calling jellybeans(5).
private int jellybeanCount = util.getJellybeans();
private void dialog(){
//unrelated irrelevant stuff
util.jellybeans(5);
jellybeanCount = util.getJellybeans();
Util.printAnimatedText("You now have " + jellybeanCount +
jellybeans!")'
}
Since int is primitive type and not set by reference in
private int jellybeanCount= ...
you might want to modify this method below to return a value
public int jellybeans(int Amount){
return Jellybeans + Amount;
}
And invoke it as below
jellybeanCount = util.jellybeans(5);
Util.printAnimatedText("You now have " + jellybeanCount + "
jellybeans!")'

Why don't I get a calclatefee result? Is my Array value overriding my overridden method? [duplicate]

This question already has answers here:
Having inheritance and polymorphism issues with Java
(2 answers)
Closed 6 years ago.
I am trying to output calclatefee of $2 per day after 3 days. I have switched things around and I am left at this which looks a little sloppy. This Array is also making me take the confusing way.
public class Movie {
String rating;
String title;
int id;
int rentTime;
public String setrating() {
return rating;
}
public void rating(String getrating) {
rating = getrating;
}
public int setid() {
return id;
}
public void id(int agetid) {
id = agetid;
}
public String settitle() {
return title;
}
public void title(String gettitle) {
title = gettitle;
}
public int setfees() {
return rentTime;
}
public void fees(int getrentTime) {
rentTime = getrentTime;
}
public Movie() {
title = " ";
rating = " ";
id = 0;
rentTime = 0;
System.out.println("default constructor");
}
public Movie(String title, String rating, int id, int rentTime) {
title = " not overridden ";
rating = " NR ";
id = 0;
rentTime = 0;
System.out.println("Overloaded -" + title + rating + id + rentTime);
}
public static void main(String[] args) {
Movie[] Array = {
new Action(" The 100", " pg-13", 105, 7, 3),
new Comedy(" Supernatural", " pg-13", 5, 2, 0),
new Drama(" Lost 2", " R", 9, 2, 0) };
for (int x = 0; x < Array.length; x++) {
// System.out.println(x);
System.out.println(Array[x].toString());
}
}
}
public abstract class Action extends Movie {
protected double latecost;
protected double latefees = 3;
public Action(String gettitle, String getrating, int getid, int getrentTime, double latecost) {
super(gettitle, getrating, getid, getrentTime);
title = gettitle;
rating = getrating;
id = getid;
rentTime = getrentTime;
latecost = latefees;
System.out.println("Overridden " + title + rating + " " + id + " " + " " + rentTime + " "
+ latecost);
}
public double calclatefees(double latecost, double rentTime) {
if (rentTime > 3)
latefees = ((rentTime - 3) * latecost);
return latefees;
}
#Override
public String toString() {
String x = "\nMovie: " + title + " is rated " + rating + "\nMovie ID number: " + id
+ " and the late fee for action movies is $" + latecost + "\n";
return x;
}
protected void finalize() throws Throwable {
try {
System.out.println("Finalize method");
} finally {
super.finalize();
}
}
public void dispose() {
System.out.println(" dispose method");
}
}
Problems:
There's no calclatefee method to override in the parent class. If you want a child class to override method, it must be present in the parent class, at least as an abstract method (if the parent is abstract or is an interface).
You never call your calclatefee method anywhere, so you shouldn't expect to ever see its result in your output.
Your child class, Action, is abstract -- isn't that backwards? Most often its the parent class that's abstract, so why are you structuring it this way? And as written your main method shouldn't compile since you seem to be trying to create an instance of an abstract class.
Your class overrides the finalize() method, something that is generally not recommended. Fortunately your override doesn't really do anything other than output to the standard out and then call the super's method, but still, why risk it?
Side issues
Your code does not follow Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.
You will want to try to improve the formatting of your code that you post in here and your code in general. Good formatting including using an indentation style that is uniform and consistent will help others (us!) to better understand your code, and more importantly, it will help you to better understand your code and thus fix your own bugs. Also it shows that you're willing to put in extra effort to make it easier for the volunteers here to help you, and that effort is much appreciated. I took the liberty of trying to fix this for you.

Java- Integer in program not being updated

Recently, I've been assigned to do a file by my teacher to make a program that simulates a TV.
I am supposed to add volume when the raiseVolume method is called. However, upon calling it, it looks like volume is not being affected whatsoever.
I have no clue as to why this could be.
(myTv is the object of the constructor in Tv)
Here is the Code for the TV Driver Class-
System.out.println ("Crank it up!");
int oldVolume = myTv.getVolume();
do {
oldVolume = myTv.getVolume();
myTv.raiseVolume();
} while (myTv.getVolume() != oldVolume);
System.out.println ("\t\tThe TV is " + myTv.getPower() +
" on channel " + myTv.getChannel() +
" at volume " + myTv.getVolume());
System.out.println ("That's a bit too loud");
myTv.lowerVolume();
myTv.lowerVolume();
and here is my code for the Tv Class-
private int volume = 0;
...
//Volume
public int getVolume(){
return volume;
}
public void raiseVolume(){
volume+=5;
}
public void lowerVolume(){
volume-=1;
if (volume > 0){
volume = 0;
}
}
If you need additional code, I will post it!
I've been called out for putting entire classes in here before, I don't wish to make the same error!
Because when you call lowerVolume after raiseVolume:
public void lowerVolume(){
volume-=1;
if (volume > 0){
volume = 0;
}
}
it will always set the volume to 0, as volume > 0 (at least 5) at that moment, you should change it to:
if (volume < 0){
volume = 0;
}
The two values will never be equal, and your while loop just terminates. Print the volume before and after the call and you'll see that it changes (assuming you're using the code you've posted)
System.out.printf("oldVolume = %d%n", myTv.getVolume());
myTv.raiseVolume();
System.out.printf("newVolume = %d%n", myTv.getVolume());
Also, your lowerVolume method always sets volume to 0 (if it's greater than zero). I think you mean less than
public void lowerVolume(){
volume--; // <-- does - 1
if (volume < 0){ // <-- less than
volume = 0;
}
}
It might be a good idea to add a max for raiseVolume(). Finally, I suggest you set the increment (and decrement) to be the same value (or pass that value in to the method); that is something like
private static final int MAX_VALUE = 100;
private static final int MIN_VALUE = 0;
public void lowerVolume(int change) {
volume -= change;
volume = Math.max(volume, MIN_VALUE);
}
public void raiseVolume(int change) {
volume += change;
volume = Math.min(volume, MAX_VALUE);
}
Or,
public void lowerVolume() {
volume--;
volume = Math.max(volume, MIN_VALUE);
}
public void raiseVolume() {
volume++;
volume = Math.min(volume, MAX_VALUE);
}
try something along the lines of a start volume of 0 so when you getVolume you can write in something like
if(tv.getvolume == 0){
volume++
}

How would I store the health values and run again until either player health == 0 or enemy health == 0

What would be the best way for me to code the the actual attack / defend between the two characters and how would I store the health value so that re attacks could be stored until either player health or enemy health reached 0, and then declare the victor. This is my first ever attempt at any kind programming after self teaching from various sources, please also give me feed back on any improvement I could make, I'm sure there will be many.
Thank you in advance.
:-)
package test;
public class BattleClass {
public static void main(String[] args) {
PlayerStats ps = new PlayerStats();
EnemyStats es = new EnemyStats();
int eh = es.getEnemyHealth();
int ph = ps.getPlayerHealth();
ps.PlayerAttackDefend();
es.AttackDefend();
System.out.println("You chose to " + ps.getpInput() + " and rolled "
+ ps.getPlayerRoll());
System.out.println("The enemy chose to " + es.getEaod()
+ " and rolled " + es.getEnemyRoll() + ".");
if (ps.getpInput().equals("Attack")) {
if (es.getEaod().equals("Attack")) {
System.out
.println("YOUR SWORDS BOUNCE OFF EACHOUTHERS... TRY AGAIN!");
System.exit(0);
}
if (es.getEaod().equals("Defend")) {
if (ps.getPlayerRoll() > es.getEnemyRoll())
eh -= ps.getPlayerRoll() - es.getEnemyRoll();
System.out.println("Enemy Health is " + eh);
}
}
if (ps.getpInput().equals("Defend")) {
if (es.getEaod().equals("Defend")) {
System.out
.println("YOUR SHIELDS BOUNCE OFF EACHOTHERS... TRY AGAIN!");
System.exit(0);
}
}
if (es.getEaod().equals("Attack")) {
if (es.getEnemyRoll() > ps.getPlayerRoll())
ph -= es.getEnemyRoll() - ps.getPlayerRoll();
System.out.println("Your Health is " + ph);
}
}
}
package test;
import java.util.Random;
import java.util.Scanner;
public class PlayerStats {
static Scanner paod = new Scanner(System.in);
//Players initial health value.
private int playerHealth = 10;
//RNG for attack value / defence value using dice as object.
private int playerRoll = new Random().nextInt(6) + 1;
private String pInput;
//Method for selecting Attack or Defence.
public void PlayerAttackDefend() {
System.out.println("Do you want to Attack or Defend?");
System.out.println("a = Attack / d = Defend");
//Player selects attack or defend.
String userInput = paod.nextLine();
if (userInput.equals("a")) {
pInput = "Attack";
}
if (userInput.equals("d")) {
pInput = "Defend";
}
}
public static Scanner getPaod() {
return paod;
}
public int getPlayerHealth() {
return playerHealth;
}
public int getPlayerRoll() {
return playerRoll;
}
public String getpInput() {
return pInput;
}
public static void setPaod(Scanner paod) {
PlayerStats.paod = paod;
}
public void setPlayerHealth(int playerHealth) {
this.playerHealth = playerHealth;
}
public void setPlayerRoll(int playerRoll) {
this.playerRoll = playerRoll;
}
public void setpInput(String pInput) {
this.pInput = pInput;
}
}
package test;
import java.util.Random;
public class EnemyStats {
//Enemy initial health value.
private int enemyHealth = 10;
//RNG for attack value / defence value using dice as object.
private static int enemyRoll = new Random().nextInt(6) + 1;
//RNG for enemy decision to Attack or Defend.
private static int eAttackDefend = new Random().nextInt(2) + 1;
//Used for returning attack or defend string.
private static String eaod;
//Attack or Defend method.
public void AttackDefend() {
if (eAttackDefend == 1) {
eaod = "Attack";
} else {
eaod = "Defend";
}
}
public int getEnemyHealth() {
return enemyHealth;
}
public int getEnemyRoll() {
return enemyRoll;
}
public int geteAttackDefend() {
return eAttackDefend;
}
public String getEaod() {
return eaod;
}
public void setEnemyHealth(int enemyHealth) {
this.enemyHealth = enemyHealth;
}
public void setEnemyRoll(int enemyRoll) {
EnemyStats.enemyRoll = enemyRoll;
}
public void seteAttackDefend(int eAttackDefend) {
EnemyStats.eAttackDefend = eAttackDefend;
}
public void setEaod(String eaod) {
EnemyStats.eaod = eaod;
}
}
An easy way would to be to set maxHp and actualHp values, if you want to be able to "heal".
If you just decrease until one is dead, you can just decrease the actual health variable you already have.
You might wanna take a look at Inheritance in general, as you have a lot of duplicate code.
In general, just make a loop
while(ps.getHealth() > 0 && es.getHealth() > 0) {
// your battle code
}
you might want to remove the System.exit(0) calls, as they terminate the program.
Add to the player/enemy a dealDamage(int damage) method to actually be able to reduce their health
The health values should be in the objects, and you should not need to store them in your BattleClass.
I could give you the short answer but I guess you get more out of a detailed explanation :-)
You want to run your code "until either player health or enemy health reached 0" so you need a loop.
In java you have 3 kinds of loops:
The for loop
for(int i=1;i<=3;i++) System.out.println("Hello Musketeer Nr. "+i);
The most elaborate loop, the for loop consists of three parts, the initialization, the condition, and the afterthought. While the for loop can be used differently, it is mostly is used in the fashion shown here, that is, you have a counter variable whose value you need somehow.
If you don't need the counter variable value, you can use the short form with collections and arrays:
for(Person p: persons) System.out.println("Hello, "+person.getName()+"!");
The while loop
The second most commonly used (at least by me) loop, it has an initial condition and iterates, as long as it is true.
while(ph>0&&eh>0)
{
...
}
As you see, it fits your problem very well. For completeness, I will however describe the third loop which is the
do-while loop
do
{
...
}
while(ph>0&&eh>0)
You use this loop like the while loop but if you want to have at least one run through.
Other Remarks
Why have two classes PlayerStats and EnemyStats in combat system (they both seem to have the same actions and values) ? You could just have:
Stats playerStats=new Stats();
Stats enemyStats=new Stats();

Coins : Invalid Method Declaration, return type required

I just started Computer Science last week, and we got a worksheet called Coins, in which I had to find out how many quarters, dimes, nickels and pennies there are in a set of coins. I am having a lot of trouble, and getting that error. Here's my code
package Coins;
public class Coins
{
private int change;
// two contructors
Change() //default constructor
{
change = 94;
}
Change( int c )
{
change = c;
}
// accessor method - change
public int getChange()
{
return Change;
}
// mutator method - change
public void setChange( int anotherChange)
{
change = anotherChange;
}
public void askUserForChange()
{
Scanner keyIn;
keyIn = new Scanner(System.in);
System.out.print("Please enter the amount of change: ");
String input = keyIn.nextLine();
int nChange = Integer.parseInt (input);
setChange(nChange);
// change = nChange
printChangex();
}
// action method - take accessor figure out coins -> output
// calculating the coins needed for the change
public void printChangeRange(int start, int end)
{
for(int c = start; c <= end; c++
{
setChange(c);
printChangex();
}
}
public void printChangex()
{
int c = change;
int quarter = c / 25;
System.out.println("quarter = " + quarter);
int a = c%25;
int dime = a / 10;
System.out.println("dime = " + dime);
int b = a%10;
int nickel = b / 5;
System.out.println("nickel = " + nickel);
int c = b%5;
int penny = c / 1;
System.out.println("penny = " + penny);
}
// instance variables - replace the example below with your own
private int x;
public Coins()
{
// initialise instance variables
x = 0;
}
public int sampleMethod(int y)
{
// put your code here
return x + y;
}
}
You have a class named Coins and are trying to give it a constructor named Change. The class and constructor must have the same name. Just pick one.
To elaborate on the error in your title, I assume that "Invalid Method Declaration, return type required" refers to the line with Change() //default constructor. Since this is in a class called Coins it is not a constructor as the comment claims. The Java compiler thinks that it is a method. All methods must have a return type, so the compiler complains.
The actual constructors are at the bottom of your code. It is standard practice to put constructors first, so I suggest that you put these poperly-named constructors at the beginning of your Coins class. You probably just need to remove the Change() constructors completely.
Also as a tip for asking questions here, it is extremel critical that you post the complete error message you are getting. My answer is based on some educated guesses and certainly don't solve all the problems in your code. Feel free to come back with more questions as you keep trying to fix your program.
This
// two contructors
Change() //default constructor
{
change = 94;
}
Change( int c )
{
change = c;
}
is unusual. You even have a constructor for the class Coins at the bottom of the file, so you would want to use that. Keep in mind that all Java classes have a constructor that are named the same as the class itself - even if it's the default constructor.
It's even more unusual that it has the magical value of 94 on instantiation...but in all seriousness, pick a class name and stick with it.
This
// accessor method - change
public int getChange()
{
return Change;
}
...is also odd. You may want to return the member variable change instead, so change that to a lower case C.

Categories

Resources