Java code issue [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm having an issue with my code. It won't compile and every time I try to fix it I get an error. I can't see what the problem with it is. I may be just overlooking or looking too hard. I haven't done Java coding since 2006 until I took this class. The class doesn't go a lot into the coding and I'm trying to work off of my memory. I have been working on this code and looking at this code since I wrote it over a week ago. Can someone look and tell me what I screwed up. It's already past-due. I already showed the teacher but haven't got any help and my school doesn't currently have a tutor for this class during this semester. Please help! Code and errors are below:
Errors:
/*
* File: Guitar2.java
* Author: Eppards,Michael
* Date: June 11, 2018
*/
class Guitar2 {
private int numStrings;
private double guitarLength;
private Color guitarColor;
private Manufacturer guitarManufacturer;
enum Manufacturer {
GIBSON,
FENDER,
IBANEZ;
}
enum Color {
RED,
BLUE,
BLACK;
}
// Default Constructor
private Guitar2() {
this.numStrings = 6;
this.guitarLength = 28.2;
this.guitarColor = Color.RED;
this.guitarManufacturer = Manufacturer.GIBSON;
}
// Argument Constructor
private Guitar2(int numStrings, double guitarLength, Color guitarColor, Manufacturer guitarMaker) {
this.numStrings = numStrings;
this.guitarLength = guitarLength;
this.guitarColor = guitarColor;
this.guitarManufacturer = guitarMaker;
}
// Getters
public int getNumStrings() {
return numStrings;
}
public double getGuitarLength() {
return guitarLength;
}
public Color getGuitarColor() {
return guitarColor;
}
public Manufacturer getGuitarManufacturer() {
return guitarManufacturer;
}
// playGuitar method for 16 randomly selected musical notes
enum Notes {
A(1),
B(4),
C(1),
D(2),
E(0.25),
F(0.5),
G(0.5);
double duration;
private Notes(double duration) {
this.duration = duration;
}
}
public String playGuitar() {
String play = "[";
int a;
int b;
// initiate a random number
Random rn = new Random();
// for loop to select random notes
for (int k = 0; k < 16; k++) {
a = rn.nextInt(7);
b = rn.nextInt(5);
play = play + Notes.values()[a] + "(" + Notes.values()[a].duration + ")";
if (k != 15) play = play + ",";
}
play = play + ']';
return play;
}
// used to return the info in a string
public String toString() {
String infoString = "(numStrings=" + this.numStrings + ", guitarLength=" + this.guitarLength + ",guitarManufacturer=" + this.guitarManufacturer + ",guitarColor=" + (this.guitarColor == null ? "none" : this.guitarColor.name()) + ")";
return infoString;
}
}
Guitar2.java:80: error: cannot find symbol
Random rn = new Random();
^
symbol: class Random
location: class Guitar2
Guitar2.java:80: error: cannot find symbol
Random rn = new Random();
^
symbol: class Random
location: class Guitar2
2 errors

-Hello, World!-
There were quite a few issues with the code that caused it to not compile. I fixed all of them (I think) and have written out what was wrong:
Public needs to be changed to public
The second Guitar constructor is missing all it's parameters.
Enums need to be referenced by their name, you can't just type in their values.
Your curly braces were all over the place. There were way more closing than opening, so I deleted a bunch of them at the end and ones that were tossed into the middle of the class.
Methods must be within classes.
Enums can't be declared inside methods, only inside classes.
Variable declarations must have a space between the type and the name of the variable. Example: int_a; needs to be int a;
Your Duration enum has no constructor that accepts and int.
Getting a random value of an enum based on its index is done by doing Notes.values()[a];, not Notes[a];
No idea where the return Optional.empty(); line should be, so I deleted it.
You're missing the import for the Random class.
Strings can't be on multiple lines.
.orElse() is not a method. Deleted this, unsure what it was supposed to do.
colorName() is not a method. I changed it to: (this.guitarColor == null ? "none" : this.guitarColor.name()).
The name of the variable in the toString() method is not the same as what you try to return. I changed them both to infoString.
You have a TON of typos, namely with things like Manufacturer being Manufacur and return being rturn.
When initializing a variable, you must have a space after new.
Your getter methods do not return the correct type.
The name of the variable numString is repeatedly referred to as numStrings. I added the s to the original variable declaration.
Below are a list of things you really SHOULD change, but you don't need to change.
All enum names should be in ALL CAPS.
Method names should be written using camelCase. Example: myVal would have a getter named getMyVal().
Have blank lines between methods, constructors, and types.
Have a space after the start of a comment. Example: // Comment Bad Example: //Comment
Have some sort of sorting pattern for enums. For notes, it should be alphabetical.
There is no need to have another enum for the duration of notes. This can easily be done in the note itself.
There is no need to do String.valueOf(someObject) for concatenation. It is better to do someObject.toString() and best to just leave it as someObject because the runtime will do that operation for you.
There should be a space before and after arithmetic operators like + and -.
I would highly recommend you read up on some basic Java tutorials and look at the Google Java Style Guide. It is what I use and what I'm sure a lot of people use to determine how code should look.
With all the changes and with the proper use of style, your code looks like this:
import java.util.Random;
/*
* File: Guitar.java
* Author: Eppards,Michael
* Date: June 11, 2018
*/
class Guitar {
private int numStrings;
private double guitarLength;
private Color guitarColor;
private Manufacturer guitarManufacturer;
enum Manufacturer {
GIBSON,
FENDER,
IBANEZ;
}
enum Color {
RED,
BLUE,
BLACK;
}
enum Notes {
A(1),
B(4),
C(1),
D(2),
E(0.25),
F(0.5),
G(0.5);
double duration;
private Notes(double duration) {
this.duration = duration;
}
}
// Default Constructor
private Guitar() {
this.numStrings = 6;
this.guitarLength = 28.2;
this.guitarColor = Color.RED;
this.guitarManufacturer = Manufacturer.GIBSON;
}
// Argument Constructor
private Guitar(int numStrings, double guitarLength, Color guitarColor, Manufacturer guitarMaker) {
this.numStrings = numStrings;
this.guitarLength = guitarLength;
this.guitarColor = guitarColor;
this.guitarManufacturer = guitarMaker;
}
// Getters
public int getNumStrings() {
return numStrings;
}
public double getGuitarLength() {
return guitarLength;
}
public Color getGuitarColor() {
return guitarColor;
}
public Manufacturer getGuitarManufacturer() {
return guitarManufacturer;
}
// playGuitar method for 16 randomly selected musical notes
public String playGuitar() {
String play = "[";
int a;
int b;
// initiate a random number
Random rn = new Random();
// for loop to select random notes
for (int k = 0; k < 16; k++) {
a = rn.nextInt(7);
b = rn.nextInt(5);
play = play + Notes.values()[a] + "(" + Notes.values()[a].duration + ")";
if (k != 15) play = play + ",";
}
play = play + ']';
return play;
}
// used to return the info in a string
public String toString() {
String infoString = "(numStrings=" + this.numStrings + ", guitarLength=" + this.guitarLength + ",guitarManufacturer=" + this.guitarManufacturer + ",guitarColor=" + (this.guitarColor == null ? "none" : this.guitarColor.name()) + ")";
return infoString;
}
}
Hope this helps! Friendly reminder that I made a LOT of changes to this code. You really should go look at the steps I took and make the changes yourself, otherwise you could get in trouble with your school for submitting work that is not your own.

Related

How to update a variable first and then execute the rest of the code in java

I'm learning app development for Android and have a small problem with my code. In the google tutorial i am working with we created a coffe ordering app. I did some extra coding for my plus and minus buttons, because i wanted them to update the price while changing the amount of cups ordered. That worked great, the moment i press the button the amount of cups and the total price get updated at the same time.
Now here comes my problem. I wanted to output a string with "Total: " + totalPrice, but that doesn't work and i found out why.
public void addCups(View view) {
numberOfCups = numberOfCups + 1;
display(numberOfCups);
displayMessage(gBetrag + endPreis);
}
Here are my global variables:
int numberOfCups = 0;
int priceOfCup = 5;
String message = "Vielen Dank!";
String gBetrag = "Gesamt: ";
String endPreis = NumberFormat.getCurrencyInstance().format(numberOfCups * priceOfCup);
I ran the code in debugging mode and found out that the method first looks for whats in "gBetrag" and "endPreis" before it updates the "numberOfCups" variable.
The output is "Gesamt: 0.00€" because endPreis is calculated before numberOfCups gets a +1. How do get java to execute the code in the order it was written or rather read the variable after it was updated?
I can workaround this issue if add the variable to every method i want to use it in, but that just adds more code and i tought that's why you use global variables.
You need to calculate the endPreis each time a cup is added:
public void addCups(View view) {
numberOfCups = numberOfCups + 1;
calculateTotal();
display(numberOfCups);
displayMessage(gBetrag + endPreis);
}
private void calculateTotal() {
endPreis = NumberFormat.getCurrencyInstance().format(numberOfCups * priceOfCup);
}
I suppose your class is written this way :
public class MyClass {
int numberOfCups = 0;
int priceOfCup = 5;
String message = "Vielen Dank!";
String gBetrag = "Gesamt: ";
String endPreis = NumberFormat.getCurrencyInstance().format(numberOfCups * priceOfCup);
public void addCups(View view) {
numberOfCups = numberOfCups + 1;
display(numberOfCups);
displayMessage(gBetrag + endPreis);
}
}
So here is how your code will be executed :
numberOfCups is set to 0
priceOfCup is set to 5
message is set
gBetrag is set
endPreis is set to (numberOfCups * priceOfCup)
When you call addCups(), it will display endPreis value.
As you could see, endPreis value was never re-calculated ;)

