Need assistance printing out a number from another method - java

I am working on a small RPG project and I can't print a number from another method.
Here's the main:
///////// SMTMain /////////
//Note: this is a parody game and not to be meant for actual retail purposes.
// SMTMain.java
import java.util.Scanner;
public class SMTMain
{
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
SMTBattle battle = new SMTBattle();//runs the battle method, works fine.
SMTStats stats = new SMTStats();
//battle.battle(); commented out battle until i can get stats working
System.out.print(stats.pcstats(str));
//error, cannot find symbol ^
} // end main
} // end class SMTMain
And the file containing all the stats:
///////// SMTStats /////////
// SMTStats.java
import java.util.Scanner;
public class SMTStats
{
Scanner input = new Scanner( System.in );
////////Main Stats///////////////
private int lvl; //level
private double str; //strength
private double agi; //agility
private double itl; //intellect
private double wis; //wisdom
private double lk; //luck
//////Main Stats end/////////////
///////stats that are influenced by main stats or gear/////////
private double hp; // health
private double mp; //mana
private double arm; //armor
private double atk; //attack
private double crit; //critical
private double hit; //chance to hit
private double def; //defense
private double dge; //dodge
////////stats etc. ends//////////////////////////////////
double pcstats; //player character function
public double pcstats() //player character stats
{
//int lvl = 1; //worried about just str currently
double str = 10.0;
/*agi = 10;
itl = 10;
wis = 10;
lk = 10;
hp = 30;
mp = 30;
arm = 30;
atk = 1.2 * str;
crit = (1.5 * lk) / 2;
hit = 1.5 * (agi * 2);
def = arm / str;
dge = (agi * 1);*/
return pcstats;
}
} // end class SMTStats
I tried googling my error but I couldn't find an answer to my question and I'm still fairly new to java programming, I was hoping y'all would lead me into the right direction.

What Java tries to do:
Java tries to find some Variable called str. But SMTMain has no variable called str. The class SMTMain can't "see" what you have declared in another class (SMTStats).
What you are probably trying to do:
The variable stats is an object (so called instance of the class) of the class SMTStats.
You need one more method (function of an Object) in the class SMTStats.
Usually, you make so called getter and setter methods.
Code:
The getter for str in SMTStats:
public int getStr() {
return str;
}
The method getStr() returns the variable str to SMTMain.
The setter for str in SMTStats:
public void setStr(double newStr) {
str = newStr;
}
The method setStr sets the variable from SMTMain.
In the class SMTMain you can now print the variable str from SMTStats:
System.out.print(stats.getStr());
The name of the getter method implies what variable you want to get/return.
A nice java tutorial by the way (Chapter 25 is Object Oriented Programming):
http://chortle.ccsu.edu/java5/index.html

Related

accessing objects in an array Java

I am having trouble understanding how to set and get objects in an array. Please keep it basic/simple; I am a beginner.
I cannot use a list as I am not there yet in my java class. We are supposed to use regular arrays.
I am building a program that creates solar system objects and puts planet objects in the solar system object array. I have to be able to insert the planet by index as well as get it by index.
Getting regular object info was simple but once arrays were added. It got tough. I understand better when I can comprehend how and why something works. Here is my code. Many thanks in advance!
Planet Class
public class Planet {
// private fields
private String planetName;
private int numMoons;
// param constructor
public Planet(String n, int m){
planetName = n;
numMoons = m;
}
public String toString(){
return planetName + " " + numMoons;
}
public void setPlanetName(String n){
this.planetName = n;
}
public String getPlanetName(){
return planetName;
}
public void setNumMoons(int m){
this.numMoons = m;
}
public int getNumMoons(){
return numMoons;
}
}
Here is the SolarSystem class
package project03;
public class SolarSystem {
private String solarSystemName;
private Planet[] allPlanets = new Planet[8];
private int numPlanets;
public SolarSystem(String ss, int np){
solarSystemName = ss;
numPlanets = np;
}
public void setSolarSystemName(String ss){
solarSystemName = ss;
}
public String getSolarSystemName(){
return solarSystemName;
}
/*public void setAllPlanets(String ss){
solarSystemName = ss;
}
public String getSolarSystemName(){
return solarSystemName;
}
*/
}
Finally here is my driver class that houses the main method
package project03;
public class Driver {
public static void main(String[] args) {
// creates planet object
Planet Mercury = new Planet("Mercury", 0);
Planet Venus = new Planet("Venus", 0);
Planet Earth = new Planet("Earth", 1);
Planet Mars = new Planet("Mars", 2);
Planet Jupiter = new Planet("Jupiter", 67);
Planet Saturn = new Planet("Saturn", 62);
Planet Uranus = new Planet("Uranus", 27);
Planet Neptune = new Planet("Neptune", 14);
SolarSystem ourSolarSystem = new SolarSystem("Sol-System", 8);
System.out.println("Planet name is : " + ourSolarSystem.getSolarSystemName());
//System.out.println("Moon number is :" + Mercury.getNumMoons());
}
}
You are missing a couple of methods from your SolarSystem class
public void setPlanet (Planet planet, int pos) {
allPlanets [pos] = planet; // pos is zero based
}
public Planet getPlanet (int pos) {
return allPlanets [pos]; // pos is zero based
}
Then you can use it as
ourSolarSystem.setPlanet (Mercury, 0);
You have to add methods in your solar system class to add objects to the internal array.
to populate an array , you need 2 things
1. Size
2. Elements.
Your solar system class has provisions for none at this point. Size is hardcoded to 8, which is fine for this example, ideally it should be passed in constructor while creating a solar system.
Ignoring that for a moment, you should add method in the class to add a planet.
Since this is for your learning, I am not adding exact code, just algorithm
public void addPlanet(Planet p, int pos){
//check pos is less than array size
// add planet to the index pos if pos is less than size.
}
You could also create an array outside and add it to the solar planet
public void addPlanets(Planet[] planetArray){
// replace current planet array with the array passed in input
}
The array outside can be created easily
Planet[] planetArray = new Planet[8];
planetArray[0] = Mercury ;
// and so on.

