Instance of a Method in a Separate Class/Method? - java

I am creating a small game of Final Fantasy characters, in which I input the name of who I would like to "fight" I have each character (only 5 of them) as a subclass to a superclass called Stats in which the variables (non static) and getters/setters are defined.
The code all works as I would like, but I don't like it all being in One huge class.
The Main method is here;
package com.George.revision;
import java.util.Random;
import com.George.characters.Cloud;
import com.George.characters.Squall;
import com.George.characters.Stats;
import com.George.characters.TheEnemy;
import com.George.characters.ThePlayer;
import com.George.characters.Tidus;
import com.George.characters.Yuna;
import com.George.characters.Zidane;
import com.George.input.GetInput;
import com.George.input.ListNames;
public class Main {
public static void main(String[] args) {
ListNames.listNames();
Stats clo = new Cloud();
Stats squ = new Squall();
Stats zid = new Zidane();
Stats tid = new Tidus();
Stats yun = new Yuna();
String versus = GetInput.getInput("\nWhich of these Characters would you like to go up against?");
Stats ene1 = new TheEnemy();
switch (versus) {
case "Cloud":
ene1.setName(Names.CLOUD);
ene1.setHairColor(Stats.BLONDE);
ene1.setWep(Weapons.BUSTER_SWORD);
ene1.setSkill(clo.skill);
ene1.setAp(clo.ap);
ene1.setStr(clo.str);
ene1.setMag(clo.mag);
break;
case "Squall":
ene1.setName(Names.SQUALL);
ene1.setHairColor(Stats.BLACK);
ene1.setWep(Weapons.LIONHEART);
ene1.setSkill(squ.skill);
ene1.setAp(squ.ap);
ene1.setStr(squ.str);
ene1.setMag(squ.mag);
break;
case "Zidane":
ene1.setName(Names.ZIDANE);
ene1.setHairColor(Stats.LIGHTBROWN);
ene1.setWep(Weapons.THIEF_DAGGER);
ene1.setSkill(zid.skill);
ene1.setAp(zid.ap);
ene1.setStr(zid.str);
ene1.setMag(zid.mag);
break;
case "Tidus":
ene1.setName(Names.TIDUS);
ene1.setHairColor(Stats.BLONDE);
ene1.setWep(Weapons.CALADBOLG);
ene1.setSkill(tid.skill);
ene1.setAp(tid.ap);
ene1.setStr(tid.str);
ene1.setMag(tid.mag);
break;
case "Yuna":
ene1.setName(Names.YUNA);
ene1.setHairColor(Stats.DARKBROWN);
ene1.setWep(Weapons.NIRVANA);
ene1.setSkill(yun.skill);
ene1.setAp(yun.ap);
ene1.setStr(yun.str);
ene1.setMag(yun.mag);
break;
default:
System.out.println("You did not enter a valid character name");
break;
}
System.out.println("You have chosen to face " + ene1.name);
System.out.println("Enemy Skill = " + ene1.skill + " Enemy Weapon = " + ene1.wep);
System.out.println("Enemy Skill = " + ene1.skill + " Enemy Weapon = " + ene1.wep);
int eneTotal = ene1.skill + ene1.ap + ene1.str + ene1.mag;
Stats player = new ThePlayer();
String plN = GetInput.getInput("What is your name?");
player.playerName = plN;
System.out.println("So Your name is " + player.playerName);
String plWep = GetInput.getInput("What is your Weapon's name?");
player.playerWep = plWep;
System.out.println("So your Weapon is " + player.playerWep);
Random generator = new Random();
int plSkill = generator.nextInt(10);
player.skill = plSkill;
System.out.println("Your skill level is " + player.skill);
Random gn = new Random();
int plAp = gn.nextInt(10 - 5) + 5;
System.out.println("So your Attack Power is " + plAp);
player.ap = plAp;
Random gns = new Random();
int plStr = gns.nextInt(10);
System.out.println("So your Strength is " + plStr);
plStr = player.str;
Random gnm = new Random();
int plMag = gnm.nextInt(10 - 5) + 5;
player.mag = plMag;
System.out.println("So your Magic is " + player.mag);
int plHax = 15;
double doubleResult = plHax;
double ene1Hax = 3.99;
int intResult = (int)ene1Hax;
double doubleValue = 6.99;
Double doubleObj = new Double(doubleValue);
int intR = doubleObj.intValue();
System.out.println(intR);
int plyrTotal = player.skill + player.ap + player.str + player.mag;
if (plyrTotal > eneTotal) {
System.out.println("Congratulations you beat " + ene1.name + " Please Play Again!" );
} else if (plyrTotal == eneTotal) {
System.out.println("You drew with " + ene1.name + " Play again and Win!");
}
else
{
System.out.println("You were not succesful this time " + ene1.name + " Defeated you by " + (eneTotal - plyrTotal) + " Please Try Again");
}
}
}
Now after this I have a whole lot more code generating random numbers for the players "stats", and the character, and then matching the total values of their stats to determine "a winner" which I would like to put in a separate class. My issue is,
how do I get ene1 in a separate class with the values that are input in the switch statement in the Main class.
Updated to full main method just for clarity

