Create different classes, a CarDemo class and a Car class - java

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.

Related

How can I display the output of the parameters I have set from a child class?

I need help accessing the variables I have inputted using the child class. I made an object for the child class in my main class, however, I do not know how will I have access to the inputs I have entered and display them at the end of the code.
public abstract class player {
public abstract String name(String name);
public abstract void race(int race);
public abstract int[] getStatArray();
}
import java.util.Scanner;
public class childplayer extends player {
Scanner sc = new Scanner(System.in);
public String name(String name) {
System.out.print("Enter your name: ");
name = sc.nextLine();
return name;
}
public void race(int race) {
System.out.println("Race options: ");
System.out.println("\t 1 - Human \n\t 2 - Elf \n\t 3 - Orc \n\t 4 - Angel \n\t 5 - Demon");
System.out.print("Enter character's race: ");
race = sc.nextInt();
if((race>5)||(race<1)) {
while ((race>5)||(race<1)) {
System.out.print("Enter character's race: ");
race = sc.nextInt();
}
}System.out.println(" ");
}
public int[] getStatArray(){
int [] stat = new int [3];
int x = 0, y = 0, pts = 0;
System.out.println("Enter character's stats.");
while(y<3) {
System.out.print("Enter value: ");
x = sc.nextInt();
y++;
pts = pts + x;
}
int i = 0;
if(pts>10) {
System.out.println("Invalid input. Try again.");
while(i<3) {
System.out.print("Enter value: ");
x = sc.nextInt();
i++;
pts = pts + x;
}
}else {
stat[i] = x;
i++;
}
return stat;
}
}
If you want to keep the values to use later then you need to store them. The best way to do this is simply with a class variable like so:
public class Childplayer extends Player {
//Create class variables that store the values
String name = "";
int race = -1;
int[] stat = new int [3];
Then we just modify your methods to use these variables, for example:
public String name(String name) {
//Process the name
if(someCondition){
name = name +" Smith"
}
//Saved the passed in variable to the class variable `this.name`
this.name = name;
return this.name;
}
And another example:
public void race(int race) {
//Saved the passed in variable to the class variable `this.race`
this.race = race:
}
Then to get the information later we simply use:
//Earlier in the code
Childplayer playerA = new Childplayer();
//Some code here
//...
//Later in the code we can get the values
String name = playerA.name;
int storedRaceFromEarlier = playerA.race;
I strongly recommend making use of a constructor method to populate the class data. I have simplified the code and value checking for the sake of this example:
//Note that Java naming conventions require that classes should always have a capital letter at the start, I have fixed this in my example
public abstract class Player {
//Example getter abstract methods that must be implimented
public abstract String getName();
public abstract int getRace();
public abstract int[] getStatArray();
}
//Note that Java naming conventions require that classes should always have a capital letter at the start, I have fixed this in my example
public class Childplayer extends Player {
Scanner sc = new Scanner(System.in);
//Create class variables that store the values
String name = "";
int race = -1;
int[] stat = new int [3];
//Constructor method with exactly the same name as the class "Childplayer"
//This method should be responsible for creating the object and populating data
Childplayer(){
//Set name
System.out.print("Enter your name: ");
name(sc.nextLine());
System.out.print("Name set as " + name + "\r\n");
//Set race
System.out.println("Race options: ");
System.out.println("\t 1 - Human \n\t 2 - Elf \n\t 3 - Orc \n\t 4 - Angel \n\t 5 - Demon");
int result = -1;
while ((result>5)||(result<1)) {
System.out.print("Enter character's race: ");
result = sc.nextInt();
}
//Set the race with the abstract method
race(result);
System.out.print("Race set as " + race + "\r\n");
System.out.println("Enter character's stats.");
int i = 0;
while(i<3) {
System.out.print("Enter stat value: ");
//Save the stat to the class variable
stat[i] = sc.nextInt();
i++;
}
}
//Abstract methods implemented to return the correct values
public String getName(){
return name;
}
public int getRace(){
return race;
}
public int[] getStatArray(){
return stat;
}
}

Java passing class array into array

I am a student and looking for help with an assignment. Here is the task: Create a CollegeCourse class. The class contains fields for the course ID (for example, “CIS 210”), credit hours (for example, 3), and a letter grade (for example, ‘A’).
Include get() and set()methods for each field. Create a Student class containing an ID number and an array of five CollegeCourse objects. Create a get() and set() method for the Student ID number. Also create a get() method that returns one of the Student’s CollegeCourses; the method takes an integer argument and returns the CollegeCourse in that position (0 through 4). Next, create a set() method that sets the value of one of the Student’s CollegeCourses; the method takes two arguments—a CollegeCourse and an integer representing the CollegeCourse’s position (0 through 4).
I am getting runtime errors on the second for loop where I am trying to get the data into the course array. It is asking for both the CourseID and Hours in the same line and regardless of what I respond with it I am getting an error, it almost seems like it is trying to get all the arrays variables at the same time. Here is my code which includes three classes. Any help to send me in the right direction is appreciated as I have spent a ton of time already researching to resolve.
public class CollegeCourse {
private String courseId;
private int creditHours;
private char grade;
public CollegeCourse(String id, int hours, char grade)
{
courseId=id;
creditHours = hours;
this.grade = grade;
}
public void setCourseId(String id)
{
courseId = id;//Assign course id to local variable
}
public String getCourseId()
{
return courseId;//Provide access to course id
}
public void setHours(int hours)
{
creditHours = hours;//Assign course id to local variable
}
public int getHours()
{
return creditHours;//Provide access to course id
}
public void setGrade(char grade)
{
this.grade = grade;//Assign course id to local variable
}
public char getGrade()
{
return grade;//Provide access to course id
}
}
Student Class
public class Student {
final int NUM_COURSES = 5;
private int studentId;
private CollegeCourse courseAdd;//Declares a course object
private CollegeCourse[] courses = new CollegeCourse[NUM_COURSES];
//constructor using user input
public Student(int studentId)
{
this.studentId=studentId;
}
public void setStudentId(int id)
{
studentId = id;//Assign course id to local variable
}
public int getStudentId()
{
return studentId;//Provide access to course id
}
public void setCourse(int index, CollegeCourse course)
{
courses[index] = course;
}
public CollegeCourse getCourse(int index)
{
return courses[index];
//do I need code to return the courseId hours, grade
}
}
InputGrades Class
import java.util.Scanner;
public class InputGrades {
public static void main(String[] args) {
final int NUM_STUDENTS = 2;
final int NUM_COURSES = 3;
Student[] students = new Student[NUM_STUDENTS];
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
//String gradeInput;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + (s+1) + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
csIndex=c;
System.out.print("Enter course ID #" + (c+1) + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
System.out.println();
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}
After input.nextInt() you need to add one more input.nextLine(); and than you can read grade.
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
Why it is needed? See this question: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
You should add a very simple length validation when you input the grade:
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
so the full main class code:
import java.util.Scanner;
/**
* Created by dkis on 2016.10.22..
*/
public class App {
public static void main(String[] args) {
final int NUM_STUDENTS = 10;
final int NUM_COURSES = 5;
Student[] students = new Student[NUM_STUDENTS];
//String name;
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + s+1 + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
//CollegeCourse course = students[s].getCourse(c);
csIndex=c;
System.out.print("Enter course ID#" + c+1 + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}

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

How do you call a scanner variable from main into another method?

public static void main(String[] args) {
//Scanner declaration and other stuff
//...
System.out.println("Enter price in $ (0.00 to 1000.00)");
int price1 = scan.nextInt();
scan.nextLine();
System.out.println("Enter user rating (0 to 5)");
int userRating1 = scan.nextInt();
scan.nextLine();
System.out.println("Enter price in $ (0.00 to 1000.00)");
int price2 = scan.nextInt();
scan.nextLine();
System.out.println("Enter user rating (0 to 5)");
int userRating2 = scan.nextInt();
scan.nextLine();
}
public static void compare(camera camOne, camera camTwo) {
int value1 = camOne.computeValue();
int value2 = camTwo.computeValue();
/*
* if(camOne.computeValue() == camTwo.computeValue() && userRating1 ==
* userRating2)
*/
}
How would I be able to call the price or the userRating inputs into the compare method, where I would like to compare the values?
You wouldn't use Scanner inside of the compare method. You're comparing two camera objects (which should be renamed Camera), and the Camera objects that you wish to compare should be fully formed before entering the method, and so there should be no need to use a Scanner inside the method.
public static void main(String[] args) {
//Scanner declaration and other stuff
//...
System.out.println("Enter price in $ (0.00 to 1000.00)");
int price1 = scan.nextInt();
scan.nextLine();
System.out.println("Enter user rating (0 to 5)");
int userRating1 = scan.nextInt();
scan.nextLine();
System.out.println("Enter price in $ (0.00 to 1000.00)");
int price2 = scan.nextInt();
scan.nextLine();
System.out.println("Enter user rating (0 to 5)");
int userRating2 = scan.nextInt();
scan.nextLine();
// not sure what constructor Camera has
Camera camera1 = new Camera(....);
Camera camera2 = new Camera(....);
int result = compare(camera1, camera2);
System.out.println("Result is: " + result);
}
// shouldn't this return an int? also camera should be renamed Camera
public static int compare(Camera camOne, Camera camTwo) {
int value1 = camOne.computeValue();
int value2 = camTwo.computeValue();
/*
* if(camOne.computeValue() == camTwo.computeValue() && userRating1 ==
* userRating2)
*/
int result = Integer.compare(value1, value2);
return result; // 0 for the same, 1 for first one > second, -1 for opposite
}
Also, you ask:
How would I be able to call the price or the userRating inputs into the compare method, where I would like to compare the values?
Assuming that your Camera class (again, rename it from "camera" to "Camera" to comply with Java naming conventions) has both a getPrice() and a getUserRating() method, then you'd call those methods on your camOne and camTwo Camera parameters inside of the compare(...) method. If you need to compare doubles, I suggest that you use the Double.compare(double d1, double d2) method, and if you need to compare ints, then use the Integer.compare(int i1, int i2) method.
For example, using a Comparator,
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class TestCamera {
public static void main(String[] args) {
ArrayList<MyCamera> cameraList = new ArrayList<>();
// We'll pretent to use Scanner here to get values
cameraList.add(new MyCamera("Sony", 8, 250.00));
cameraList.add(new MyCamera("Olympus", 7, 450.0));
cameraList.add(new MyCamera("Nikon", 10, 400.0));
cameraList.add(new MyCamera("Fuji", 7, 450.50));
System.out.println("Pre-sorted list:");
for (MyCamera myCamera : cameraList) {
System.out.println(myCamera);
}
System.out.println();
System.out.println("Post-sorted list:");
Collections.sort(cameraList, new MyCameraComparator(false));
for (MyCamera myCamera : cameraList) {
System.out.println(myCamera);
}
}
}
class MyCamera {
private int rating;
private double cost;
private String name;
public MyCamera(String name, int rating, double cost) {
this.name = name;
this.rating = rating;
this.cost = cost;
}
public String getName() {
return name;
}
public int getRating() {
return rating;
}
public double getCost() {
return cost;
}
#Override
public String toString() {
return "MyCamera [rating=" + rating + ", cost=" + cost + ", name=" + name
+ "]";
}
}
class MyCameraComparator implements Comparator<MyCamera> {
private boolean lowestToHighest = true;
public MyCameraComparator() {
// default constructor
}
public MyCameraComparator(boolean lowestToHighest) {
this.lowestToHighest = lowestToHighest;
}
#Override
public int compare(MyCamera cam1, MyCamera cam2) {
int finalResult = 0;
int ratingValue = Integer.compare(cam1.getRating(), cam2.getRating());
if (ratingValue != 0) {
finalResult = ratingValue;
} else {
finalResult = Double.compare(cam1.getCost(), cam2.getCost());
}
if (lowestToHighest) {
return finalResult;
} else {
return -finalResult;
}
}
}

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

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

Categories

Resources