Java create a unique ID for each instantiated object using instance methods instead of class/static methods

Quite new to this so I hope I have the terminology in the title right.
I am trying to figure out how to create an instance method that will do the following:
--An ID number is returned.
--As each object is created from the class constructor(instantiated?), a unique integer ID number is assigned to it. The first ID number is 1, and as new objects are instantiated, successive numbers will be assigned.
I am able to find examples of class/static methods that do the above however I am unable to figure out how to do this with an instance method. My attempt is below:
class Coordinates
{
private int iD = 0;
private float xCoordinate;
private float yCoordinate;
public Coordinates()
{
//Asks for input and assigns it to the two variables below
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the X Coordinate followed by the return key");
xCoordinate = keyboard.nextDouble();
System.out.println("Please enter the Y Coordinate followed by the return key");
yCoordinate = keyboard.nextDouble();
iD++;
}
public getiD()
{
return iD;
}
}
My main method is as follows:
public class Machine
{
public static void main(String[] args)
{
Coordinates c1 = new Coordiantes();
Coordinates c2 = new Coordiantes();
Coordinates c3 = new Coordiantes();
System.out.println("ID: " + c1.getID());
System.out.println("ID: " + c2.getID());
System.out.println("ID: " + c3.getID());
}
}
Please note I have not included my entire code for the sake of simplicity and easiness to follow. I hope I have added enough.
I also don't want to use java.util.UUID.
The problem right now is that your 'id' is an instance variable, meaning it belong to the objects you create.
Think of it that every time you create an object a new and fresh copy of your instance variable is made.
So every time you create an object the id is first set to 0, then post incremented once (thus all objects have an id=0).
If you want to create a variable that, say, automatically counts all objects you have created in a class or has the id, you need to make a class variable.
These variable belong to all the objects you create from a class and the keyword used for that is 'static'.
Note: I have used a static variable BUT not a static method. If you don't want to use static at all, it is a different question
class Coordinates
{
private static int count = 0;
private int id=0;
private float xCoordinate;
private float yCoordinate;
public Coordinates()
{
//Asks for input and assigns it to the two variables below
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the X Coordinate followed by the return key");
xCoordinate = keyboard.nextDouble();
System.out.println("Please enter the Y Coordinate followed by the return key");
yCoordinate = keyboard.nextDouble();
id=count++;
}
public getiD()
{
return iD;
}
}
A simple change of keyword will make your program correct. You dont have to do too much complicated stuff.
It is difficult to grasp the concept of class and objects, static and instance variables at first. Let me know if you'd like more explanation :)
In the context of your current code, the simplest thing to to do is as below:
import java.util.concurrent.atomic.AtomicInteger;
public class Coordinates {
//static id generator shared among all instances of Coordinates
private static final AtomicInteger idGenerator = new AtomicInteger(1000);
private final Integer id;
public Coordinates() {
//assign unique id to an instance variable
id = idGenerator.getAndIncrement();
}
public int getId() {
//return instance variable
return id;
}
}
Test
public class Test {
public static void main(String[] args) {
for(int i = 0; i < 10; ++ i){
System.out.println(new CoordinatePoint().getId());
}
}
}
Output
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
Maintaining an ID sequence is a separate responsibility from the rest of what your object does, and doesn't belong to any one instance of the Coordinates class, so it belongs in a different object. Make a separate object to maintain the sequence and hand out numbers, something like
public class MySequence {
private AtomicLong currentValue = new AtomicLong(0L);
public long getNextValue() {
return currentValue.getAndIncrement();
}
}
then use that sequence to initialize your objects:
new CoordinatePair(mySequence.getNextValue(), x, y);
By the way keeping user input separate from the model makes things simpler, you may want to instantiate your Coordinates class in cases where the input doesn't come from the user. Console input doesn't go in a constructor. You might have a Coordinate class like
public CoordinatePoint {
private long id;
private float x;
private float y;
public CoordinatePoint(long id, float x, float y) {
this.id = id;
this.x = x;
this.y = y;
}
public String toString() {
return "id=" + id + ", (" + x + ", " + y + ")";
}
}
and a main method like
public class Example {
public static void main(String ... args) {
MySequence seq = new MySequence();
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the X Coordinate followed by the return key");
float xCoordinate = keyboard.nextDouble();
System.out.println("Please enter the Y Coordinate followed by the return key");
float yCoordinate = keyboard.nextDouble();
CoordinatePoint c1 = new CoordinatePoint(seq.getNextValue(), xCoordinate, yCoordinate);
System.out.println(c1.toString());
}
}
You can either make that ID static, or you could just make a Parent class called "Coordinate" (with that ID again being static) with "Point" children, and increment the ID in the constructor of each "Point" object.
Static would seem like the way to go.