One of the issues you have is that you are assigning Enemy as a subclass of Stats, but with no relation to your characters. So while the enemy has the same attributes of a character, it has no relationship in which to speak to the character. Instead of copying all of these values like name and color, instead make Enemy it's own entity that holds a Stats value, that shares an interface with stats. The enemy can then use that interface to call various methods in the Stats class.
public class Static implements Actions{
// ...
}
public class Enemy implements Actions{
private Static characterType;
}
Also for future reference, could you please design your questions to be more generic? It not only helps those who don't understand the references, but also makes it easier for people who have similar problems to find this.

You can just pass it into a method (or constructor) of that class as you would any other variable or text. I.e.
clo.setOpponent(ene1);
Then have the implementation of setOpponent be like this
class Stats
{
private Stats opponent;
//ALL OF YOUR OTHER CODE AND METHODS GO HERE
public void setOpponent(Stats enemy)
{
opponent = enemy;
}
}
This doesn't take into account the poor OO design of your application, it only answers your question. Better design comes with more practice and some studying (look up IS-A and HAS-A relationships to help with basic OO design)

In your particular example I would suggest to have Enumerations for the enemies, instead of using class hierarchy, as you have got the same fields for all enemy entities and you're not using any external storage here (like DB, file or whatever).
Class hierarchies are more suitable for situations, when you have several entities which have got both similarities and distinguishes. For example, you can have one class for regular enemies, and one class for 'enforced' enemies with some superskills, so the second class will inherit the first one and will have 1 additional field. This allows you to reduce the code duplicates and provides enough flexibility. Also, class hierarchy gives you some more benefits when you want to save this entities in some storage, for example, DB.
But in you case, it is more logical to use a single Enum to have some set of enemies, which is 'hardcoded' to the application. I would suggest the next solution:
public enum Enemy {
CLOUD("Cloud", "Red", "Sword", 10),
SQUALL("Cloud", "Black", "Minigun", 999)
// and so on
;
public String name;
public String hairColor;
public String wep;
public int skill;
Enemy(String name, String hairColor, String wep, int skill /* and so on */) {
this.name = name;
this.hairColor = hairColor;
this.wep = wep;
this.skill = skill;
}
public static Enemy getByName(String name) {
for (Enemy enemy : Enemy.values()) {
if (enemy.name.equalsIgnoreCase(name)) {
return enemy;
}
}
throw new IllegalArgumentException("Enemy with the name `" + name + "` doesn't exist.");
}
}
And then it is possible to initialize an enemy in the main class by its key name:
String versus = GetInput.getInput("\nWhich of these Characters would you like to go up against?");
try {
Enemy enemy = Enemy.getByName(versus);
} catch (IllegalArgumentException e) { // processing incorrect input
System.out.println(e.getMessage());
}
Then you can pass this constant to any other class to process it and calculate whatever you want:
public class FightCalculator {
public int calculateScore(Enemy enemy) {
// Some calculations here...
}
}

