Currently a beginner, I wrote a simple program which uses getters and return values (current course). I'd like to ask when should I use the void solution and the int solution, if both gives me the same outcome?
I really hope the formatting isn't too terrible.
class Database {
String name;
int age;
String getName() {
return name;
}
int getAge() {
return age;
}
int yearsPlusFifty() {
int year = age + 50;
return year;
}
void plusFifty() {
int year2 = age + 50;
System.out.println(year2);
}
}
public static void main(String args[]) {
Database person1 = new Database();
person1.name = "Josh";
person1.age = 30;
int year = person1.yearsPlusFifty();
System.out.println("The age plus 50 is: " + year);
person1.plusFifty();
}
Use the int method (yearsPlusFifty) as that one has one responsibility - to calculate the value. Println in plusFifty is a side effect, which is not desirable. Keep the responsibilities of calculating and printing separate (makes it more reusable, testable, and easier to understand).
Basically, void should be used when your method does not return a value whereas int will be used when your method returns int value.
Now coming to your methods, they both are not same, they are doing two different things:
int yearsPlusFifty() - adding 50 and returning int value
void plusFifty() - better rename to printPlusFifty() - this method does both adding plus printing as well
int yearsPlusFifty() {//only adding and returning int value
int year = age + 50;
return year;
}
void printPlusFifty() {//adding + printing
int year2 = age + 50;
System.out.println(year2);
}
Related
I am learning JAVA OOP, I have to compare the age between 2 objects:
In java Procedural, I will have done:
public static int calculateDifferenceAge(int agePlayer1, int agePlayer2){
int differenceAge = agePlayer1 - agePlayer2;
if(differenceAge < 0){
differenceAge = -differenceAge;
}
return differenceAge;
}
Then
public static void displayDifferenceAge(String namePlayer1, String namePlayer2, int agePlayer1, int agePlayer2){
System.out.println("Age difference between " + namePlayer1 + " and " + namePlayer2 + " is of" + calculateDifferenceAge(agePlayer1, agePlayer2) + " year(s).");
}
}
I don't understand how to create my calculateDifferenceAge() method in OOP ?
In my main file I have this:
List<Player> players = new ArrayList <Player>();
players.add(new Player("Eric", 31, true));
players.add(new Player("Juliette", 27, false));
I am stuck into my 2 methods:
How to subtract the age of 2 objects?
public static int calculateAgeDifference(List <Player> players){
Player differenceAge = (players.get(0) - players.get(1));
return differenceAge;
}
public static void displayCalculateAgeDifference(List <Player> players){
System.out.println(calculateAgeDifference().age);
}
Class Player
public class Player {
public String name;
public int age;
public boolean sex;
public Player(String name, int age, boolean sex){
this.name = name;
this.age = age;
this.sex = sex;
}
you're only missing a little step in your code. The steps to extract the ages of the list should be:
1.- Extract the object from the list
2.- Extract the age of that object (or player, in this case)
3.- Substract the ages
There's some ways to do it, but I would do it this way:
public static int calculateAgeDifference(List<Player> players) {
int age1= players.get(0).age;
int age2= players.get(1).age;
int differenceAge = age1 - age2;
if(differenceAge < 0){
differenceAge = -differenceAge;
}
return differenceAge;
}
I hope that helps. What i've done there is extract the objects player from the list: players.get(0) extracts the first object inside the list, which is a Player. Now that I have a player and it has an age variable i have to extract it with player.age. I collapsed those steps, if you have any questions I can explain you further
Display method:
public static int displayCalculateAgeDifference (List<Player> players){
String name1= players.get(0).name;
String name2= players.get(1).name;
//as you know this method return the difference in a number form
int difference= calculateAgeDifference(players);
System.out.println("Age difference between " + name1 + " and " + name2 + " is of" + difference + " year(s).");
}
Let's start with a class Player. Let's give it a name and an age, and a calculateAgeDifference method. It should look something like,
public class Player {
private int age;
private String name;
public Player(String name, int age) {
this.name = name;
this.age = age;
}
public int calculateAgeDifference(Player player2) {
return Math.abs(this.age - player2.age);
}
}
Then you can call it like
Player a = new Player("Eric", 40);
Player b = new Player("Sally", 51);
System.out.println(a.calculateAgeDifference(b));
You must have a similar Player class. Yours appears to also have a boolean field. It isn't clear why. So I can't speak to that.
Why did your method interface change from two parameters to a list? You can still pass two instances of the object. You can still return the integer age value from the method, no need to create a Frankenstein's Player instance only to hold the age.
I am assuming your Player class has a method getAge() to extract the age value which was passed in in the constructor:
public static int calcAgeDiff(final Player player1, final Player player2) {
int age1 = player1.getAge();
int age2 = player2.getAge();
return Math.abs(age2 - age1);
}
Alternatively, you can add an instance method to your Player class itself to calculate the age difference to a different player:
public class Player {
// fields
// constructor
// getters
public int ageDiffTo(final Player otherPlayer) {
return Math.abs(this.age - otherPlayer.age); // <- a class can always access its private fields, even of other instances
}
}
then call as player1.ageDiffTo(player2)
I am having a little difficulty with a school assignment, long story short I declared two local variables in a method and I need to access those variables outside the method :
public String convertHeightToFeetInches(String input){
int height = Integer.parseInt(input);
int resultFeet = height / IN_PER_FOOT;
int resultInches = height % IN_PER_FOOT;
Math.floor(resultInches);
return input;
}
I would have to print the following string in a different method :
System.out.println("Height: " + resultFeet + " feet " + resultInches + " inches");
Any suggestions?
Thank you.
You can't access local variables outside of the scope they are defined. You need to change what is return by the method
Start by defining a container class to hold the results...
public class FeetInch {
private int feet;
private int inches;
public FeetInch(int feet, int inches) {
this.feet = feet;
this.inches = inches;
}
public int getFeet() {
return feet;
}
public int getInches() {
return inches;
}
}
Then modify the method to create and return it...
public FeetInch convertHeightToFeetInches(String input) {
int height = Integer.parseInt(input);
int resultFeet = height / IN_PER_FOOT;
int resultInches = height % IN_PER_FOOT;
Math.floor(resultInches);
return new FeetInch(resultFeet, resultInches);
}
You can't access local variables from method A in method B. That's why they are local.
Take a look: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
As such, local variables are only visible to the methods in which they
are declared; they are not accessible from the rest of the class.
I recommend to use solution written by #MadProgrammer - create class which contains feet and inches.
You need to create a shared variable that holds your result or you encapsulate the result in a single object and then return to caller method, it may be class like result
public class Result {
public final int resultFeet;
public final int resultInches;
public Result(int resultFeet, int resultInches) {
this.resultFeet = resultFeet;
this.resultInches = resultInches;
}
}
Now, you make a result,
public Result convertHeightToFeetInches(String input){
int height = Integer.parseInt(input);
int resultFeet = height / IN_PER_FOOT;
int resultInches = height % IN_PER_FOOT;
Math.floor(resultInches);
return new Result(resultFeet, resultInches);
}
Use this result in other function to print result.
Result result = convertHeightToFeetInches(<your_input>);
System.out.println("Height: " + result.resultFeet + " feet " + result.resultInches + " inches")
I'm trying to create a class in Java using BlueJ. My class is named Automobile. My goal is to be able to use my Constructor method to create cars with the variables: year, color, brand, number of doors, number of kilometers, if it's automatic (boolean), if it's sold (boolean), a description, and an identification number. All the variables have a set default value, a minimum and a maximum accepted value.
I have to use getVariablename and setVariablename for my methods. My color and brand variables are int, and I made methods to retrieve their String counterparts in a table in my class.
My issue is I don't understand the principle of setting my variable in one method and getting it in another (while making sure it's an accepted value). Also, once I have my Setter and Getter method, what do I have to write down in the creation of my Constructor method?
Up to now, I have this :
public class Automobile {
private static final String[] COLORS = { "Other", "Noir", "Blanc", "Bleu Nuit", "Bleu Clair", "Vert Pomme", "Vert Bouteille", "Taupe", "Argent", "Sable"};
private static final String[] BRANDS = { "Autre", "Mazda", "Toyota", "Ford", "GM", "Hyunday", "BMW", "SAAB", "Honda"};
public static final int COLOR_DEF = 8;
public static final int COLOR_MIN = 0;
public static final int COLOR_MAX = COULEURS.length - 1;
public static final int BRAND_DEF = 4;
public static final int BRAND_MIN = 0;
public static final int BRAND_MAX = MARQUES.length - 1;
public static final double KILO_DEFAULT = 55000;
public static final double KILO_MIN = 15000;
public static final double KILO_MAX = 140000;
public static final int TWO_DOORS = 2;
public static final int FOUR_DOORS = 4;
public static final int DOORS_DEFAULT = FOUR_DOORS;
public static final boolean AUTO_DEF = true;
public static final int YEAR_MIN = 1997;
public static final int YEAR_MAX = 2016;
public static final int YEAR_DEFAUT = 2007;
public static final String COMM_DEFAUT = "";
public static String color (int cou) {
String chainecolor = "";
if (cou >= COLOR_MIN && cou <= COLOR_MAX) {
chainecolor = COLORS[cou];
}
return chainecolor;
} //This method is to return the String value of a color from its int value using the COLORS table. If invalid it returns an empty chain.
public static String brand (int br) {
String chainebrand = "";
if (ma >= BRAND_MIN && ma <= BRAND_MAX) {
chainebrand = BRANDS[br];
}
return chainebrand;
} //same thing for the brand
public Automobile (int brand, int year, int color, boolean automatic, double kilometers,int nbrDoors, String description, boolean sold){
//To be completed
}
//here i'm supposed to create getters that return int values for everything but automatic, sold and description
public void setYear ( int year ) {
if (year >= YEAR_MIN && YEAR <= YEAR_MAX) {
year = year;
}
} // supposed to be the setter for my year, as long as it's within the accepted values
public void setMarque (int brand){
if (brand >= BRAND_MIN && brand <= BRAND_MAX) {
brand = brand;
}
} //same, for the brand
public void setColor (int color) {
if (color >= COLOR_MIN && color <= COLOR_MAX){
color = color;
}
}// same for the color
public void setNbrDoors (int p) {
if (p == TWO_DOORS || p == FOUR_DOORS){
p = p;
}
} // same for the door. I am forced to use (int p) as the variable for this method, which confuses me as to how I will refer to it from nbrDoors up in the Automobile constructor method
} // Automobile
So my difficulties lie in:
Are the examples of setters that I made valid for this purpose? I do not understand the need for p = p, or color = color...
How do I create a getter method that will be able to go pick up the Variable p from setNbrDoors, return its value and have it be used for nbrDoors in the Automobile constructor?
What am I supposed to write in the Constructor method, such as it will be able to get its values from the getters?
This is all because the second part is I will have to create a little code to ask the user to input all the values for variables, then create a table to stock the Cars the user creates.
P.S.: the work is originally in french, so I translated the variable and method names best I could for your better understanding. Also, the variable names, methods, etc are all imposed, I am FORCED to make the class this way exactly.
EDIT: As such, the use of static for brand and color conversion are also imposed. Those 2 methods are solely for returning a String of character from an int value. they are not used in the Constructor. Finally, the exceptions will be handled in the second part of the work using a separate validation loop. The Automobile class is really used solely to handle the creation of the "car" object.
There are few issues with your code:
(1) You did not have any proper instance variables (like year, brand, etc..) for Automobile
(2) You did not use this. to set the instance variables (because you did not create them)enter code here. Just note that, this always refers to the current object, refer here i.e., when you say this.year= year, you are actually assigning the right hand side year value to the current object's year variable (left hand side).
You can refer the below code with comments:
public class Automobile {
private int year;
private int color;
private int brand;
//add other fields
public Automobile (int brand, int year, int color, boolean automatic, double kilometers,int nbrDoors, String description, boolean sold) {
if (year >= YEAR_MIN && year <= YEAR_MAX) {
this.year = year;
} else {
new IllegalArgumentException("Invalid Year Passed to construct Automobile");
}
//Similarly add other validations for brand, color, etc..
}
public void setYear ( int year ) {
if (year >= YEAR_MIN && YEAR <= YEAR_MAX) {
//USE 'this.' as shown below' to set the given year to 'this' object's year
this.year = year;
}
}
public int getYear() {
return year;
}
//Similarly add setters and getters for year, color, brand, etc...
}
1-it's better to use this.p=p to attribute on your object.
2-setNbrDoors, return a void , you cant pick up a variable from it,you should create a getNbrDoors:int getNbrDoors() { return this.p; }
I am doing some homework for my java programming class, but this code is giving me trouble. The online program that grades it says there is a problem with my output, but I really don't see why. Can anyone help?
The assignment:
Write a class named Car that has the following fields:
yearModel: The yearModel field is an int that holds the car's year model.
make: The make field is a String object that holds the make of the car.
speed: The speed field is an int that holds the car's current speed.
In addition, the class should have the following methods :
Constructor : The constructor should accept the car's year model and make as arguments .
These values should be assigned to the object 's yearModel and make fields. The
constructor should also assign 0 to the speed field.
Accessor: The appropriate accessor methods should be implemented to access the values
stored in the object 's yearModel, make, and speed fields.
accelerate: The accelerate method should add 5 to the speed field when it is called.
brake: The brake method should subtract 5 from the speed field each time it is called.
Demonstrate the class in a program that contains a Car object , and then calls the
accelerate method five times. After each call to the accelerate method , get the current
speed of the car and print it on a separate line. Then, call the brake method five times,
each time printing the current speed of the car on a separate line.
My code:
public class Car {
private int yearModel;
private String make;
private int speed;
public Car(int model, String m) {
yearModel = model;
make = m;
speed = 0;
}
public int getYearModel() {
return yearModel;
}
public String getMake() {
return make;
}
public int getSpeed() {
return speed;
}
public int accelerate() {
speed += 5;
return speed;
}
public int brake(int b) {
b -= 5;
return b;
}
}
class CarDemo {
public static void main(String[] args) {
Car c = new Car(1992, "Mustang");
int s = 0;
s = c.getSpeed();
for(int i = 0; i < 5; i++) {
System.out.println("The " + c.getYearModel() + " " + c.getMake() + "is going: " + s);
s = c.accelerate();
System.out.println("Now the " + c.getYearModel() + " " + c.getMake() + "is going: " + s);
}
}
}
Edit:
Based on the suggestions below, I have edited my code to the following; however, the system still says that my output is incorrect.
public class Car{
private int yearModel;
private String make;
private int speed;
public Car(int y, String m){
yearModel = y;
make = m;
speed = 0;
}
public int getYearModel(){
return yearModel;
}
public String getMake(){
return make;
}
public int getSpeed(){
return speed;
}
public void accelerate(){
speed += 5;
}
public void brake(){
speed -= 5;
}
}
class CarDemo{
public static void main(String[] args){
Car theCar = new Car(2010, "Porsch");
for(int i = 0; i < 5; i++){
theCar.accelerate();
System.out.println(theCar.getSpeed());
}
for(int count = 0; count < 5; count++){
theCar.brake();
System.out.println(theCar.getSpeed());
}
}
}
for brake you need to do speed -= 5, not b -= 5. Also I do not think the brake method needs an input argument.
In addition you accelerate 5 times but never brake
Your main issue is the brake method. The requirements state that it should subtract 5 from the current speed. So, you should make it like your accelerate method, but subtracting 5 instead of adding. It shouldn't take in a parameter.
Also, I don't know if this would cause an issue, but your accelerate and brake methods shouldn't return the speed, according to the requirements. Change their return types to void, and remove the return statements.
Lastly, You test main doesn't do exactly what the requirements say to do. Read it carefully to see what it should do, and do EXACTLY what it says.
Follow the specification.
The spec says:
accelerate: The accelerate method should add 5 to the speed field when it is called.
brake: The brake method should subtract 5 from the speed field each time it is called.
These 2 methods have no return type and take no arguments.
So, they should be:
public void accelerate() {
speed += 5;
}
// brake should not take an argument
public void brake() {
// this should be speed, not b
speed -= 5;
}
Additionally, your demo should follow the spec (in comments):
class CarDemo {
public static void main(String[] args) {
//Demonstrate the class in a program that contains a Car object
Car c = new Car(1992, "Mustang");
for (int i = 0; i < 5; i++) {
//and then calls the accelerate method five times.
c.accelerate();
//After each call to the accelerate method, get the current speed of the car and print it on a separate line.
System.out.println(c.getSpeed());
}
for (int i = 0; i < 5; i++) {
//Then, call the brake method five times,
c.brake();
//each time printing the current speed of the car on a separate line.
System.out.println(c.getSpeed());
}
}
}
When working off of a well-written, explicit specification as has been provided for your assignment, it can be very helpful to do what I've done above--include the spec as comments and fill in the code around them.
You're printing The " + c.getYearModel() + " " + c.getMake() + "is going: " + s 5 times. You should put that outside the loop so it's printed once only.
IMHO I don't think you need to be returning the speed from the accelerate() function either. I'd suggest making that a void function and using the getSpeed() method instead of assigning to an intermediate variable.
I am currently taking the Prog Fund I & II class. If you are using Pearson, then this should help. I had the answer correct the first time. You just have to format it correctly in the proper order as so.
import java.util.Scanner;
public class Car
{
private int yearModel; // Holds the car's year model
private String make; // Holds the make of the car
private int speed; // Holds the car's current speed
public static void main(String[] args)
{
// Creates car object
Car vehicle = new Car(2018, "Barbie Mobile");
// Creates object for user input
Scanner keyboard = new Scanner(System.in);
// Holds the speed of the car
int speed = 0;
// Calls accelerate 5 times
vehicle.accelerate();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.accelerate();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.accelerate();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.accelerate();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.accelerate();
speed = vehicle.getSpeed();
System.out.println(speed);
// Calls break 5 times
vehicle.brake();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.brake();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.brake();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.brake();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.brake();
speed = vehicle.getSpeed();
System.out.println(speed);
}
public Car(int year, String maker)
{
// Assigns values to car's year model and make
yearModel = year;
make = maker;
// Assigns 0 to the speed field
speed = 0;
}
/* #return gets year model */
public int getYearModel()
{
return yearModel;
}
/* #return The speed */
public int getSpeed()
{
return speed;
}
/* #return Gets the making of car */
public String getMake()
{
return make;
}
/* Adds 5 to speed when called */
public void accelerate()
{
speed += 5;
}
/* Subtracts 5 from speed when called */
public void brake()
{
speed -= 5;
}
}
I am taking the same class right now, using Pearson Revel. If anyone else comes across this problem, this should help.. Spoiler alert, I will be posting the answer to the problem below
Pearson Revel is such a pain in the butt, they do a horrible job describing how they want the programs structured and output displayed, and if anything is off by even one space or something similar, you lose all points. That being said, the problem demonstrates the calling of the program under "Sample Run" as java Car. So it sounds like the main program that creates a Car object and calls all of it's methods is within the same class (test it out in a text editor, you'll see that if you create a seperate class under the Car class and call Car.java from the command line, it will throw an error; stating the class Car does not have a main. So therefore, it's safe to say you need to create the main method inside of the Car class (wish they would just say that, right?).
Here is my graded & passing answer.
public class Car {
private int yearModel;
private String make;
private int speed;
public Car(int year, String make) {
this.yearModel = year;
this.make = make;
this.speed = 0;
}
public void brake() {
this.speed -= 5;
}
public void accelerate() {
this.speed += 5;
}
public int getSpeed() {
return this.speed;
}
public String getMake() {
return this.make;
}
public int getYearModel() {
return this.yearModel;
}
public static void main(String[] args) {
Car myCar = new Car(2019, "Tacoma");
for (int i=0;i < 5;i++) {
myCar.accelerate();
System.out.println(myCar.getSpeed());
}
for (int i=0;i < 5;i++) {
myCar.brake();
System.out.println(myCar.getSpeed());
}
}
}
And here is Revel's suggested answer after completion
public class Car {
public static void main(String[] args) {
Car batmobile = new Car(1965, "Bat Mobile");
for(int i=0; i<5; i++){
batmobile.accelerate();
System.out.println(batmobile.getSpeed());
}
for(int i=0; i<5; i++){
batmobile.brake();
System.out.println(batmobile.getSpeed());
}
}
private int yearModel;
private String make;
private int speed;
public Car(int yearModel, String make){
this.yearModel = yearModel;
this.make = make;
this.speed = 0;
}
public int getYearModel(){
return this.yearModel;
}
public String getMake(){
return this.make;
}
public int getSpeed(){
return this.speed;
}
public void accelerate(){
this.speed += 5;
}
public void brake(){
this.speed -= 5;
}
}
I'm writing a program that simulates simple bank account activities and I was wondering how to do it so that if I create a new Account without any parameters, it receives random 7digit identification number that is shown as String. The way I do, I only receive java.util.Random#2a0364ef in output.
Looking forward to any help and additional comments on this question as it is the first one I've posted on this website.
import java.util.Random;
class Account {
String id;
double stan;
int num;
static int counter;
public Account() {
**id = randomId().toString();**
stan = 0;
num = ++counter;
}
public Account(String id) {
this.id = id;
stan = 0;
num = ++counter;
}
public Account(String id, double mon) {
stan = 0;
this.id = id;
this.stan = mon;
num = ++counter;
}
**static String randomId() {
Random rand = new Random(7);
return String.valueOf(rand);**
}
String getId() {
return id;
}
double getStan() {
return stan;
}
int getNum() {
return num;
}
#Override
public String toString() {
return "Account's id " + getId() + " and balance " + getStan();
}
}
public class Exc7 {
public static void main(String[] args) {
Account account = new Account("0000001"),
acount0 = new Account("0000002", 1000),
acount1 = new Account();
System.out.println(account + "\n" + account0 + "\n" + account1);
}
}
Change return String.valueOf(rand);
To
return String.valueOf(rand.nextInt());
Reason:
You are passing random Object to valueOf method, not the value you need. Call nextInt() method on it to get the desired random value.
Use this code:
Random rand = new Random(7);
return String.valueOf(Math.abs(rand.nextInt()));
Right now you are representing the Random instance.
Instead printing the String representation of the mathematical absolute of the next int of your random will do the trick.
The Math.abs part is important, otherwise you might have negative numbers.
Use
return String.valueOf(rand.nextInt());
otherwise you will get the string representation of the Random object and not of a random int that it can produce.