Java enum ordinal returning -1?

Alright so I'm currently writing some code for a project I'm working on, and I decided an Enum for data storage will be my best bet. But in the first time in my life, the enum.ordinal() returns -1?
Heres the code:
DuelRules.Rules rule = DuelRules.Rules.values()[(buttonId - (buttonId < 29 ? 18 : 19))];
if (buttonId == 29) {
rule = DuelRules.Rules.POCKET;
}
System.out.println(rule + ", " + rule.ordinal());
rules.swapRule(player, other, rule);
reset(false);
This statement here:
System.out.println(rule + ", " + rule.ordinal());
It prints the correct rule value, but when it prints rule.ordinal() it is printing -1?
Example:
HAT, -1
My Enum:
public enum Rules {
HAT(5000, 1),
CAPE(5000, 2),
AMULET(5000, 4),
WEAPON(5000, 8),
BODY(5000, 16),
SHIELD(5000, 32),
LEG(5000, 128),
GLOVE(5000, 512),
BOOT(5000, 1024),
RING(5000, 4096),
ARROW(5000, 8192),
POCKET(17837, 1),
FORFEIT(4989),
MOVEMENT(4990),
RANGE(4991),
MELEE(4992),
MAGIC(4993),
DRINKS(4994),
FOOD(4995),
PRAYER(4996),
OBSTACLES(4997),
FUN_WEAPONS(4998),
NO_ABILITIES(4999),
SUMMONING(5001);
private final int varbitId;
private final int value;
private Rules(int id, int... value) {
this.varbitId = id;
this.value = value.length > 0 ? value[0] : 0;
}
}
Note, that enum is inside of another class, not sure if that can effect the outcome. Thanks for your help, I'm completely lost with this one.
EDIT: Upon farther review I found that the ordinal is being changed by passing it as an argument?
Screnshot of console:
Code:
} else if (buttonId >= 18 && buttonId <= 42) {
DuelRules.Rules rule = DuelRules.Rules.values()[(buttonId - (buttonId < 29 ? 18 : 19))];
System.out.println("Point one: "+rule + ", " + rule.ordinal());
rules.swapRule(player, other, rule);
getDuel(other).rules.setRules(player, other, rules
.rules);
reset(false);
sendFlash(interfaceId, buttonId);
}
Where it prints Point one, the Rule and its .ordinal is correct, in this case OBSTACLES, 20
But where it passes the rule paramters in rules.swapRule, it changes the ordinal to -1?
public boolean swapRule(Player player, Player other, Rules rule) {
System.out.println("Point 2(swapRule): " + rule + ", " + rule.ordinal());
}
What is causing the Rule parameters to be changes when getting passed as an argument?
Your approah defeats the sheer purpose of using an enumerator. Instead of mangling with indices you could use the Enum directly like this
button.setActionCommand (Rules.HAT.toString ());
Then in your ActoinListener you can determine which button was clicked by using this
public void actionPerformed (ActionEvent e) {
if (Rule.valueOf (e.getActionCommand()) == Rules.HAT) {
//HAT related button was called, process it
}
}
You can get this result by reflection:
import java.lang.reflect.Field;
public class Main {
enum Fruit { APPLE }
public static void main(String[] args) {
try {
Field field = Fruit.class.getSuperclass().getDeclaredField("ordinal");
field.setAccessible(true);
field.set(Fruit.APPLE, -1);
} catch (Exception e) {
}
System.out.println(Fruit.APPLE + ", " + Fruit.APPLE.ordinal());
}
}
However I doubt anyone could do this by mistake.

