Syntax error on token(s), misplaced construct(s) in Eclipse - java

So I'm having troubles with my program here. I'm supposed to write a program that calls for the Accelerate / Brake methods in a car. I'm getting the Syntax error in the first half of the code, but the second half is marked as correct.
Car class:
public class Car {
private int yearModel;
private String make;
private int speed;
public Car(String m, int year) {
yearModel = year;
make = m;
speed = 0;
}
// Declare mutators (methods).
// Declare accessors (methods).
public int getModel() { // Model year of car.
return yearModel;
}
public String getMake() {
return make;
}
public int getSpeed() {
return speed;
}
public void setModel(int year) {
yearModel = year;
}
public void setMake(String carMake) {
make = carMake;
}
public void setSpeed(int s) { // Incorrect??? Possible outSpeed = speed;
speed = s; // Not sure if correct; should be "0" | or equal to "carSpeed"
}
public void accelerateSpeed() {
speed += 5;
// Each call will increase by 5.
}
public void brakeSpeed() {
speed -= 5;
// Each call will decrease by 5.
}
}
CarResults class:
import javax.swing.JOptionPane;
class CarResults {
public static void main(String[] args) {
String input, carMake;
int model, yearModel, year, s;
Car myCar = new Car("Car", 2011);
// Retrieve car's Make & Model.
carMake = JOptionPane.showInputDialog("What is the Make of your car? ");
myCar.setMake(carMake);
year = Integer.parseInt(JOptionPane.showInputDialog("What is the Model Year of your car? "));
myCar.setModel(year);
input = JOptionPane.showInputDialog("Enter your car's speed: ");
s = Integer.parseInt(input);
myCar.setSpeed(s);
for (int i = 0; i < 5; i++) {
myCar.accelerateSpeed();
System.out.println();
System.out.println("The " + " " + myCar.getModel() + " " + myCar.getMake() +
" is gradually accelerating. ");
// Apply acceleration.
System.out.println("Your current speed is: " + myCar.getSpeed());
}
// Begin applying brakes.
System.out.println();
System.out.println("\t>>> Now, let's get the results for applying the brakes... ");
System.out.println();
for (int i = 0; i < 5; i++) {
myCar.brakeSpeed();
System.out.println();
System.out.println("[Braking] Your" + " " + myCar.getModel() + " " + myCar.getMake() + " is now traveling at: ");
// Apply brakes.
System.out.println("Now your speed is: " + myCar.getSpeed());
}
// End the program.
System.exit(0);
}
}

I don't think there is anything wrong with this. I was able to compile and run this just fine. Try compiling on your command line with
javac CarResults.java Car.java
and then run it with
java CarResults

Related

Why does my Mooc.fi ski jumping programm not print the correct score? Is it overwritten?

