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.
Related
At the end of the program, when it prints out what was behind your door, it gets the default string instead of the mutated one, but the mutated one was called and worked perfectly fine with the previous method. Why?
Also, the answer to what is behind your chosen door always seems to be the bad prize (goat). Is This just a coincidence?
If you spot any other errors in my program please comment below.
This is class 1
package montehallproblem;
import java.util.Random;
public class GameInfo {
private boolean reset;
private String D1;
private String D2;
private String D3;
private String res1;
private String res2;
private int choice;
public GameInfo(){
res1 ="new car";
res2 ="goat";
choice = 404;
reset = false;
// NOTE: If un-mutated, the Door Strings will default to this result every time
D1 = res1;
D2 = res2;
D3 = res2;
}
public void manualSetChoicesAndDoors(String one, String two, int d1, int d2, int d3){
setResult1(one);
setResult2(two);
//NOTE: This allows the OLC to utilize the previously typed prize strings;
if(d1==1){
setDoor1(res1);
}else if(d1==2){
setDoor1(res2);
}else if(d2==1){
setDoor2(res1);
}else if(d2==2){
setDoor2(res2);
}else if(d3==1){
setDoor3(res1);
}else if(d3==2){
setDoor3(res2);
}
}
public void setDoor1(String x){
D1 = x;
}
public void setDoor2(String x){
D2 = x;
}
public void setDoor3(String x){
D3 = x;
}
public void setResult1(String x){
res1 = x;
}
public void setResult2(String x){
res2 = x;
}
public void setChoice(int x){
choice = x;
}
public void setReset(boolean x){
reset = x;
}
public String getDoor1(){
return D1;
}
public String getDoor2(){
return D2;
}
public String getDoor3(){
return D3;
}
public String getResult1(){
return res1;
}
public String getResult2(){
return res2;
}
public int getChoice(){
return choice;
}
public void generatePrizeDoor(){
if(reset){
Random rand = new Random();
int prize = rand.nextInt(3);
//NOTE: this determines which door has the best prize behind it (res1)
switch(prize){
case 1:
setDoor1(getResult1());
setDoor2(getResult2());
setDoor3(getResult2());
break;
case 2:
setDoor1(getResult2());
setDoor2(getResult1());
setDoor1(getResult2());
break;
case 3:
setDoor1(getResult2());
setDoor1(getResult2());
setDoor1(getResult1());
System.out.println("a new game generates...");
}
}
}
public void revealBadDoor(){
//NOTE: This reveals one of the doors with the bad prize in it;
//NOTE: Appends "used" to door string so that it can be detected later
if(getDoor1().contains(getResult2()) && getChoice() != 1){
System.out.println("Monty reveals door one contains a "+getResult2());
setDoor1(getDoor1()+"used");
}else if(getDoor2().contains(getResult2()) && getChoice() != 2){
System.out.println("Monty reveals door two contains a "+getResult2());
setDoor2(getDoor2()+"used");
}else if(getDoor3().contains(getResult2()) && getChoice() != 3){
System.out.println("Monty reveals door one contains a "+getResult2());
setDoor3(getDoor3()+"used");
}
}
public void switchDoorChoice(String x){
//NOTE: This changes your door choice to the door string that doesnt contain "used"
if(x.contains("yes")){
switch(getChoice()){
case 1:
if(getDoor2().contains("used")){
setChoice(3);
}else if(getDoor3().contains("used")){
setChoice(2);
}
break;
case 2:
if(getDoor3().contains("used")){
setChoice(1);
}else if(getDoor1().contains("used")){
setChoice(3);
}
break;
case 3:
if(getDoor2().contains("used")){
setChoice(1);
}else if(getDoor1().contains("used")){
setChoice(2);
}
System.out.println("you choose to switch to door "+getChoice());
}
}else if(x.contains("no"))
System.out.println("You choose to stay with door "+getChoice());
}
}
public void revealPlayerDoor(){
switch(getChoice()){
case 1:
System.out.println("Monty reveals your door contains "+getDoor1());
break;
case 2:
System.out.println("Monty reveals your door contains "+getDoor2());
break;
case 3:
System.out.println("Monty reveals your door contains "+getDoor3());
}
}
}
I have two files one is the driver, I'm having a problem with setters. It looks did set the value .
public class Movie {
private String name;
private int minutes;
protected int tomatoScore;
public Movie(String name, int minutes, int tomatoScore)
{
this.name=name;
this.minutes=minutes;
this.tomatoScore=tomatoScore;
}
public String getName() {return name;}
public void setName(String name) {this.name=name;}
public int getMinutes() {return minutes;}
public boolean setMinutes(int minutes) {return minutes>=0;}
public int getTomatoScore() {return tomatoScore;};
public boolean setTomatoScore(int tomatoScore) {return tomatoScore>=0 &&tomatoScore<=100;};
public boolean isFresh() {return tomatoScore>=60;};
public void display()
{
//this.name = name;
//this.minutes = minutes;
//this.tomatoScore =tomatoScore;
System.out.println("Movie: "+ getName());
System.out.println("Length: "+ getMinutes() +"min.");
if(tomatoScore>=60)
{
System.out.println("TomatoScore: Fresh");
}
else
{
System.out.println("TomatoScore: Rotten");
}
}
}
and bellow is the driver file if you notice the setters did do the job that is supposed to do I believe the problem is movie class, if you run the driver to test the program you see if you set the value to the negative the if statement does not function properly.( setMinutes and setTomatoScore are wrong. They do not set the class fields at all)
public class MovieDriver {
public static void main (String [] args){
Movie[] myCollection = new Movie[5];
myCollection[0] = new Movie("Batman The Dark Knight", 152, 94);
myCollection[1] = new Movie("Guardians of the Galaxy", 125, 91);
myCollection[2] = new Movie("The GodFather", 178, 98);
myCollection[3] = new Movie("Suicide Squad", 137, 27);
myCollection[4] = new Movie("Get out", 104, 99);
//TODO
//Initialize the variable below and add it to myCollection at index 4.
//You can pick any movie you wish.
Movie yourMovie;
System.out.println("Here are all the movies in my collection of movies.\n");
for(int i = 0; i < myCollection.length; i++) {
if(myCollection[i] != null)
myCollection[i].display();
}
System.out.println("_______________________________________________");
System.out.println("\nHere are the Fresh movies.");
for(int i = 0; i < myCollection.length; i++) {
if(myCollection[i] != null && myCollection[i].isFresh()) {
System.out.println(myCollection[i].getName() + " is fresh.");
}
}
System.out.println();
System.out.println("Here are the Rotten movies.");
for(Movie movieTmp: myCollection){
if (movieTmp != null && !movieTmp.isFresh())
System.out.println(movieTmp.getName() + " is rotten.");
}
System.out.println("_______________________________________________\n");
Movie harryPotter = new Movie("Harry Potter and the Prisoner of Azkaban", 144, 91);
System.out.println("The movie " + harryPotter.getName() + " was created.\n");
System.out.println("Is " + harryPotter.getName() + " a long movie?");
if(harryPotter.getMinutes() > 120) {
System.out.println("Yes, it is a bit long.\n");
} else {
System.out.println("Nope, that isn't too bad.\n");
}
System.out.println("Can I set the minutes of " + harryPotter.getName() + " to a negative number?");
harryPotter.setMinutes(-5);
if(harryPotter.getMinutes() == -5) {
System.out.println("It worked. The runtime is -5 minutes.\n");
} else {
System.out.println("It did NOT work. Negative runtimes are not allowed.\n");
}
System.out.println("Can I set tomato score of " + harryPotter.getName() + " to a negative number?");
harryPotter.setTomatoScore(-100);
if(harryPotter.getTomatoScore() == -100) {
System.out.println("It worked. The score is -100. This movie is terrible according to the site.\n");
} else {
System.out.println("It did NOT work. Negative scores are not allowed.\n");
}
System.out.println("Can I set tomato score of " + harryPotter.getName() + " to a number greater than 100?");
harryPotter.setTomatoScore(101);
if(harryPotter.getTomatoScore() == 101) {
System.out.println("It worked. The score is 101. Best Harry Potter movie ever!\n");
} else {
System.out.println("It did NOT work. Still the best Harry Potter movie out all the movies though.\n");
}
}
}
Your setMinutes and setTomatoScore methods don't set anything, they just return a boolean. I assume you've forgotten to add this.tomatoScore = tomatoScore for example.
As rzwitserloot mentioned, setter function for minutes and tomatoScore are not setting any thing.This might be the case.
Additional I would like add, I found it is better to use well known IDE for java programming like intellij, netBean, eclipse. They have provide many feature like auto generate setter, getter , constructor. So we can focus more on core logic and this saves our time and reduce possiblity of manual error.
One more point I would like to add,
It is better to use setter in the constructor, so before setting value is we want to perform any input validation,we can have that in setter and can use that even when setting value via constructor.
For an example,
public class Example {
private int x;
public Movie(int x){setMinutes(x);}
public void setX(int x) {
//some validation on input
if(x >= 0){this.x = x;}
public int getX() {return x;}
Looks like you need this:
public boolean setMinutes(int minutes) {
if(minutes >= 0 && minutes < 60) {
//I'm guessing the <60 part here, but whatever,
//this is how you'd set the 100 limit on your setTomatoScore method
this.minutes = minutes;
return true;
}
return false;
}
Make similar corrections for the setTomatoScore
You need to set something tomatoScore in the state of methods as shown below :
public boolean setTomatoScore(int tomatoScore) {
if (tomatoScore >= 0 && tomatoScore <= 100) {
this.tomatoScore = tomatoScore;
return true;
}
return 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());
}
}
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.";
}