Multidata Type Array In Java

Complete newbie here guys. I'm working on a Java program to prompt the user for 3 variables which are used to calculate a future investment's value. Everything works perfectly, except when it comes time to put both my datatypes into ONE array.
Here's what the output SHOULD look like:
Year Future Value
1 $1093.80
2 $1196.41
3 $1308.65
...
This is what mine looks like:
Year 1
Future Value 1093.81
Year 2
Future Value 1196.41
Year 3
Future Value 1308.65
...
My year is an int value and my Future value is a double (rounded). I've been sitting here racking my brain and all the forums I can find and haven't been successful. Every time I put both value into an array I get an error about putting two different datatypes together. Any insight would be greatly appreciated. Below is the code for my full program:
import java.util.Scanner;
class investmentValue {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter investment amount: $");
double i = s.nextDouble();
System.out.print("Enter percentage rate: ");
double r = s.nextDouble()/100;
System.out.print("Enter number of years: ");
int y = s.nextInt();
for (y=1; y<=30; y++) {
double f = futureInvestmentValue(i,r,y);
System.out.println("Year " + y);
System.out.println("Future Value " + f);
}
}
public static double futureInvestmentValue (double investmentAmount, double monthlyInterestRate, int years){
double value=1;
value = investmentAmount*Math.pow((1+(monthlyInterestRate/12)),(years * 12));
double roundValue = Math.round(value*100.0)/100.0;
return roundValue;
}
}
One solution is to start by implementing a pad function. Something like,
public static String pad(String in, int len) {
StringBuilder sb = new StringBuilder(len);
sb.append(in);
for (int i = in.length(); i < len; i++) {
sb.append(' ');
}
return sb.toString();
}
Now we can combine that with String.format() to get the dollars and cents, use a consistent printf() for the header and output lines. To get something like,
// Print the header.
System.out.printf("%s %s%n", pad("Year", 12), "Future Value");
for (int y = 1; y <= 30; y++) {
String year = pad(String.valueOf(y), 13); // <-- One more in your alignment.
String fv = String.format("$%.2f", futureInvestmentValue(i,r,y));
System.out.printf("%s %s%n", year, fv);
}
The System.out.println command isn't the only method available to you!
Try this in your loop:
System.out.print(y); // note that we use print() instead of println()
System.out.print('\t'); // tab character to format things nicely
System.out.println(f); // ok - now ready for println() so we move to the next line
Naturally, you'll want to do something similar to put your headings in.
PS - I'm pretty sure this is just an output formatting question - you don't really want to put all these values into a single array, right?
Given that you really are looking for formatted output, it may be better to use the printf() method.
The following inside the loop (instead of the 3 lines I wrote above) should do the trick (untested - I haven't used printf() format strings in a long, long time).
System.out.printf("%i\t$%0.2f", y, f);
EDIT: edited to answer your question in the comments about constructors... You should also check out this for further understanding
You could create a class that will hold both of the arrays...
This would give you a single object, let's call it StockData, that holds two arrays for the two separate types you need. You need to create the object once and then insert the data separately by type.
class StockData {
double[] data1;
int[] data2;
// default constructor
StockData() {
}
// constructor
StockData(double[] data1, int[] data2) {
this.data1 = data1;
this.data2 = data2;
}
// getters, setters...
}
Then you add data to an array of its type:
// using default constructor to add a single value to both arrays
StockData sd = new StockData();
sd.data1[INDEX_X] = YOUR_DOUBLE;
sd.data2[INDEX_X] = YOUR_INT;
// using default constructor to add all data to both arrays
StockData sd = new StockData();
sd.data1 = YOUR_ARRAY_OF_DOUBLE;
sd.data2 = YOUR_ARRAY_OF_INTS;
// using constructor to add all array data directly
StockData sd = new StockData(YOUR_ARRAY_OF_DOUBLE, YOUR_ARRAY_OF_INTS);
You could also have an object that will hold the double and int value, so the object will represent a single stock information of 2 values and then create an array containing those objects...
class StockData {
double data1;
int data2;
// default constructor same as before
// constructor
StockData(double data1, int data2) {
this.data1 = data1;
this.data2 = data2;
}
// getters, setters...
}
// ...
Adding data:
// create an array of StockData objects
StockData[] sd = new StockData[TOTAL_AMOUNT_OF_DATA];
// ... obtain your data
// using default constructor to add a single value to the array
sd[INDEX_X] = new StockData();
sd[INDEX_X].data1 = YOUR_DOUBLE;
sd[INDEX_X].data2 = YOUR_INT;
// using constructor to add all data directly
sd[INDEX_X] = new StockData(YOUR_DOUBLE, YOUR_INT);
If you want the program to have an specific format you could try to change your code and put this where your for is:
System.out.println("Year Future Value");
for (y=1; y<=30; y++) {
double f = futureInvestmentValue(i,r,y);
System.out.print(y);
System.out.println(" " + f);
}
this way you will have your output in the format you need without using arrays. But if you want to do an array for this you could declare an array of objects and create a new object with two attributes (year and future value)
Also your class name is investmentValue and it is recommended that all classes start with upper case it should be InvestmentValue
I hope that this can help you
A fun data structure you would be able to use here is a Map (more specifically in Java, a HashMap). What you are doing is associating one value with another, an integer to a double, so you could make something that looks like this:
Map<Integer, Double> myMap = new HashMap<>();
This would take the year as the integer, and the double as the price value, and you could iterate over the map to print each value.
Additionally if you really are looking for a "multidata type array," Java automatically casts from integer to double should you need to. For example:
int i = 2;
double[] arr = new double[2];
arr[0] = 3.14
arr[1] = i;
The above code is perfectly valid.

Error resolving variables and left-side side assignments and figuring ++ tokens

I'm starting to get blind looking at my code and my brain is about to overheat. I'm new when it comes to programming.
public class RecyclingSystem {
public static void main(String[] args) {
System.out.println("Please put in a valid bottle");
Scanner sc = new Scanner(System.in);
while ( sc.nextInt() != -1) {
if (sc.nextInt(char a) = getaBottle);
int bottleAcount++;
} else if { (sc.nextInt(char b) = getbBottle);
int bottleBcount++;
} else if { (sc.nextInt(char c) = getcBottle);
int bottleCcount++;
} else { throw new EmptyStackException();
System.out.println("Bottle not recognized");
}
System.out.println("The total number of bottles is " + totalBottlecount);
System.out.println();
System.out.println("The total amount returned is " + sumOfBottles );
}
sc.close();
}
}}
public class Bottle {
private static final double A_BOTTLE = 1.0;
/**
* #return the aBottle
*/
public static double getaBottle() {
return A_BOTTLE;
}
/**
* #return the bBottle
*/
public static double getbBottle() {
return B_BOTTLE;
}
/**
* #return the cBottle
*/
public static double getcBottle() {
return C_BOTTLE;
}
private static final double B_BOTTLE = 1.5;
private static final double C_BOTTLE = 3.0;
}
public class EmptyStackException extends Exception {
}
public class bottleCount {
int bottleAcount = 0;
int bottleBcount = 0;
int bottleCcount = 0;
int totalBottleCount = bottleAcount + bottleBcount + bottleCcount;
}
I have seperate classes for the getbottle, totalBottlecount and bottlecount variables.
I want to make a user-input based recycling system simulator, if that makes any sense, with 3 different types of bottles, which are assigned different values, a total bottle count and the sum of the values of the 3 bottle types combined.
I get several compiler errors and I have spend HOURS trying to resolve them all, but every time I do, new errors occur and now I get a "coders-block".
I get asked to delete the ++ tokens, the compiler cannot resolve my variables and syntax errors. I would really appreciate some insight, since I'm only ~3weeks into java programming.
UPDATED: Compiler errors exact copy pasta
Multiple markers at this line
- Syntax error, insert ")" to complete Expression
- Duplicate method nextInt(char) in type RecyclingSystem
- Syntax error, insert "}" to complete Block
- Syntax error, insert "AssignmentOperator Expression" to complete Assignment
- Return type for the method is missing
- Syntax error on tokens, delete these tokens
- The left-hand side of an assignment must be a variable
- Syntax error, insert "AssignmentOperator Expression" to complete Expression
- The left-hand side of an assignment must be a variable
- Syntax error, insert ";" to complete BlockStatements
- Syntax error on tokens, delete these tokens
- Syntax error on token ")", { expected after this token
- Syntax error, insert ";" to complete Statement
int bottleAcount++;
In java you need to declare the local variable like
type name = intial value;
then do any operation on that like increament or decrement.
In youe case declar the variable before while loop with zero as intial value like
int bottleAcount = 0;
then inside while increament it by 1, like bottleAcount++;
or
bottleAcount += 1;
So... If this is all the code there are many problems and what can I recommend in the beginning - go back to some basic Java programming course.
Let's look at one of the first lines:
if (sc.nextInt(char a) = getaBottle);
Firstly, it's a condition, and you are assigning the value of a getaBottle to the sc.nextInt(char a).
Secondly, nextInt(char a) looks like method declaring, not like a method call.
Thirdly, getaBottle is never declared before
Fourthly, you have a getaBottle() method in a Bottle class, which you probably want to use instead of getaBottle which is (should) be a variable
...etc., etc.
This code is not even valid Java code. It's hard to help you somehow in that problem, you just need to learn a bit more, which I encourage you to do.
Good luck and in case of any specific question - come and ask!
else if { (sc.nextInt(char b) = getbBottle);
int bottleBcount++;
}
Syntax is totally wrong for if.Also condition is checked using == not = It should be :
else if (sc.nextInt(char b) == getbBottle);
int bottleBcount++;
Also you cant do int bottleBcount++. Its meaningless. Since you already declared bottleBcount in another class, you have to access it using the object of that class. Before that change the declaration in the class from int bottleAcount = 0; to public int bottleAcount = 0; . Do this for all bottles.
Now you can use it as :
public static void main(String[] args) {
System.out.println("Please put in a valid bottle");
bottleCount counter = new bottleCount();
Scanner sc = new Scanner(System.in);
while ( sc.nextInt() != -1) {
if (sc.nextInt(char a) == getaBottle);
counter.bottleAcount++;
} else if (sc.nextInt(char b) == getbBottle);
counter.bottleBcount++;
else if (sc.nextInt(char c) == getcBottle);
counter.bottleCcount++;
else { throw new EmptyStackException();
System.out.println("Bottle not recognized");
}
System.out.println("The total number of bottles is " + totalBottlecount);
System.out.println();
System.out.println("The total amount returned is " + sumOfBottles );
}
sc.close();
}
Also the statement int totalBottleCount = bottleAcount + bottleBcount + bottleCcount; doesnt make sense. It won't work as you wanted it to. You need to write a function to do this addition and then call it. Or if you want this to happen just once ( which I doubt) , you can put it in a constructor.
I suggest you brush up on class and variable declaration concepts before proceeding
You just have problem in this:
else {
throw new EmptyStackException();
System.out.println("Bottle not recognized");
}
Check the proper syntax and error will be resolved.