I am working on mooc.fi week 8, the last exercise: ski jumping. At the very bottomt of the page. Here is the link: https://materiaalit.github.io/2013-oo-programming/part2/week-8/
All tests are succesfull, except for the calculation of the output.
When the jumpers jump twice, the scores of the first and second jump are meant to be added. If the user decides to terminate the programm at this point, the jumpers are meant to be printed out, winner first, with their final scores assigned to them.
As the actual final scores printed can (based on the number) only be the result of one jump, I suspect that the programm overwrites the first jump with the second instead of adding them, but I am not sure.
The error message says, that the actual final score is supposed to be 275 but was actually 158, which with two rounds and therefore two executed jumps is just not a possible score if the jumper had actually been assigned the score of two jumps and not just one.
But it is difficult for me to assess that as the jump length and the points assigned by the judges (which together make up the jumper's score) are generated randomly.
The error message I receive when testing is the following:
"twoRoundsOneJumperCalculationCorrect Failed: Jumper Arto's points are printed incorrectly in the tournament results your programm prints.
I have tested the calculation in the programm while it is running and the points the jumpers receive while jumping are accurate. Only the final results seem to be off. I am not sure why that is the case though. They appear to be overwritten with new scores.
I have gone through the code again to find what I am doing wrong, but I just cannot see where the mistake is.
I have divided the programm in four classes:
-Main to execute the UserInterface
-UserInterface for the organizing and printing the programm
-Jumper for creating jumpers for the ski tournament and to execute everything related to them such as jumping and the calculation of the scores
-SortAgainstPoints to sort the jumpers in ascending order by score
Here is my code:
//Main:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
UserInterface ui = new UserInterface();
ui.start(reader);
}
}
//UserInterface:
import java.util.*;
import java.util.Set;
import java.util.TreeMap;
public class UserInterface {
private HashMap<String,Jumper> participants;
private Jumper participant;
public UserInterface()
{
this.participants = new HashMap<String,Jumper>();
}
public void start(Scanner reader)
{
System.out.println("Kumpula ski jumping week");
System.out.println("");
System.out.println("Write the names of the participants one at a time; an empty string brings you to the jumping phase.");
while(true)
{
System.out.print(" Participant name: ");
String name = reader.nextLine();
if(!name.isEmpty())
{
this.participant = new Jumper(name);
this.participants.put(name, participant);
}
if(name.isEmpty())
{
System.out.println("");
break;
}
}
System.out.println("The tournament begins!\n");
rounds(reader);
}
public void sortAgainstPoints(ArrayList<Jumper> list)
{
Collections.sort(list, new SortAgainstPoints());
}
public void rounds(Scanner reader)
{
int roundCounter = 0;
ArrayList<Jumper> list = new ArrayList<Jumper>(this.participants.values());
while(true)
{
sortAgainstPoints(list);//does that even work????
System.out.print("Write \"jump\" to jump; otherwise you quit: ");
String input = reader.nextLine();
System.out.println("");
roundCounter ++;
if(!input.equals("jump"))
{
break;
}
System.out.println("Round " + roundCounter + "\n");//Round 1 ...
System.out.println("Jumping order:");
int counter = 0;
for(Jumper p : list)
{
counter++;
System.out.println(" " + counter + ". " + p);
}
System.out.println("");
System.out.println("Results of round " + roundCounter);
for(Jumper p : list)
{
int jumpLength = p.jump();
p.addJumpLength(jumpLength);
int[] judgesScores = new int[5];
judgesScores = p.judgeScores();
int score = 0;
score += p.jumpScore(jumpLength, judgesScores);
p.setPoints(score);
System.out.print(" " + p.getName() + "\n" +
" length: " + jumpLength + "\n" +
" judge votes: " + p.printJudgesScores(judgesScores) +"\n"
);
}
sortAgainstPoints(list);
System.out.println("");
}
Collections.reverse(list);//highest scored jumper should now be first
System.out.println("Thanks!\n");
System.out.println("Tournament results:");
System.out.println("Position Name");
for(int i = 0; i < list.size(); i++)
{
System.out.println((i +1) + " " + list.get(i).getName() + " (" + list.get(i).getPoints() + ")\n"
+ " jump lengths: " + list.get(i).printJumpLengths());
}
//tournament result does not equal acutal points and jump lengths, assignment is most likely overwritten with each new jump
}
}
//Jumper:
import java.util.*;
public class Jumper {
private String name;
private int points;
private Random random;
private int[] judges;
private ArrayList<Integer> jumpLengths;
public Jumper(String name)
{
this.name = name;
this.points = 0;
this.jumpLengths = new ArrayList<Integer>();
}
#Override
public String toString()
{
return this.name + " (" + this.points + " points)";
}
public int getPoints()
{
return this.points;
}
public int jump()
{
this.random = new Random();
int jumpLength = random.nextInt(120 - 60 +1) + 60;
return jumpLength;
}
public int[] judgeScores()
{
this.judges = new int[5];
for(int i = 0; i< judges.length; i++)
{
int judgeScore = random.nextInt(20 - 10 +1) + 10;
judges[i] = judgeScore;//scores, unsorted
}
return judges;
}
//smallest and largest judge score are meant to be skipped as specified //by task
public int jumpScore(int jumpLength, int[] judges)
{
sort(judges);//sorted
//skip first and last:
int score = jumpLength;
for(int i = 1; i < judges.length-1; i++)//skips first and last index
{
score += judges[i];
}
return score;
}
public String printJudgesScores(int[] judges)
{
String judgesScores = "[";
for(int i = 0; i < judges.length-1; i++)
{
judgesScores += judges[i] + ", ";
}
judgesScores += judges[judges.length-1] +"]";
return judgesScores;
}
public String getName()
{
return this.name;
}
public void setPoints(int points)
{
this.points = points;
}
public int[] sort(int[] judges)
{
for(int i = 0; i < judges.length; i ++)
{
for(int j = i+1; j < judges.length; j++)
{
if(judges[i] > judges[j])
{
int temp = judges[i];
judges[i] = judges[j];
judges[j] = temp;
}
}
}
return judges;
}
public void addJumpLength(int jumpLength)
{
this.jumpLengths.add(jumpLength);
}
public String printJumpLengths()
{
String jumps = "jump lengths: ";
for(int i = 0; i < this.jumpLengths.size()-1; i++)
{
jumps += this.jumpLengths.get(i) + " m, ";
}
jumps += this.jumpLengths.get(this.jumpLengths.size()-1) + " m";
return jumps;
}
}
//SortAgainsPoints:
import java.util.Comparator;
public class SortAgainstPoints implements Comparator<Jumper> {
public int compare(Jumper jumper1, Jumper jumper2)
{
if(jumper1.getPoints() > jumper2.getPoints())
{
return 1;
}
else if(jumper1.getPoints() < jumper2.getPoints())
{
return -1;
}
else
return 0;
}
}
I would appreciate any help!
I have done my best to post a good question, I know there are many better ones out there. If there is anything I can do to make the question clearer, let me know!
Edit: In case anybody is wondering, it's because I did not update the points correctly, I just replaced the old score with the new. It should have been p.setPoints(p.getPoints() + score);
instead of p.setPoints(score);