It might help to create separate Hero and Enemy classes. Or if your characters aren't "good" or "bad" guys, perhaps just a Character class. For the following discussion, I will simply use Character, but you can replace this with Hero or Enemy and it should still make sense.
First of all, what is the relationship between a Character and a Stats. I think a Characater has a Stats. This means that Character should have a member variable of type Stats:
class Character {
private Stats stats = new Stats();
}
Now you can add a constructor that a new Stats object for a Character. This means that the Character needs to take several parameters for each of the values stored in a Stats. One advantage of this approach is that you write the code to set up a Stats object just once and then each case statement has just 1 line:
ene1 = new Character(/* all the stats values go here */);
The moral of the story here is that when you find yourself repeating code, you should consider writing a method which encapsulates that repetition.

Related

I have made a Java programme but has repetition problem

I have created that Java programme but it have repetition problem, I want that if one question has done either right or wrong it must not be ask again.
It should ask 10 question only. I have tried alot to change but every time I am getting error.
I have created that Java programme but it have repetition problem, I want that if one question has done either right or wrong it must not be ask again.
It should ask 10 question only. I have tried alot to change but every time I am getting error.
package examapp;
import java.util.Random;
import javax.swing.JOptionPane;
public class Examapp {
static int nQuestions = 0; static int nCorrect = 0;
public static void main(String[] args) {
int prevNum=0;
int sum=0;
do{
Random rand = new Random();
int randomNum = rand.nextInt((11 - 1) + 1) + 1;
if(randomNum==prevNum){
prevNum=randomNum;
}
else if(randomNum==1){
String question1;
question1 = "What was the name of Google in late 90s?\n";
question1+="A. Googol\n";
question1+="B. Gigablast\n";
question1+="C. Backrub\n";
question1+="D. Google\n";
question1+="Marks=9";
check(question1,"C");
sum=sum+1;
}
else if(randomNum==2){
String question2;
question2 = "\"Do no evil\" is a tagline of?\n";
question2+="A. Yahoo\n";
question2+="B. Google\n";
question2+="C. Bing\n";
question2+="D. Duck Duck Go\n";
question2+="Marks=9";
check(question2,"B");
sum=sum+1;
}
else if(randomNum==3){
String question3;
question3 = "Which of the following is fully Object Oriented Programming Language?\n";
question3+="A. SmallTalk\n";
question3+="B. Kotlin\n";
question3+="C. Java\n";
question3+="D. F#\n";
question3+="Marks=9";
check(question3,"A");
sum=sum+1;
}
else if(randomNum==4){
String question4;
question4 = "Which among the following is not a mobile Operating System?\n";
question4+="A. Bada\n";
question4+="B. Safari\n";
question4+="C. WebOS\n";
question4+="D. MeeGo\n";
question4+="Marks=9";
check(question4,"B");
sum=sum+1;
}
else if(randomNum==5){
String question5;
question5 = "Which of the following is a correct format of Email address?\n";
question5+="A. info.website.com\n";
question5+="B. info#website.com\n";
question5+="C. info#website#com\n";
question5+="D. info.website#com\n";
question5+="Marks=9";
check(question5,"B");
sum=sum+1;
}
else if(randomNum==6){
String question6;
question6 = "What is the shortcut key of printing a document for computer having windows?\n";
question6+="A. Ctrl + Shift + P\n";
question6+="B. Alt + P\n";
question6+="C. Ctrl + Alt + P\n";
question6+="D. Ctrl + P\n";
question6+="Marks=9";
check(question6,"D");
sum=sum+1;
}
else if(randomNum==7){
String question7;
question7 = "Computer software includes\n";
question7+="A. Packaged programs\n";
question7+="B. Operating system programs\n";
question7+="C. Applications programs\n";
question7+="D. All of these\n";
question7+="Marks=9";
check(question7,"D");
}
else if(randomNum==8){
String question8;
question8 = "A function inside another function is called a _______ function\n";
question8+="A. Nested\n";
question8+="B. Round\n";
question8+="C. Sum\n";
question8+="D. Grouped\n";
question8+="Marks=9";
check(question8,"A");
sum=sum+1;
}
else if(randomNum==9){
String question9;
question9 = "What does HTTP stands for?\n";
question9+="A. Hypertext Transfer Plotter\n";
question9+="B. Hypertext Transfer Plot\n";
question9+="C. Hypertext Transfer Protocol\n";
question9+="D. Head Tail Transfer Protocol\n";
question9+="Marks=9";
check(question9,"C");
sum=sum+1;
}
else if(randomNum==10){
String question10;
question10 = "The term 'Pentium' is realted to\n";
question10+="A. DVD\n";
question10+="B. Hard Disk\n";
question10+="C. Microprocessor\n";
question10+="D. Mouse\n";
question10+="Marks=9";
check(question10,"C");
sum=sum+1;
}
else{
prevNum=randomNum;
}
}while(sum<=9);
JOptionPane.showMessageDialog(null,nCorrect + " correct out of 10" + " questions");
JOptionPane.showMessageDialog(null,"Total Obtained Marks="+(nCorrect*9));
}
public static String ask(String question) {
while(true) {
String answer = JOptionPane.showInputDialog(question);
answer = answer.toUpperCase();
if(!(answer.equals("A") || answer.equals("B") || answer.equals("C") || answer.equals("D"))){
JOptionPane.showMessageDialog(null,"Invalid Answer");
continue;
}
return answer;
}
}
static void check(String question, String correctAnswer) {
nQuestions++;
String answer = ask(question);
if(answer.equals(correctAnswer)) {
nCorrect++;
}
else {
}
}
}
Thank you!
Your main is quite cluttered. By the time you get to the bottom, you have already forgotten what was on top, such as that it is a very large do-while block. If I were you, I would put the questions and answers in an array, list or even better in your own question object. Then you could use array shuffle to put them in different order for each run and omit all the if-else blocks. It is best to also pull your initialization from random out of the loop so that you don't create a new object with every iteration.
In order to answer your question, so that you do not use an already generated random number again, you must somehow remember the already generated ones. For example, use a list.
public static void main(String[] args) {
Random rand = new Random();
List<Integer> list = new ArrayList<>();
int count = 0;
int randomNum;
do{
randomNum = rand.nextInt(10)+1;
while(list.contains(randomNum)){
randomNum = rand.nextInt(10)+1;
}
list.add(randomNum);
count++;
// rest of your code goes here
}while( count < 10);
System.out.println(list);
}