Extended class issues

I have had some issues involving code that accesess variables defined in a superclass that were later revised in a child class. Ie
//start of Stat class. Variables in question are defined here. (Name, Level, Experience, totalXP)
public class Stat {
public static String Name = " ";
public static int Level = 0;
public static double Experience = 0;
public static double totalXP = 0;
//Sets Name
public static void setName(String NameIn) {
Name = NameIn;
}
//Sets Level
public static void setLevel(int LevelIn) {
Level = LevelIn;
}
//Sets Experience
public static void setExperience(double ExperienceIn) {
Experience = ExperienceIn;
}
//Sets totalXP
public static void settotalXP(double totalXPIn) {
totalXP = totalXPIn;
}
//Sets up Attributes
public static void setall() {
setName("Herp");
setLevel(1);
setExperience(0);
settotalXP(0);
}
//Displays a Stat's Attributes
public static void DisplayLevel() {
System.out.println(Name);
System.out.println("Level: " + Level);
System.out.println(Experience + " out of " + totalXP + " total experience.");
}//End of method
public static void Levelup() {
if(Experience >= totalXP) {
Level++;
totalXP = totalXP * 1.3;
Experience = 0;
}//end of if statement
}//end of Levelup method
}//end of Stat.class
public class Agility extends Stat{
{//Revisionary Block
Name = "Agility";
Level = 1;
Experience = 0;
totalXP = 125;
}
public static int runnappDodge(int Dodge) {
Random generator = new Random(10);
Dodge = generator.nextInt(10);
if (Dodge == 0) {
Player.incomingDMG = 0;
}//end of if statement
return Dodge;
}
//start of the method located on player.class. This prints out " ", 0.0 and 0.0 for all //of the fields.
public static void checkLevel() {
System.out.println("You are level: " + Level);
System.out.println("You have " + experience + " experience out of " + totalXP + " total experience");
System.out.println(stat.Attack.Name + " Level: " + stat.Attack.Level + ": Experience: " + stat.Attack.Experience + "/" + stat.Attack.totalXP);
System.out.println(stat.Archery.Name +" Level: " + stat.Archery.Level +": Experience: " + stat.Archery.Experience + "/" + stat.Archery.totalXP);
System.out.println(stat.Agility.Name +" Level: " + stat.Agility.Level + ": Experience: " + stat.Agility.Experience + "/" + stat.Agility.totalXP);
}//end of checkLevel method
my full code is here: http://pastebin.com/6nPGwJQe
reddit was no help so I now turn to you. (not that you arent helpful, but I just use reddit more so it is more convenient). I think that my code should be updating the variables in the subclasses but it doesnt. When I refrence the variable it ends up being excactly what it was when defined by super class, in Aaron.name's case, " " rather than "Aaron". I'm not sure if a getter and setter might be useful here, but I appreciate all advice
PS: My first question on stackoverflow!
Edit: Thanks for the feedback. This was example code. The last commenter helped out a lot, but my real code is entirely independent from this. It was to convey an example. So please see the link because that code is really what matters.
Edit 2: Because I can see that one might need to see the structure of my project for imports and references sake, here is an image of my project structure: http://imgur.com/VhDzRrm
Edit 3: No longer does my post use an example that is incorrect, it uses my actual code.
Java is very clear about case-sensitivity. Since you have extended the Derp class your Aaron class now has two String fields. name and Name. That is why it is displaying nothing, because you have instantiated your name String to "". if you replaced it with Aaron.Name you will have what you are looking for.
I'll go over a few issues in your code.
First obviously, it doesn't compile, as others have pointed out. You should take your actual code and strip out anything that's not germane to the problem. Keep stripping until your sample code is as small as what you posted here, but make sure it still compiles. See http://sscce.org/
Odds are, you'll find the bug as you go, in which case post your own answer to the question (yes, you can do that). If not, edit your question with the actual code.
Now, to address your issues:
There was no need to use an anonymous constructor for Aaron. It should have been
public class Aaron extends Derp {
public Aaron() { Name = "Aaron"; IQ = 10; }
}
(Something tells me you're coming from a C++ background.)
"name" is an instance variable, which means that it only exists as part of an object of type Derp (or Aaron). You first need to create an object, then reference that.
public static void main() {
Aaron aaron = new Aaron();
System.out.println("Hi, my name is: " + aaron.name + "!\n");
}
You could also have made name a class variable:
static String name = " ";
but there's no good way to override that variable in a subclass, so we won't go there.
One final nit: you didn't need that "\n" in the println() call, since that function appends a newline for you.

Categories