public class Fan {
public static void main(String[] args){
Fan fan1 = new Fan();
fan1.setSpeed(FAST);
fan1.setRadius(10);
fan1.setColor("yellow");
fan1.setOn(true);
System.out.println(fan1.toString());
}
// fan speed variables
final static int SLOW = 1;
final static int MEDIUM = 2;
final static int FAST = 3;
// Other fan variables
private int speed;
private boolean on; // true means on
private double radius; // radius of fan
String color;
// No-arg constructor
public void Fan(){
speed = SLOW;
on = false;
radius = 5;
color = "blue";
}
// Mutator methods
public void setSpeed(int newSpeed){
if(newSpeed < 0)
System.out.println("Illegal speed!");
else
speed = newSpeed;
}
public void setOn(boolean newOn){
on = newOn;
}
public void setRadius(int newRadius){
if(newRadius < 0)
System.out.println("Illegal radius!");
else
radius = newRadius;
}
public void setColor(String newColor){
color = newColor;
}
// Accessor methods
public int getSpeed(){
return speed;
}
public boolean getOn(){
return on;
}
public double getRadius(){
return radius;
}
public String getColor(){
return color;
}
// toString method to output Fan data
public String toString(){
if(on = false)
return "Fan is off.";
else
return "Fan Properties:\n" + "Fan speed: " + speed + "\n"
+ "Color: " + color + "\n"
+ "Radius: " + radius + "\n";
}
}
The above piece of code is simple but I was wondering how the toString method uses the on variable even though I didn't supply parameters for that method. Also, why do we not need to invoke get methods in the main class and only need to invoke the set methods? (please explain how each method invokes one another until the final output)
Thanks a lot!
As far as you are in this class body you can access everything (except for static can not access non-static). That means that you can easily set and get variables like that:
var = <value>;
System.out.println(var);
However nobody stops you from using the accessor methods - getter and setters. It is just not required.
One final note:
if(on = false)
This will always fail - it does assignment to false and then checks the newly assigned value (which is false). You need to check for equality here. Like that:
if(on == false)
Or even better:
if(!on)
I just copied-pasted your code into a new file and compiled it. It compiled and ran. The output was
$ java Fan
Fan Properties:
Fan speed: 3
Color: yellow
Radius: 10.0
This is because the comparison in your toString method is wrong. It should be as following:
public String toString(){
if(on)
return "Fan Properties:\n" + "Fan speed: " + speed + "\n"
+ "Color: " + color + "\n"
+ "Radius: " + radius + "\n";
else
return "Fan is off.";
}
Related
I have to be able to convert some variables in my class. I have a boolean variable, WaGa (Stands for Workstation/Gaming computer), and if it's true, I want to convert String WorGam
I have to do this through service and support methods, and I keep trying, but I constenly fail. It just prints out what's in the driver. HELP.
public class Graphics
//instance data
{
private int Ram;
private String Brand;
private int Res;
private int BiWi;
private int BaCl;
private boolean K4;
private boolean WaGa;
private String WorGam;
//boolean WaGa, boolean K4, int BaCl, int BiWi, int Res, String Brand, int Ram
public Graphics (int R, String B, int Re, int Bi, int Ba, boolean K4, boolean Wa, String Wor ) // constructor
{
Ram = R;
Brand = B;
Res = Re;
BiWi = Bi;
BaCl = Ba;
K4 = K4;
WaGa = Wa;
Wor = WorGam;
}
public int get_Ram() //Accessor Method - there are 3 of them
{
return Ram;
}
public String get_Brand() //Accessor Method - there are 3 of them
{
return Brand;
}
public int get_Res() //Accessor Method - there are 3 of them
{
return Res;
}
public int get_BiWi() //Accessor Method - there are 3 of them
{
return BiWi;
}
public int get_BaCl()
{
return BaCl;
}
public boolean get_K4()
{
return K4;
}
public String WorGam(boolean WaGa)
{
String WorGam;
if ( WaGa == true) {
return WorGam = "Workstation";
} else {
return WorGam = "True";
}
}
public String toString()
{
return ("Ram" + " " + Ram + ". " + "Brand:" + " " + Brand + ". " + "Resolution" + " " + Res + ". " + "Processer" + " " + BiWi + "." + " " + "Base Clock" + " " + BaCl+ " " + "K4?" + " " + K4+ " " +WorGam);
}
}
public class Graphicse_Driver
{
public static void main(String [] args)
{
Graphics unique=new Graphics(4, "Nvinda", 6, 7, 9, false, false, "sdf" );
System.out.println(unique);
You may need to reread you code to make sure there aren't any other mistakes in your code, but this is the root of your problem.
In order to access the WarGam getter, you need to call:
System.out.println(unique.WarGam());
When you do System.out.println(unique), you are trying to print out the entire Graphics object instead of just the WarGam string.
You then should change your WarGam() method to look like the following:
public String WorGam()
{
if (WaGa) {
return "Workstation";
}
return "Gaming";
}
Here is a more in depth explanation of the changes:
WaGa is a private variable of your Graphics class. Since the WarGam() method is in the same Graphics class, it already had access to the WaGa variable, so you do not need to pass it in.
if(WaGa == true) is just a wordier way of writing if(WaGa).
Instead of creating a String WorGam variable, you can just return the string you want directly.
The else surrounding the second return is unnessary since that code will only be hit if the first return is skipped.
After these changes, the private String WarGam variable is really not necessary either.
public String worGam(boolean waGa) {
if (waGa)
return "Workstation";
else
return "Gaming";
}
You need to correct your worGam() function:
public String worGam(boolean waGa) {
if (waGa == true)
return "Workstation";
else
return "True";
}
And the main() function:
public static void main(String [] args) {
Graphics unique = new Graphics(4, "Nnn", 6, 7, 9, false, false, "xxx");
System.out.println(unique.WorGam(false));
}
I am new to java and am currently creating a program where I calculate various amounts of money (tax, gross pay, etc) using overload methods and then display it. I have completed the bulk of it (I think), but now I need to create a second class in the same package where I set values to the first program to see if it works. I have no idea how to call the method when overload methods are involved, I tried to use get and set but I don't know how to apply that in the overload method. I apologize if my terminology is off, I'm still quite new!
package payrolllibrary;
public class PayrollLibrary {
public static float calculatePay(float hours, float rates)
{System.out.println("Pay: " + rates*hours);
return 0;
}
public static float calculatePay(float hours, float rates, float multiplier)
{System.out.println("Pay: " + rates*hours*multiplier);
return 0;
}
public static float calculateGrossPay(float regularPay, float overtimePay, float shift2Pay, float shift3Pay, float weeklyPay)
{float grossPay;
grossPay = regularPay + overtimePay + shift2Pay + shift3Pay + weeklyPay;
System.out.println("Gross Pay: " + grossPay);
return 0;
}
public static float calculatedSocialSecurityTax(float grossPay, float ytdEarnings, float ytdSocialSecurity)
{
float calculateSocialSecurityTax = 0;
float calculateGrossPay = 0;
if(ytdEarnings > 118500)
{calculateSocialSecurityTax = 0;}
if (ytdEarnings+calculateGrossPay < 118500)
{calculateSocialSecurityTax = calculateGrossPay*.062f;}
if (ytdEarnings+calculateGrossPay > 118500)
{if (calculateGrossPay*.062 <= 118500)
{calculateSocialSecurityTax = 118500;}
}
{System.out.println("Social Security Tax: " + calculateSocialSecurityTax);
return 0;
}
}
public static float calculateMedicareTax(float grossPay)
{float medicareTax;
medicareTax = grossPay*.0145f;
System.out.println("Medicare Tax: " + medicareTax);
return 0;
}
public static float calculateStateTax(float grossPay, float stateWithholding)
{System.out.println("State Tax: " + grossPay*stateWithholding);
return 0;
}
public static float calculateNetPay(float grossPay, float federalWithholding, float socialSecurityWithholding, float medicareWithholding, float stateWithholding, float deduction1Amount, float deduction2Amount, float deduction3Amount)
{float calculateNetPay;
calculateNetPay = grossPay-federalWithholding-socialSecurityWithholding-medicareWithholding-stateWithholding-deduction1Amount-deduction2Amount-deduction3Amount;
System.out.println("Net Pay: " + calculateNetPay);
return 0;
}
public static float calculateDeduction(float grossPay, char deductionCode, float deductionValue)
{if (deductionCode == 'N')
{deductionValue = 0;}
else if (deductionCode == 'F')
{deductionValue = deductionValue;}
else if (deductionCode == 'P')
{deductionValue = deductionValue*grossPay;}
System.out.println("Deduction: " + deductionValue);
return 0;
}
}
package PayrollLibrary;
public class TestPayroll {
public static void main(String[] args) {
PayrollLibrary Person = new PayrollLibrary();
Person.setRate(99.99);
Person.setHours(99);
Person.setMultiplier(999);
Person.setRegularPay(999);
Person.setOvertimePay(999);
Person.setShift2Pay(999);
Person.setShift3Pay(999);
Person.setWeekendPay(999);
Person.setYtdEarnings(999);
Person.setYtdSocialSecurity(999);
Person.setStateWithholding(999);
Person.setDeduction1Amount(999);
Person.setDeduction2Amount(999);
Person.setDeduction3Amount(999);
Person.setDeductionCode('F');
Person.setDeductionAmount(999);
}
}
Those setXXX() won't set the values just because their English meaning are so. They are just names of methods. To set the values you have to code them. So in your PayrollLibrary you should have
public class PayrollLibrary {
float rate;
float hours;
......
public void setRate(float inRate) {
this.rate = inRate;
}
public void setHours(float inHours) {
this.hours = inHours;
}
Then in your calculation methods, if what you going to use are rate and hours, you don't have to pass them to the method, simply:
public float calculatePay() {
return rate*hours;
}
So in your main(), do this:
PayrollLibrary person = new PayrollLibrary();
person.setRate(99.99f);
person.setHours(99.0f);
to obtain the pay right after the setXXX above, do this:
float thePay = person.calculatePay();
Please note the Java convention: class names starts in upper case, variable and method names start in lower case.
Hope it helps.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I am trying to create a program where you can change a fans speed, color, radius, and whether you can turn the fan on or off, I have the fan class working fine, except for the toString() method, for some reason when I set some values in the test program, it just defaults to the regular values, any help is accepted.
Thank you.
public class Fan {
final int SLOW = 1;
final int MEDIUM = 2;
final int FAST = 3;
public int speed = SLOW;
public boolean on = false;
public double radius = 5;
public String color = new String("blue");
//fan on
boolean fanOn() {
on = true;
return on;
}
//fan off
boolean fanOff() {
on = false;
return on;
}
//sets fan speed
String setSpeed(String speed) {
if (speed == "SLOW"){
speed = String.valueOf(SLOW);
} else if (speed == "MEDIUM") {
speed = String.valueOf(MEDIUM);
} else if (speed == "FAST") {
speed = String.valueOf(FAST);
} else {
speed = "Please enter 'SLOW', 'MEDIUM' or 'FAST' to change the speed of the fan.";
}
return speed;
}
//sets custom radius
double setRadius(double rad) {
rad = radius;
return rad;
}
//sets custom color
String setColor(String colorType) {
return colorType;
}
//toString() method
public String toString() {
return ("Speed: " + speed + "\nRadius: " + radius + "\nColor: " + "\nOn: " + on);
}
}
//test program
public class TestFan {
public static void main(String[] args) {
Fan fan1 = new Fan();
fan1.setColor("green");
fan1.setSpeed("FAST");
fan1.setRadius(3.5);
fan1.fanOff();
System.out.println(fan1.toString());
}
}
This just outputs:
Speed: 1
Radius: 5.0
Color:
On: false
public class Fan {
final int SLOW = 1;
final int MEDIUM = 2;
final int FAST = 3;
public int speed = SLOW;
public boolean on = false;
public double radius = 5;
public String color = new String("blue");
//fan on
void fanOn() {
on = true;
return on;
}
//fan off
void fanOff() {
on = false;
return on;
}
//sets fan speed
void setSpeed(String speed) {
this.speed=speed;
}
//sets custom radius
double setRadius(double rad) {
rad = radius;
return rad;
}
//sets custom color
void setColor(String colorType) {
color = colorType;
}
//toString() method
public String toString() {
return ("Speed: " + speed + "\nRadius: " + radius + "\nColor: " + "\nOn: " + on);
}
}
//test program
public class TestFan {
public static void main(String[] args) {
Fan fan1 = new Fan();
fan1.setColor("green");
fan1.setSpeed("FAST");
fan1.setRadius(3.5);
fan1.fanOff();
System.out.println(fan1.toString());
}
}
The null-pointer exception error occurs in my toString method. I'm at a loss as to why. The error can occur through multiple ways. Most commonly, an object's reference is declared but the object itself remains uncreated. I've declared and created (is initialized the right word?) Mycircle circle1 = new Mycircle (); and Mypoint center = new Mypoint ();
I suspected that I hadn't initialized any of my fields when I invoked my getter methods, but that's not true. The setter methods work cleanly -- I've been successful in inputting values. Doesn't that imply that my getter methods can access some non-null value.
import java.util.Scanner;
public class MyCircle {
private Mypoint center;
private double radius;
Scanner input = new Scanner (System.in);
public MyCircle() {
radius = 0.0;
Mypoint center = new Mypoint ();
System.out.println("Enter coordinates here");
center.setCoordinateX(input.nextDouble());
center.setCoordinateY(input.nextDouble());
}
public String toString(MyCircle object) {
return "Circle # " + "(" + object.center.getCoordinateX() + "," +
object.center.getCoordinateY() + ")" + ". Its radius is " +
object.radius;
}
public double calcArea(MyCircle object) {
double area = Math.pow(object.radius, 2) * Math.PI;
return area;
}
public static void main (String[]args) {
MyCircle circle1 = new MyCircle ();
circle1.radius = 3.0;
System.out.println(circle1.calcArea(circle1));
System.out.println(circle1.toString(circle1));
}
}
class Mypoint {
private double posX;
private double posY;
public void setCoordinateX(double x) {
posX = x;
}
public void setCoordinateY(double y) {
posY = y;
}
public double getCoordinateX() {
return posX;
}
public double getCoordinateY() {
return posY;
}
}
In your MyCircle constructor, you're creating a local variable called center here:
Mypoint center = new Mypoint ();
What you probably want is to initialize the instance member:
center = new Mypoint ();
Your code doesn't make much sense, presumably this
public String toString(MyCircle object)
{
return "Circle # " + "(" + object.center.getCoordinateX() + ","
+ object.center.getCoordinateY() + ")"
+ ". Its radius is " + object.radius;
}
Should be
#Override
public String toString() {
return "Circle # (" + center.getCoordinateX() + ","
+ center.getCoordinateY()
+ "). Its radius is " + radius;
}
Then let's fix your constructor, use this so you know you're updating the instance field (instead of shadowing it) -
public MyCircle() {
this.radius = 0.0;
this.center = new Mypoint(); // <-- this.center
System.out.println("Enter coordinates here");
this.center.setCoordinateX(input.nextDouble());
this.center.setCoordinateY(input.nextDouble());
}
First of all, your toString() method is untypical. You want a Circle#toString() with no argument and produce a print representaton of yourself (i.e. this instead of object=).
Your toString method can fail if:
object is null
object.center is null
object.center.getCoordinateX() or getCoordinateY() itself throws exception.
The later case would be visible in the stacktrace, the other two cases all show the same line number as the cause.
It looks like the second case is your problem (as you fill a local variable and not the field of MyCircle).
BTW: using a input scanner in a constructor is a horrible layering violation. You should seperate input/output/user interaction logic from the geometric (circly, point) classes.
There are many things wrong in your code beside what #Mike pointed out.
Getting input from the user within the constructor is bad. You should get the input in the main method, and pass it to the constructor. In addition, you don't initialize the radius. It remains 0.0.
The constructor call should look like this (the MyPoint object passed to the constructor should be initialized prior to calling the constructor) :
MyCircle circle1 = new MyCircle (center, radius);
The constructor should look like this :
public MyCircle(MyPoint center, double radius)
{
this.radius = 0.0;
this.center = center;
}
The toString and calcArea methods don't need a parameter. They should operate on the current object (this) :
public String toString()
{
return "Circle # " + "(" + this.center.getCoordinateX() + "," + this.center.getCoordinateY() + ")" + ". Its radius is " + this.radius;
}
I am still at HelloWorld when it comes to my lack of Java skills. I cannot understand this to save my life. I am working on writing an override method? And am just starting out with the code provided from my school before I even start trying to complete the rest and I am already getting errors that I cannot even begin to think of how to correct. Any help at all would be greatly appreciated. I just want this error to go away so I can create some new ones :)
Here is the code:
public class Vehicle
public static void main (String [] args)}
{
private boolean moving; // whether or not the vehicle
private double speed;
private char bearing;
('N','E','S', or 'W')
public Vehicle(){ // Vehicle class no-arg constructor
moving = false; // assume not moving
speed = 0.0; // not moving
bearing = 'N'; // assume 'N'orth
System.out.println("Created a vehicle (no-arg)");
}
public Vehicle (double initialSpeed) // Vehicle 1-arg constructor
bearing = 'W';
speed = initialSpeed;
if (speed > 0.0)
{
moving = true;
}
System.out.println("Created a vehicle (1-arg)");
public Vehicle (double initialSpeed, char initialBearing) // Vehicle 2-arg constructor
bearing = initialBearing;
speed = initialSpeed;
if (speed > 0.0){
moving = true;
}
System.out.println("Created a vehicle (2-arg)");
public void start(double initialSpeed, char initialBearing){
moving = true;
if (initialSpeed >= 5.0 && initialSpeed <= 20.0){
speed = initialSpeed; // valid expected range
} else if (initialSpeed >= 0.0 && initialSpeed < 5.0){
speed = 5.0; // minimum
} else if (initialSpeed < 0.0){
speed = 0.0; // assume no movement
moving = false;
} else if (initialSpeed > 20.0){
speed = 20.0; // maximum allowed
}
switch(initialBearing){
case 'N':
bearing = initialBearing;
break;
case 'E':
bearing = initialBearing;
break;
case 'S':
bearing = initialBearing;
break;
case 'W':
bearing = initialBearing;
default:
System.out.println("invalid bearing " +
initialBearing +
" set to N"); // additional user notification
bearing = 'N';
}
public double getSpeed() { // get and return current speed in mph
return speed;
}
public void setSpeed(double newSpeed){ // set new speed in mph
speed = newSpeed;
}
/**
*
* #return
*/
public char getBearing(){
return bearing;
}
public void speedUp(double mphSteps, int numSteps){
int counter = 0;
while (counter < numSteps)
speed += mphSteps;
System.out.println("counter= " + counter + ", " +
this.toString());
counter++;
}
public String toString(){
return "From toString(): speed= " + getSpeed() +
" mph and bearing= " + getBearing();
}
}
public class Car extends Vehicle{
private String color;
private int doors;
private double hp;
public Car(String carColor, int numDoors,
double horsePower, double
startingSpeed)
{
super(startingSpeed);
color = carColor;
doors = numDoors;
hp = horsePower;
System.out.println("Created a car");
}
public String getColor()
{
return color;
}
public int getDoors()
{
return doors;
}
public double getHp()
{
return hp;
}
public String toString()
{
return "From Car toString(): color= " + getColor() +
" doors= " + getDoors() +
" hp= " + getHp() +
" speed= " + getSpeed() +
" mph and bearing= " + getBearing();}
}
public class TestCar2
{
public static void main(String[] args)
{
Car myCar2 = new Car("blue", 4, 300., 10.0);
System.out.println(myCar2.toString());
myCar2.speedUp(5.0, 2);
}
}
Please Please and thank you for helping!
public class Vehicle
public static void main (String [] args)} // this is totally wrong
// This not compile at least
{
Actually parenthesis({}) you are using is totally wrong. Following structure should follow you. I am guessing that you are not using IDE to do coding. I suggest you to use IDE to do code.
public class MyClass{
public static void main(String[] args){
// main method
}
// some other method
}
Firstly You cannot have two public classes in a single file!!
Secondly you braces are completely unmatching.
public class Vehicle
public static void main (String [] args)}
{
Class has it's own scope and main() function has it's own. So change your code to
public class Vehicle {
public static void main (String [] args) { //your code}
}
your multiple arg constructors don't have proper brackets.
public Vehicle (double initialSpeed) // Vehicle 1-arg constructor
bearing = 'W';
speed = initialSpeed;
if (speed > 0.0)
{
moving = true;
}
System.out.println("Created a vehicle (1-arg)");
change it to
public Vehicle (double initialSpeed) { // Vehicle 1-arg constructor
bearing = 'W';
speed = initialSpeed;
if (speed > 0.0)
{
moving = true;
}
System.out.println("Created a vehicle (1-arg)");
}
lastly your switch statement you need to put break in all cases(except default)
change
case 'W':
bearing = initialBearing;
to
case 'W':
bearing = initialBearing;
break;
If you are new to java and learning basics I suggest use an IDE like Eclipse, Netbeans or Intellij IDEA. Google them to find more info.