How do I get my 2 objects and call a function passing a variable through it?

In my driver class CarRaceSim in the function race I call both of my objects car1 and car2. Then I call the accelerate and brake function from my CarRace class that is supposed to add and subtract a random number from the speed variable that is passed in accelerate and brake. The speed variable is an int that the user assigns a value to. However, when I call the function and print it out it displays only what the user put in. The program in general is supposed to simulate 5 races in which each lap (loop 5 times) the car accelerates and brakes which is why I called accelerate and brake for both cars. How can I get accelerate and brake to function properly?
package carrace;
import java.util.Random;
/**
*
* #author Daniel
*/
public class CarRace {
int year, speed;
String model, make;
// default constructor
public CarRace(){
year = 2000;
model = "";
make = "";
speed = 0;
}
// non-default constuctor
public CarRace(int aYear, String aModel, String aMake, int aSpeed){
this.year = aYear;
this.model = aModel;
this.make = aMake;
this.speed = aSpeed;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public void accelerate(int speed){
Random randomNum = new Random();
int ranNum;
ranNum = randomNum.nextInt(26) + 5;
speed += ranNum;
}
public void brake(int speed){
Random randomNum = new Random();
int ranNum;
ranNum = randomNum.nextInt(26) + 5;
speed -= ranNum;
}
public String toString(){
return "The year of the car is " + year + ", the model of the car is " + model + ", the make of the car is " + make + ", and the initial speed is " + speed + ".\n";
}
}
package carrace;
import java.util.Scanner;
/**
*
* #author Daniel
*/
public class CarRaceSim {
public static CarRace car1;
public static CarRace car2;
public static void main(String[] args) {
System.out.println("Welcome to the car simulation program!");
System.out.println("You will now begin to create your two cars to race, good luck!\n\n");
createCar(1);
createCar(2);
race(car1, car2);
}
public static void createCar(int carCreation){
Scanner keyboard = new Scanner(System.in);
int year = 0;
String model;
String make;
int speed = 0;
do{
if (carCreation == 1)
System.out.println("Create your first car!");
else
System.out.println("Create your second car!");
System.out.println("What year is your car?");
year = keyboard.nextInt();
System.out.println("What model is your car?");
model = keyboard.next();
System.out.println("What make is your car?");
make = keyboard.next();
System.out.println("What speed is your car initially starting at? (0-60)");
speed= keyboard.nextInt();
if(speed < 0){
System.out.println("You can not begin at a negative speed, please choose between 0-60.");
}
else if(speed > 60){
System.out.println("You can not start above 60, please choose between 0-60.");
}
}while(speed <= 0 && speed >= 60);
if(carCreation == 1){
car1 = new CarRace(year, model, make, speed);
System.out.println(car1);
}
else{
car2 = new CarRace(year, model, make, speed);
System.out.println(car2);
}
}
public static void race(CarRace carUno, CarRace carDue){
for(int i = 1; i <= 5; i++){
System.out.println("Lap " + i);
System.out.println("Car 1's stats:");
car1.accelerate(car1.getSpeed());
System.out.println(car1.getSpeed());
car1.brake(car1.getSpeed());
System.out.println(car1.getSpeed());
System.out.println("Car 2's stats:");
car2.accelerate(car2.getSpeed());
System.out.println(car2.getSpeed());
car2.brake(car2.getSpeed());
System.out.println(car2.getSpeed() + "\n");
}
}
}
In your accelerate() function you assign a value to the local variable speed. What you want to assign to is the class variable this.speed, just like you do in your other methods (like setMake() for example).
In other words change
speed += ranNum;
to
this.speed += ranNum;
Do the same for your brake function.
The value that you change in accelerate() and brake() methods is updated on the variable that you passing not on the speed variable of class.
To assign new value to speed variable of class add following line in your accelerate() and brake() methods:
//for accelerate() method
//add below line after speed += ranNum;
this.speed = speed;
//for brake() method
//add below line after speed -= ranNum;
this.speed = speed;
Also see Instance Variable Hiding for further explanation on why you need to do this.
You should change your accelerate method as following:
public void accelerate(int speed){
Random randomNum = new Random();
int ranNum;
ranNum = randomNum.nextInt(26) + 5;
this.speed += ranNum;
}
Similarly u have to change brake method

Create different classes, a CarDemo class and a Car class

Creating an external Car class and driver CarDemo class. Alter the instructions for the CarDemo class to include two methods (getInputYear() that returns a year between 1940 and 2016 and getInputMake() that returns the make of the car and checks for an empty String).
It compiles without errors but It only asks for the year model input and then prints out everything else on its own.
public class Car
{
private int yearModel;
private String make;
private int speed;
// initialize variables
Car(int y, String m)
{
yearModel = y;
make = m;
speed = 0;
}
// setYear method
public void setYearModel(int y)
{
yearModel = y;
}
// setMake method
public void setMake(String m)
{ make = m;
}
// set speed method
public void setSpeed(int s)
{
speed = s;
}
// getYearModel method
public int getYearModel()
{
return yearModel;
}
// getMake method
public String getMake()
{
return make;
}
// getSpeed method
public int getSpeed()
{
return speed;
}
// accelerate method accelerates the car's speed by 5
public void accelerate()
{
speed += 5;
}
// brake method decreases the car's speed by 5
public void brake()
{
speed -= 5;
}
}
and this is the DemoCar class
import java.util.Scanner;
public class CarDemo
{
public static void main(String[] args)
{
Car yourCar;
String make;
double yearModel, speed;
Scanner sc = new Scanner(System.in);
System.out.print("What is the car's year model? ");
yearModel = sc.nextDouble();
System.out.print("What is the make of the car? ");
make = sc.nextLine();
yourCar = new Car(0, make);
System.out.println("Current status of the car:");
System.out.println("Year model: " + yourCar.getYearModel());
System.out.println("Make: " + yourCar.getMake());
System.out.println("Speed: " + yourCar.getSpeed());
// Accelerate the car five times.
System.out.println("Speed up!");
System.out.println();
for(int i=0; i<5; i++)
{
yourCar.accelerate();
System.out.println("demoCar's speed " + yourCar.getSpeed());// Display the speed.
}
System.out.println();
// Brake the car five times.
System.out.println("Slow down!");
System.out.println();
for(int i=0; i<5; i++)
{
yourCar.brake();
System.out.println("demoCar's speed " + yourCar.getSpeed());// Display the speed.
}
}
}
sc.nextDouble(); didn't handle the newline character and your sc.nextLine() consumed it and skip the rest.
You can add one more nextLine() to capture the left-over newline character.
System.out.print("What is the car's year model? ");
yearModel = sc.nextDouble();
boolean isInRange = (1940 <= yearModel) && (yearModle <= 2016);
if(!isInRange){
// not in range
return;
}
sc.nextLine(); // consumes the left-over newline character.
System.out.print("What is the make of the car? ");
make = sc.nextLine();
Alternatively:
System.out.print("What is the make of the car? ");
make = sc.nextLine();
change sc.nextLine() to sc.next()
method next() finds and returns the next complete token from this scanner.

Java: Use an Array over a Linked list

I am relatively new to Java. And I am a Student in the second semester.
The following has been my last task, and I have already presented it. Everything was fine, and the task that was neccessary for me to accomplish has been completely fulfilled.
The task over the semester was making a little game (My choice was guess a number game), and the tasks were simply build upon eachother. (e.g. use at least 5 functions, at least 3 classes, show all four examples of OOP and make a Computer Player)
So having that said I do not mean for people to solve these task because as you will see they have been completed.
Just one additional thing gives me trouble.
I use a Linked list to store the guessed numbers and recall them when needed.
So finally my question is:
How would I go about switching the Linked list with an Array?
Here the code:
Here the Run Class:
package fourfive;
public class Run {
/*
The Game Initializing class!
>>>> "game.getNumPlayers()" //can be uncommented if you want to play
if left commented, you can watch the bots fight to the death.
------------------------------------------------------
game.setBotPlayers //Same as getNumPlayers - defines how many (Bot) players you want to add
------------------------------------------------------
game.setTopNum() // defines the maximum range of numbers
which you want to guess. Starting from 0!
-----------------------------------------------------
*/
public static void main(String[] args){
Game game = new Game(0);
//game.getNumPlayers();
game.setBotPlayers(100);
game.setTopNum(2000);
game.start();
}
}
Game Class:
package fourfive;
import java.util.Random;
import java.util.Scanner;
public class Game {
/*
Some Variables being defined here.
*/
private static Scanner input = new Scanner(System.in);
private int MAX_Tries;
private int TOP_Num;
private int numPlayers;
private int numBots;
private boolean gameWinner = false;
private Random rand = new Random();
private int num;
private Participants[] players; //inheritance 1
private Participants currentPlayer; //polymorphism 1
public Game(int numPlayers) {
this(numPlayers, 10);
}
public Game(int numPlayers, int maxTries) {
this(numPlayers, maxTries, 1000);
}
public Game(int numPlayers, int maxTries, int topNum) {
MAX_Tries = maxTries;
TOP_Num = topNum;
this.numPlayers = numPlayers;
resetPlayers();
resetTheNumber();
}
/*
Inheritance Example 1
The following is a piece of inheritance. Whereas an array of Players whenever of the type
"Participants". Which is then resolved into the type "Human" and that is being inherited from
"Participants". And whenever Bots or Human players are joined, they will be joined within
the same array
*/
public void resetPlayers() {
players = new Human[numPlayers + numBots];
for (int i = 0; i < numPlayers; i++) {
players[i] = new Human(i + 1);
}
for (int i = numPlayers; i < (numBots + numPlayers); i++) {
players[i] = new Computer(i + 1, TOP_Num);
}
}
public void setNumPlayers(int numPlayers) {
this.numPlayers = numBots;
resetPlayers();
}
public void setBotPlayers(int numBots) {
this.numBots = numBots;
resetPlayers();
}
public int getMaxTries() {
return MAX_Tries;
}
public void setMaxTries(int maxTries) {
this.MAX_Tries = maxTries;
}
public int getTopNum() {
return TOP_Num;
}
public void setTopNum(int topNum) {
this.TOP_Num = topNum;
resetTheNumber();
resetPlayers();
}
private void resetTheNumber() {
num = rand.nextInt(TOP_Num);
}
public void start() {
resetPlayers();
System.out.println("Welcome to the Guess a Number Game!\n");
System.out.println("Guess a number between 0 and " + (TOP_Num - 1) + "!");
currentPlayer = players[0];
System.out.println("The num " + num);
/*
Polymorphism example.
Any object that can pore than one IS-A test is considered to be Polymorphic.
In this case we are setting up a condition in which any given player has
the ability to win, which is depicted from the "isCorrect()" Method.
*/
while (!gameWinner && currentPlayer.getNumTries() < MAX_Tries) {
for (int i = 0; i < players.length; i++) {
//currentPlayer = players[i];
players[i].guess();
if (isCorrect()) {
gameWinner = true;
printWinner();
break;
} else
printWrong();
}
if (!gameWinner) {
printTriesLeft();
}
}
if (!gameWinner)
printLoser();
}
public boolean isCorrect() {
return currentPlayer.getLastGuess() == num;
}
public void printWinner() {
if (currentPlayer instanceof Computer)
System.out.println("Sorry! The Bot " + currentPlayer.getPlayerNum() + " got the better of you, and guessed the number: [" + num + "] and won! Perhaps try again!");
else
System.out.println("GG Player " + currentPlayer.getPlayerNum() + "you guessed the Number [" + num + "] right in just " + currentPlayer.getNumTries() + " tries!");
}
public void printLoser() {
System.out.println("Too Sad! You didn't guess within " + MAX_Tries + " tries! Try again!");
}
public void printWrong() {
String word = "too high";
if ((Integer.compare(currentPlayer.getLastGuess(), num)) == -1)
word = "too low";
System.out.println("Nope! " + word + "!");
}
public void printTriesLeft() {
System.out.println(MAX_Tries - currentPlayer.getLastGuess() + " tries left!");
}
public void getNumPlayers() {
System.out.print("Enter number of Persons playing => ");
while (!input.hasNextInt()) {
input.nextLine();
System.out.println("Invalid input! It must be a number!");
System.out.print("Enter the number of Players => ");
}
numPlayers = input.nextInt();
System.out.print("Enter number of Bots! =>");
while (!input.hasNextInt()) {
input.nextLine();
System.out.println("Invalid input! It must be a number!");
System.out.print("Enter number of Bots! =>");
}
numBots = input.nextInt();
resetPlayers();
}
}
Participants class:
package fourfive;
import java.util.LinkedList;
public abstract class Participants extends Run {
protected int numTries;
protected int playerNum;
protected LinkedList<Integer> guesses;
abstract void guess();
public int getLastGuess(){
return guesses.peek();
}
public int getPlayerNum(){
return playerNum;
}
public int getNumTries(){
return guesses.size();
}
}
Now the Human class: (basically the human player)
package fourfive;
import java.util.LinkedList;
import java.util.Scanner;
public class Human extends Participants {
protected static Scanner input = new Scanner(System.in);
public Human(int playerNum) {
numTries = 0;
this.playerNum = playerNum;
guesses = new LinkedList<Integer>();
}
public void guess(){
System.out.print("Player " + playerNum + "guess =>");
while(!input.hasNextInt()){
input.nextLine();
System.out.println("Invalid input!");
System.out.print("Player " + playerNum + "guess =>");
}
guesses.push(input.nextInt());
}
}
And Last the Computer class:
package fourfive;
import java.util.Random;
public class Computer extends Human {
protected static Random rand = new Random();
protected int maxGuess;
Computer(int playerNum) {
super(playerNum);
maxGuess = 1000;
}
Computer(int playerNum, int topNum){
super(playerNum);
maxGuess = topNum;
}
#Override
public void guess() {
int guess = rand.nextInt(maxGuess);
System.out.println("Bot " + playerNum + " turn *" + guess + "*");
guesses.push(guess);
}
public int getMaxGuess() {
return maxGuess;
}
public void setMaxGuess(int num) {
maxGuess = num;
}
}
You would initialize the Array with a fixed size, e.g. 4 and resize if needed. For this, you need an extra attribute to store the fill level of the array.
int[] guesses = new int[4];
int guessFilling = 0;
[...]
#Override
public void guess() {
int guess = rand.nextInt(maxGuess);
System.out.println("Bot " + playerNum + " turn *" + guess + "*");
if (guessFilling == guesses.length) {
resizeGuesses();
}
guesses[guessFilling++] = guess;
}
private void resizeGuesses() {
int[] newGuesses = new int[guesses.length > 0 ? 2 * guesses.length : 1];
System.arraycopy(guesses, 0, newGuesses, 0, guesses.length);
guesses = newGuesses;
}

Error: method in class cannot be applied to given type

I'm getting this error message for my getYear, getMake, and getModel methods within my class car, because apparently they aren't being passed arguments. It appears to me that they are being passed arguments, but I'm still in a beginner in Java, so I'm not sure where I messed up.
public class NextCar {
public static final void main(String args[]) {
//Creates objects from Car class
Car c = new Car ();
Car c1 = new Car ();
Car c2 = new Car ();
Car c3 = new Car ();
//First object
//Prints mileage
c.start();
c.moveForward(6);
c.moveBackward(2);
c.moveForward(4);
System.out.println ("The car went " + c.mileage() + " miles.");
//Second object
//Prints year of car
c1.getYear(2050);
System.out.println("The year of the car is " + c1.getYear());
//Third object
//Prints year and make of car
c2.getYear(2055);
c2.getMake("Google");
System.out.println("The year of the car is " + c2.getYear() + " and the make is " + c2.getMake());
//Fourth object
//Prints year, make, and model of car
c3.getYear(2060);
c3.getMake("Google");
c3.getModel("Smart");
System.out.println("The year of the car is " + c3.getYear() + " and the make is " +
c3.getMake() + " and the model is " + c3.getModel());
}
}
//creates Car class
class Car {
public int year = 0;
public String make = "";
public String model = "";
public int miles = 0;
public boolean power = false;
public void start() {
power = true;
}
public void moveForward(int mf) {
if (power == true) {
miles += mf;
}
}
public void moveBackward(int mb) {
if (power == true) {
miles -= mb;
}
}
public int mileage() {
return miles;
}
public int getYear(int y) {
year = y;
return year;
}
public String getMake(String ma) {
make = ma;
return make;
}
public String getModel(String mo) {
model = mo;
return mo;
}
}
Your Car class getYear method takes an integer input:
public int getYear(int y)
but you call it few times without providing an input
System.out.println("The year of the car is " + c1.getYear());
System.out.println("The year of the car is " + c2.getYear() + " and the make is " + c2.getMake());
System.out.println("The year of the car is " + c3.getYear() + " and the make is " +
thats the reason for your errors.
You probably want two methods getYear(to get the year value) and setYear (to set the year value) but you have defined only one. Probably this is what you need:
public void setYear(int y) {
year = y;
}
public int getYear() {
return year;
}
Furthermore look here:
c1.getYear(2050);
System.out.println("The year of the car is " + c1.getYear());
the getYear return a value. so you could do
int year = c1.getYear(2050);
System.out.println("The year of the car is " + year);
Similar for the others. Or as Juned said, use appropiate getters/setters

Categories

Resources