How do I call a method recursively?

I'm trying to recursively call a method until I obtain the desired output. However, I want to call a method from another class and get information from that method in order to use it in my recursive method. For example, suppose I have a parent class called Cake that contains information about a cake such as its batter(i.e. amount the batter), an extended class with a specific type of cake containing a unique instance of the batter, and I have another class called Bakery where I want to actually make cakes that are being ordered. I have a method in Bakery called createCake, and I want to recursively call this method until enough batter is in the pan to create a cake. If the amount of batter is randomly generated in the extended class, how do I call the getBatter method from that class and capture the information about the batter amount in order to use it in my recursive method for creating the cakes? Can anyone help me out with this? I'm doing something similar to this, but I don't quite understand how I would go about actually getting the information in order to get the recursion to work. I have an example of the code below, so that you can have an idea of what I'm trying to do (I know it's not very accurate). Any help would be greatly appreciated.
import java.util.Random;
public abstract class Cake
{
static Random gen = new Random(System.currentTimeMillis());
public int type; //type of cake
public static int batter = gen.nextInt() * 3; //random amount of batter
public int getType()
{
return type;
}
public int getBatter()
{
return batter;
}
}
public class RedVelvet extends Cake
{
public int type;
public int batter = gen.nextInt(3)+6; //generates between 6-8 cups of batter inclusive
public int getType()
{
return 1;
}
public int getBatter()
{
return batter;
}
}
public class Chocolate extends Cake
{
public int type;
public int batter = gen.nextInt(3)+6; //generates between 6-8 cups of batter inclusive
public int getType()
{
return 2;
}
public int getBatter()
{
return batter;
}
}
public class Pound extends Cake
{
public int type;
public int batter = gen.nextInt(3)+6;
public int getType()
{
return 3;
}
public int getBatter()
{
return batter;
}
}
public class Bakery
{
import java.util.Scanner;
System.out.print("Enter desired size of cake to be baked (Must be at least 12):");
desiredSize=scan.nextInt();
public static void createCake(int desiredSize, int currentSize) //currentSize is the current amount of batter in the pan
{
if (currentSize == desiredSize)
return;
else if (currentSize < desiredSize)
{
//Recursively call createCake method so that batter continues to be added to the pan until there is enough to make the desired cake size. I want to get the batter information from one of the extended classes in order to add it to the cake.
}
}
Is this for school or a course of sorts because I personally wouldn't go this route but then again that's my opinion. It's like, what the heck do I know about baking and I can safely tell you....absolutely nothing. Some may even say that about my programming/coding skills but then again, I'm not a programmer and I am self taught in almost all programming environments including good old Assembly most of which I have now forgotten. :/
I should think that when it comes to baking cakes (or most things for that matter) some sort of accuracy must be established so as to avoid waste and we all know that waste costs money. I'm not overly convinced that generating random amounts of cake batter is accurate enough for what you're most likely are trying to accomplish but then again, you already know this. I noticed that in your different cake classes they all basically generate a random number from 6 to 8. If they all do the same thing then why have them?
I don't believe you need recursion at all but instead a simple method called from within a loop, for example:
while (currentSize < desiredSize) {
currentSize+= getBatter(cake, desiredSize);
}
Here is how I would do this and I apologize now if you find this is all totally meaningless:
import java.util.Random;
import java.util.Scanner;
public class Bakery {
public static void main(String[] args) {
getBaking(); // :)
}
private static void getBaking(){
Scanner scan = new Scanner(System.in);
String cakeType = "";
while (cakeType.equals("")) {
System.out.print("Enter desired cake to be baked (Pound, Chocolate, "
+ "RedVelvet) or\nenter 'exit' to quit: -> ");
cakeType = scan.nextLine();
if (cakeType.isEmpty()) {
System.out.println("\nYou must supply the name of cake to bake or "
+ "enter 'exit' to quit!\n");
}
else if (cakeType.toLowerCase().equals("exit")) { System.exit(0); }
else if (!cakeType.toLowerCase().matches("(pound|chocolate|redvelvet)")) {
System.out.println("\nYou must supply the name of cake as shown above!\n");
cakeType = "";
}
}
int desiredSize = 0;
String size = "";
while (size.equals("")) {
System.out.print("\nEnter desired size of cake to be baked (must be at "
+ "least 12\"): -> ");
size = scan.nextLine();
if (size.isEmpty()) {
System.out.println("\nYou must supply the size of cake to bake or "
+ "enter 'exit' to quit!\n");
}
else if (size.toLowerCase().equals("exit")) { System.exit(0); }
else if (Integer.valueOf(size.replace("\"","")) < 12 ) {
System.out.println("\nYou must supply a cake size of 12\" or greater!\n");
size = "";
}
}
desiredSize = Integer.valueOf(size.replace("\"",""));
createCake(cakeType, desiredSize, 0);
}
public static void createCake(String cake, int desiredSize, int currentSize) {
//currentSize is the current amount of batter in the pan
while (currentSize < desiredSize) {
currentSize+= getBatter(cake, desiredSize);
System.out.println(currentSize);
}
System.exit(0); // Done! - Quit!
}
public static int getBatter(String cake, int desiredSize) {
Random gen = new Random(System.currentTimeMillis());
// Since the random generation for the batter amount is the
// same for all cake types according to your code we just
// need this:
int batterAmount = gen.nextInt(3)+6;
// But if we want to be more specific for each Cake Type
// then we can do it this way but first create the required
// batter equations for each cake type and remove the /* and
// */ from the code but first comment out (//) the batterAmount
// variable declaration above.
// NOTE: Both cake diameter AND 'Height' should play into the factor
// of how much batter is required unless of course all cakes made are
// of the same height.
/*
int batterAmount = 0;
switch (cake.toLowerCase()) {
case "pound":
batterAmount = //batter amount to make 12 inch cake + (this much batter for a 1 inch cake * (desiredSize - 12));
break;
case "chocolate":
batterAmount = //batter amount to make 12 inch cake + (this much batter for a 1 inch cake * (desiredSize - 12));
break;
case "redvelvet":
batterAmount = //batter amount to make 12 inch cake + (this much batter for a 1 inch cake * (desiredSize - 12));
break;
} */
return batterAmount;
}
}
Well, I do hope this has helped you somewhat or at least thrown a little thought into the oven :P

Java - Setters and Inheritance - Why is my dailyFee parameter not setting properly? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
Good evening all!
The assignments are getting confusing! Again, not asking for a straight up answer but rather a pointer in the right direction so any help is appreciated.
Edit 2: Here is the exercise in question if it helps clear anything up:
I'm wondering how I can set the dailyFee variable in the CarRental.java file using the UseCarRental.java file. The if statements from CarRental.java don't seem to be working properly (inputting size doesn't set the dailyFee variable). Additionally, if I enter "l" for the size, it's not prompting to LuxuryCarRental.java. Here is the code:
CarRental.java
import javax.swing.JOptionPane;
public class CarRental
{
private String name;
private String zipCode;
private String size;
private double dailyFee;
private int rentalDays;
private double totalFee;
public CarRental(String name, String zipCode, String size, double dailyFee, int rentalDays, double totalFee)
{
this.name = name;
this.zipCode = zipCode;
this.size = size;
if (size == "e")
{
this.dailyFee = 29.99;
}
else if (size == "m")
{
this.dailyFee = 38.99;
}
else if (size == "f")
{
this.dailyFee = 43.50;
}
this.dailyFee = dailyFee;
this.rentalDays = rentalDays;
totalFee = dailyFee * rentalDays;
}
public CarRental(){}
public void display()
{
JOptionPane.showMessageDialog(null, "Luxury car for " + name + " from zip code " + zipCode + "\n"
+ "Type = " + size + "\n"
+ "Daily Fee = " + dailyFee + "\n"
+ "Days = " + rentalDays + "\n"
+ "Your rental is $" + totalFee);
}
//includes getters and setters but I didn't include them in this post
LuxuryCarRental.java
import javax.swing.JOptionPane;
public class LuxuryCarRental extends CarRental
{
public LuxuryCarRental(String name, String zipCode, String size, double dailyFee, int rentalDays, double totalFee, String includeChauffeur)
{
super(name, zipCode, size, dailyFee, rentalDays, totalFee);
if (size == "l")
{
dailyFee = 79.99;
includeChauffeur = JOptionPane.showInputDialog(null, "Include chauffeur? Y/N");
if (includeChauffeur == "Y")
{
totalFee = totalFee + 200;
}
}
}
}
UseCarRental.java (incomplete)
import javax.swing.JOptionPane;
public class UseCarRental
{
public static void main(String[] args)
{
CarRental userInfo = new CarRental();
userInfo.setName(JOptionPane.showInputDialog("Enter name"));
userInfo.setZipCode(JOptionPane.showInputDialog("Enter zip code"));
userInfo.setSize(JOptionPane.showInputDialog("Enter type of car" + "\n" + "e - economy" + "\n" + "m - midsize" + "\n" + "f - full" + "\n" + "l - luxury"));
userInfo.setRentalDays(Integer.parseInt(JOptionPane.showInputDialog("Enter days to rent")));
System.out.println(userInfo.getDailyFee());
userInfo.display();
}
}
As you can see, I'm completely stumped as to how I can use setDailyFee in UseCarRental.java to set the dailyFee variable, which is need to make the totalFee calculation.
Edit: Being asked to explain why this is not a duplicate question. I fixed the string comparison issue (not updated here yet) but the core issue is still setters and inheritance.
Edit 3: Well I guess the question of the century (for clarity's sake) is: how do I set dailyFee value? I thought that it would be set by the if statement in CarRental.java once size is entered?
You have a few problems here:
You're using == to compare strings.
In your CarRental constructor, you're setting this.dailyFee based on the size and then overwriting it with the parameter's value. You should either eliminate the parameter or not have that logic in the constructor.
The dailyFee field is private to CarRental, meaning it's not available for direct access in LuxuryCarRental. LuxuryCarRental should use this.setDailyFee() instead.
It's Bad Code to put interactions such as a dialog box in a constructor. It'll work for this assignment, but don't use it in Real Code. Separate the interface and the data classes.
You seem to be misunderstanding how inheritance works. You create a CarRental object in your main, but the code for handling l only exists in LuxuryCarRental. You would need to either unconditionally create a LuxuryCarRental (which you could still assign to the CarRental variable) or input the rental type and create a CarRental or LuxuryCarRental based on what it is. Note that while you have a default (no-argument) constructor for CarRental, you do not have one for LuxuryCarRental.
My overall recommendation, besides fixing the string comparison: Move all of the questions into your main method, and assign their values to local variables. Use those values in a call to new LuxuryCarRental(name, zipCode, size, rentalDays, includeChauffeur) (note that dailyFee is calculated based on the size, and the totalFee is calculated based on the daily fee, days, and chauffeur). Instead of having totalFee as a variable on your CarRental, make getTotalFee() a method that performs your calculations when called, since the fee will change whenever you change any of the other parameters.
(And learn about enums when you can; the size shouldn't be a string in the first place.)

can i compare using .equal() for two or more things in the same time

I should Define four boolean variables as follows:
Freshman for students in levels 1 or 2.
Sophomore for students in levels between 3 and 5.
Junior for students in levels between 6 and 8.
Senior for students in levels 9 or 10.
the user enters the course code, then I decide which level is the student (user) and then define the 4 boolean variables depending on the level.
But I don't know how to do the equal() for two thing or more.
this is my code:
import java.util.*;
public class point8 {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// declaring
String CourseCode, Level;
boolean Freshman, Sophomore, Junior, Senior;
// input
System.out.println("Course code:");
CourseCode = input.next().toUpperCase();
System.out.println("\nCourse Code: " + CourseCode);
// output
Level = CourseCode.substring(CourseCode.length() - 1);
System.out.println("Student Level: " + Level);
Freshman = Level.equals("1");
System.out.println("Freshman: " + Freshman);
Sophomore = Level.equals("3");
System.out.println("Sophomore: " + Sophomore);
Junior = Level.equals("6");
System.out.println("Junior: " + Junior);
Senior = Level.equals("9");
System.out.println("Senior: " + Senior);
}
}
What shall I do to compare from level 1 or 2 for freshman
and compare from level 3 to 5 for Sophomore ?
It seems to me that you're better of using integers, just parse the String to int.
For example:
int myLevel = Integer.parseInt(Level);
if(myLevel >= 3 && myLevel <= 5)
{
System.out.println("Sophomore: " + Sophomore);
}
You might get an error if the user inserts a letter instead of a number, to avoid this you need to catch the exception and handle it. This however is an entire different story, but you should readup about it: https://docs.oracle.com/javase/tutorial/essential/exceptions/
if(Level.equals("9") || Level.equals("10"))
{
//Senior
}
Update: The OR operator is something you should learn in the first couple weeks. The only thing more basic is to just write out the second if statement.
if(Level.equals("9"))
{
//Senior
}
else if(Level.equals("10"))
{
//Senior
}

Trying to compare rep sales in an array list in Java

Ok so here is my issue. I am trying to compare the annual sales of two or more sales reps in an ArrayList and am getting some strange results that I just can't figure out. I have to compare the two, then tell the user how much the rep with the lower sales needs to sell to take the lead. I have it broken into three classes. But I'm pretty sure this act is dependent on just two of those. The first is:
import java.util.ArrayList;
/**
*
* #author Cameron
*/
public class SalesRep {
private ArrayList<CompensationCalculator> pool;
public SalesRep(){
pool = new ArrayList<>();
}
public void setPool(ArrayList<CompensationCalculator> pool){
this.pool = pool;
}
public ArrayList<CompensationCalculator> getPool(){
return pool;
}
public void addToPool(CompensationCalculator salesRep){
pool.add(salesRep);
}
public String toString(String report){
double diff;
for(int i=0; i<pool.size(); i++){
if (pool.get(i).getSales() < pool.get(i++).getSales()){
diff = pool.get(i++).getSales() - pool.get(i).getSales();
report = pool.get(i).getName() + "needs to sell " +
diff + " to take the lead.";
}
if (pool.get(i).getSales() > pool.get(i++).getSales()){
diff = pool.get(i).getSales() - pool.get(i++).getSales();
report = pool.get(i++).getName() + "needs to sell " +
diff + " to take the lead.";
}
}
return report;
}
}
That class should compare the two reps in the array while this one displays it to the user:
import java.util.Scanner;
public class AnnualSales {
public static void main(String[] args){
CompensationCalculator test = new CompensationCalculator(); //Creates a new instance of the class
SalesRep testName = new SalesRep(); //Creates a new instance of the SalesRep class
String cont = new String(); //A string to represent if there ar emore names to be added
Scanner scan = new Scanner(System.in); //Allows for user input to be read
while (!cont.equalsIgnoreCase("n")){
System.out.println("What is the name of the sales representative? ");
test.setName(scan.next());
System.out.println("Please enter " + test.getName() +
"'s annual sales: ");
test.setSales(scan.nextDouble());
testName.addToPool(test);
System.out.println("Are there any more sales representatives you "
+ "would like to add? ");
cont = scan.next();
}
System.out.print(testName.getPool());
System.out.print(testName.toString());
}
}
Now there are no errors being found, the program compiles and executes without a problem. But as a result I get
`[compensationcalculator.CompensationCalculator#55f96302, compensationcalculator.CompensationCalculator#55f96302]compensationcalculator.SalesRep#3d4eac69'
I am extremely confused and have been working on just this method for three hours so I am sure I need a fresh pair of eyes. Any help or guidance would be amazing.
EDIT:
Ok so your suggestion to use a Comparator was deffinetely helpful. I was also confusing myself with unnecessary code so I reworked it a bit and now it is working except for one aspect. Here is the code that I changed:
public String compare(SalesRep rep1, SalesRep rep2){
NumberFormat fmt = NumberFormat.getCurrencyInstance();
Double diff;
if (rep1.getSales() > rep2.getSales()){
diff = rep1.getSales() - rep2.getSales();
return rep2.getName() + " needs to sell " + fmt.format(diff) +
" to take the lead.";}
else{
diff = rep2.getSales() - rep1.getSales();
return rep1.getName() + " needs to sell " + fmt.format(diff) +
" to take the lead.";}
}
I also renamed my classes to better organize them to account for the new requirements. Now the only problem is that it is giving a difference of the two sales as $0.0 no madder what I input. Am I calling on each objects sales incorrectly? I feel like I have run into this problem before but reviewing my past code isn't highlighting what I am doing wrong.
I don't see you call toString(String) but only toString(), that's why you'd get that "stange" output.
Btw, that report parameter of your toString(String) method seems quite odd, since you're not using it besides assignments. You should use a local variable in that case.
Another potential error:
if (pool.get(i).getSales() > pool.get(i++).getSales()){
diff = pool.get(i).getSales() - pool.get(i++).getSales();
report = pool.get(i++).getName() + "needs to sell " +
diff + " to take the lead.";
}
Here you are incrementing i three times, so you'd refer to 3 different indices in pool.
Suppose i = 0, then you'd get:
//the first i++ returns i (0) and then increments i to 1
if (pool.get(0).getSales() > pool.get(0).getSales()){
//here i is 1, thus the next i++ returns 1 and increments i to 2
diff = pool.get(1).getSales() - pool.get(1).getSales();
//here i is 2, so the next i++ returns 2 and increments i to 3
report = pool.get(2).getName() + "needs to sell " +
diff + " to take the lead.";
}
So in that second case you'd add 3 to i and thus advance the loop by 4, since the i++ in the loop's head also increments i once more. I'd suggest you use i + 1 in your loop body instead of i++.
Besides that, your design is quite odd, since class CompensationCalculator actually seems to define a sales rep.
Another thing: I'd probably sort the list of sales reps in descending order (hint: use a Comparator). Then element 0 would be the sales rep with the highest sales and the last element would be the sales rep with the lowest sales. Difference calculations would then be a piece of cake.
The toString that you are calling is the method inherited from Object. The toString method that you defined takes a String parameter.
System.out.print(testName.toString());
so override the proper method.
or use the returned String from your method.
String out;
out = testName.toString(out); // Strings are immutable
Add #override annotation to your toString method and move report in, lie so:
#Override
public String toString(){
String report;
.....
}

Categories

Resources