Instance Methods: complex numbers

I am currently doing solo text book work for java(not part of a class) and I'm stuck on a question.
Write an instance method modulus for this class that could be called by a statement like
double size = z.modulus(); where z is of type Complex. If z represented the value a + ib,
then the call would set the variable size to the value of |z| = square root(a2 + b2).
What am I doing wrong?
public class complex {
double re;
double im;
complex x;
public static void main(String[] args) {
public complex z = new complex();
{
z.im = In.getDouble();
z.re = In.getDouble();
}
//public complex modulus = (x);
//{
// x.im = z.im * z.im;
// x.re = z.re * z.re;
// return ;
//}
public double size() {
System.out.println(Math.sqrt(x.im+ x.re));
return Math.sqrt(x.im+ x.re);
}
double size = z.modulus();
// {
//}
private double modulus() {
// TODO Auto-generated method stub
x.im = z.im * z.im;
x.re = z.re * z.re;
return 0;
}
}
I made the changes and came out with this but it still doesn't work i put the errors next to the line in which they occur.
public class complex {
double re;
double im;
public complex z = new complex();
{
z.im = In.getDouble();
z.re = In.getDouble();}
public static void main(String[] args) {
private double modulus() { // insert enumIdentifier and body, Syntax error on "double" # expected.
return Math.sqrt( im * im + re * re );
}
double size = z.modulus();
}
}
You don't need to refer to either x or z. You have the right fields in your class to be able to calculate the modulus.
public double modulus() {
return Math.sqrt( im * im + re * re );
}
However, in the code in your question, you seem to be defining your class's methods inside the main method. You can't do that. Close off the definition of one method (with }) before starting the next.

Online grading says my output values are not correct but I don't see why?

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;
}
}

Java Code Questions

I want to implement a class which includes a student's name, their GPA, grade level, and their final score. We had to create a Tester along with the initial class creates 2 different students, prints their grade level, GPA, their name, and the calculated final test score.
Formula to calculate final test score = .60 * written + .40 * handsOn
Any help would be appreciated, I can't get this program down and I've been trying for quite a while now.
Here is my code:
Tester:
public class IntroToJavaTester
{
public static void main()
{
IntroToJava j1 = new IntroToJava("Joe", 11, 3.2);
System.out.println(j1.getName());
System.out.println(j1.getGradeLevel());
System.out.println(j1.getGPA());
System.out.println(j1.getFinalScore(written, handsOn));
IntroToJava j2 = new IntroToJava("Jim", 11, 3.2);
System.out.println(j2.getName());
System.out.println(j2.getGradeLevel());
System.out.println(j2.getGPA());
System.out.println(j2.getFinalScore( written,handsOn));
}
}
Here is the IntroToJava class:
public class IntroToJava
{
private String name;
private int glev;
private double gpa;
private double finalscore;
private double written = 80;
private double handsOn = 90;
public IntroToJava(String a, int b, double c, double d, double e)
{
name = a;
glev = b;
gpa = c;
written = d;
handsOn = e;
}
public String getName()
{
return name;
}
public int getGradeLevel()
{
return glev;
}
public double getGPA ()
{
return gpa;
}
public double getFinalScore(int written, int handsOn)
{
finalscore = .60*written+.40*handsOn;
return finalscore;
}
}
Your IntroToJava constructor is defined with 5 arguments and you're calling it with only 3 in IntroToJavaTester.
The two arguments you're omitting appear to correspond to the fields written and handsOn.
You've defined getFinalScore to take two arguments with the same names but a different type.
I suspect what you probably really want is for getFinalScore to take no arguments but use these two fields.
Or perhaps getFinalScore is supposed to just be a getter for the field finalScore which doesn't seem to be set or used anywhere, but has a suspiciously similar name.

Categories