setters and getters in java - java

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

Related

Searching for a String in an ArrayList of Objects

I have been trying to figure this out for hours and I have had no luck doing so,
I'm trying to iterate over my Arraylist<Booking> which utilizes my Booking class file and trying to understand how I'm able to search it for the matching, case-insensitive term.
this is my current method:
private void searchBookings() {
if (bookings.size() <= 0) {
JOptionPane.showMessageDialog(null, "There are no bookings.", "Search Bookings", 3);
} else {
String searchTerm = JOptionPane.showInputDialog(null, "Please input search term: ", "Search Bookings", 3);
for (int i = 0; i < bookings.size(); i++) {
while (!bookings.get(i).getStudent().getName().equalsIgnoreCase(searchTerm)) {
i++;
if (bookings.get(i).getStudent().getName().equalsIgnoreCase(searchTerm)) {
String output = String.format("%-30s%-18s%-18b$%-11.2f\n", bookings.get(i).getStudent(), bookings.get(i).getLessons(), bookings.get(i).isPurchaseGuitar(), bookings.get(i).calculateCharge());
this.taDisplay.setText(heading + "\n" + output + "\n");
}
}
}
}
JOptionPane.showMessageDialog(null, "There is no booking with that name.", "Search Bookings", 3);
}
I know it's messy but, just trying to make do.
I am trying to retrieve the name of the booking as I am searching by name as well as provide an error message if that names does not exist, to do that I must
use bookings.getStudent().getName() I have had some luck as I can return the value but now I am not able to provide my error message if I do not find it. Any help is appreciated.
package com.mycompany.mavenproject1;
public class Booking {
private Student student;
private int lessons;
private boolean purchaseGuitar;
// CONSTANTS
final int firstDiscountStep = 6;
final int secondDiscountStep = 10;
final int tenPercentDiscount = 10;
final int twentyPercentDiscount = 5;
final double LESSON_COST = 29.95;
final double GUITAR_COST = 199.00;
double LESSON_CHARGE = 0;
final int MINIUMUM_LESSONS = 1;
public Booking() {
}
public Booking(Student student, int lessons, boolean purchaseGuitar) {
this.student = new Student(student.getName(), student.getPhoneNumber(), student.getStudentID());
this.lessons = lessons;
this.purchaseGuitar = purchaseGuitar;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public int getLessons() {
return lessons;
}
public void setLessons(int lessons) {
this.lessons = lessons;
}
public boolean isPurchaseGuitar() {
return purchaseGuitar;
}
public void setPurchaseGuitar(boolean purchaseGuitar) {
this.purchaseGuitar = purchaseGuitar;
}
public double calculateCharge() {
double tempCharge;
if (lessons < firstDiscountStep) {
LESSON_CHARGE = (lessons * LESSON_COST );
} else if (lessons < secondDiscountStep) {
tempCharge = (lessons * LESSON_COST) / tenPercentDiscount;
LESSON_CHARGE = (lessons * LESSON_COST) - tempCharge;
} else {
tempCharge = (lessons * LESSON_COST) / twentyPercentDiscount;
LESSON_CHARGE = (lessons * LESSON_COST) - tempCharge;
}
if (isPurchaseGuitar()) {
LESSON_CHARGE += GUITAR_COST;
}
return LESSON_CHARGE;
}
#Override
public String toString() {
return student + ","+ lessons + "," + purchaseGuitar +"," + LESSON_COST;
}
}
If I understood you correctly, you are searching for a given student name in your collection of bookings. And if it is present, set a formatted text.
First of all, use a for-each loop, because you don't use the index.
Secondly, return from the for-each loop, when you found your student.
private void searchBookings() {
if (bookings.size() <= 0) {
JOptionPane.showMessageDialog(null, "There are no bookings.", "Search Bookings", 3);
} else {
String searchTerm = JOptionPane.showInputDialog(null, "Please input search term: ", "Search Bookings", 3);
for (final Booking booking : bookings) // for-each
{
if (booking.getStudent().getName().equalsIgnoreCase(searchTerm))
{
String output = booking.getFormattedOutput();
this.taDisplay.setText(heading + "\n" + output + "\n");
return; // break out of the loop and method and don't display dialog message
}
}
}
JOptionPane.showMessageDialog(null, "There is no booking with that name.", "Search Bookings", 3);
}
Then there are multiple other things, which you could improve.
Don't get all the data from a booking just to format it externally. Let the Booking class handle the formatting and return you the string you desire. (move the formatting in a function inside the Booking class)
Instead of recreating a Student you receive in your Booking constructor, make the Student class immutable, and then you can just reuse the object provided.
Try also making the Booking class immutable. You provided some setters, but do you really want to change the student in a booking? Or would you rather create a new booking for the other student?
The calculteCharge method could be stateless. Just get the LESSON_CHARGE value and hold it in a local variable. Your method would also get threading-proof.
Make your constants final and better yet make them members of the class (by adding the static modifier) instead of every member.
Lastly, representing a money amount with a floating (double is better but not good either) number, you will run into funny situations. Try this calculation: 0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1 for example.
One way would be to create a Money class which holds the value in cents as an integer. And when you want to display the amount you can divide it by 100 and format it accordingly. That way, you can also restrict it become negative.
PS: Sometimes we desperately try to find a solution that we don't give ourselves some rest. After a little break, you might recognize the problem. Oh and try debugging with breakpoints. Or this, if you use IntelliJ IDEA (which I would highly recommend, the community edition is free).
You're re-incrementing your counter variable, which is really not going to help. Try the following:
private void searchBookings() {
if (bookings.size() <= 0) {
JOptionPane.showMessageDialog(null, "There are no bookings.", "Search Bookings", 3);
} else {
String searchTerm = JOptionPane.showInputDialog(null, "Please input search term: ", "Search Bookings", 3);
boolean studentFound = false;
for (int i = 0; i < bookings.size(); i++) {
if (bookings.get(i).getStudent().getName().equalsIgnoreCase(searchTerm)) {
String output = String.format("%-30s%-18s%-18b$%-11.2f\n", bookings.get(i).getStudent(),
bookings.get(i).getLessons(), bookings.get(i).isPurchaseGuitar(),
bookings.get(i).calculateCharge());
this.taDisplay.setText(heading + "\n" + output + "\n");
studentFound = true;
break;
}
}
}
if (!studentFound) {
JOptionPane.showMessageDialog(null, "There is no booking with that name.", "Search Bookings", 3);
}
}

How would I write a toString and reduce duplicate outputs?

So, I've created a simple app for moving a bug along a wire. The code works well (for the most part) though, I am having a few issues.
When reaching the end of the wire, the program terminates all well and good but I'm getting a double output that it's fallen off the wire when it reaches the end.
I am supposed to be writing a toString for this, but am having a bit of a hard time grasping why and how I should go about doing this.
If someone could assist with this, I'd greatly appreciate it.
import java.util.Scanner;
public class ClassPracticeMain {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
int userInput;
Bug bug1 = new Bug();
bug1.setInitialPosition();
bug1.setInitialDirection();
System.out.println("Your starting position is " + bug1.initialPosition
+ " and you are facing " + bug1.getCurrentDirection()
);
while (bug1.getExit(1) != 0) {
System.out.println("Which way would you like to move? 1 for left/ 2 for right or 0 for exit");
userInput = input.nextInt();
bug1.move(userInput);
bug1.getCurrentDirection();
bug1.getCurrentPosition();
System.out.println("You are now at " + bug1.currentPosition + " and you are facing " + bug1.getCurrentDirection());
bug1.getExit(userInput);
}
}
}
public class Bug {
final int WIRELEFTEND=-15;
final int WIRERIGHTEND=15;
int initialPosition=0, currentPosition=0, direction,exit=1;
String currentDirection;
String left = "left";
String right = "right";
public int setInitialPosition(){
return initialPosition;
}
public int setInitialDirection(){
direction=1;
return direction;
}
public int getCurrentPosition(){
return currentPosition;
}
public String getCurrentDirection(){
if (direction== 1){
currentDirection=left;
} else if (direction == 2){
currentDirection=right;
}
return currentDirection;
}
public int move(int move){
if(move==1 && direction==1){
currentPosition=currentPosition-1;
return currentPosition;
} else if (move==1 && direction==2){
direction=1;
return currentPosition;
} else if (move==2 && direction==1){
direction=2;
return currentPosition;
} else if (move==2 && direction ==2){
currentPosition=currentPosition+1;
return currentPosition;
}
return 0;
}
public int getExit(int exit){
if(currentPosition<(WIRELEFTEND)||currentPosition>WIRERIGHTEND){
System.out.println("You've fallen off the wire... Oh no!");
exit=0;
} else{
exit=exit;
}
return 1;
}
}
You probably want to write
public int getExitStatus(){
if(currentPosition<(WIRELEFTEND)||currentPosition>WIRERIGHTEND){
System.out.println("You've fallen off the wire... Oh no!");
return 0;
}
return 1;
}
instead of your current getExist(int) function. It always returns 1, and setting the exit argument doesn't do anything.

Printing out most expensive boat and it's information from an array

I am working on a boat program that has a super class (Boat) and two subclasses (SailBoat, Powerboat) and I must print out all of the boats information and price as well as the most expensive boat and it's information alone. This is the part I am having trouble with since I am not entirely sure how to go about it. Here is what I have so far...
Boat Class:
public class Boat {
String color;
int length;
public Boat() {
color = "white";
length = 20;
}
public Boat(String col, int leng) {
color = col;
length = leng;
}
public boolean setColor(String col) {
if ("white".equals(col) || "red".equals(col) || "blue".equals(col) || "yellow".equals(col)) {
col = color;
return true;
} else {
System.out.println("Error: can only be white, red, blue or yellow");
return false;
}
}
public String getColor() {
return color;
}
public boolean setLength(int leng) {
if (leng < 20 || leng > 50) {
leng = length;
System.out.println("Sail Boats can only be between 20 and 50 feet, inclusively.");
return false;
} else {
return true;
}
}
public int getLength() {
return length;
}
public String toString() {
String string;
string = String.format("Color = " + color + " Length = " + length);
return string;
}
public int calcPrice() {
int price;
price = 5000 + length;
return price;
}
}
PowerBoat Subclass
import java.text.NumberFormat;
public class PowerBoat extends Boat {
int engineSize;
public PowerBoat() {
super();
engineSize = 5;
}
public PowerBoat(String col, int len, int esize) {
this.color = col;
this.length = len;
engineSize = esize;
}
public boolean setEngineSize(int esize) {
if (esize < 5 || esize > 350) {
System.out.println(
"Error: That engine is too powerful. The engine size must be between 1 and 350, inclusively");
esize = engineSize;
return false;
} else {
return true;
}
}
public int calcPrice() {
int price;
price = 5000 + length * 300 + engineSize * 20;
return price;
}
public String toString() {
NumberFormat nf = NumberFormat.getCurrencyInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
return super.toString() + " Engine Size = " + engineSize + " Price = " + nf.format(calcPrice());
}
}
SailBoat subclass
import java.text.NumberFormat;
public class SailBoat extends Boat {
int numSails;
public SailBoat() {
numSails = 0;
}
public SailBoat(String col, int leng, int numsail) {
color = col;
length = leng;
numSails = numsail;
}
public boolean setNumSails(int nsails) {
if (nsails < 1 || nsails > 4) {
nsails = numSails;
return false;
} else {
return true;
}
} // end setNumSails
public int getNumSails() {
return numSails;
}
public int calcPrice() {
int price;
price = length * 1000 + numSails * 2000;
return price;
}
public String toString() {
NumberFormat nf = NumberFormat.getCurrencyInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
return super.toString() + "Color: " + color + " Length: " + length + " Number Sails = " + numSails + " Cost = "
+ nf.format(calcPrice());
}
public int getTotalCost() {
int totalCost = 0;
totalCost += calcPrice();
return totalCost;
}
}
Inventory class (tester)
import java.util.ArrayList;
public class Inventory {
public static void main(String[] args) {
// boat objects
Boat pb1 = new PowerBoat("blue", 22, 60);
Boat sb1 = new SailBoat("white", 20, 1);
Boat sb2 = new SailBoat("red", 42, 3);
Boat pb2 = new PowerBoat("yellow", 35, 80);
Boat pb3 = new PowerBoat("red", 50, 120);
Boat sb3 = new SailBoat("blue", 33, 2);
Boat pb4 = new PowerBoat("white", 20, 10);
ArrayList<Boat> AL = new ArrayList<Boat>();
// add boat objects to arraylist
AL.add(pb1);
AL.add(sb1);
AL.add(sb2);
AL.add(pb2);
AL.add(pb3);
AL.add(sb3);
AL.add(pb4);
// print all boat objects
System.out.println("Print all boats");
for (Boat anyBoat : AL) {
System.out.println(anyBoat.toString());
}
int max = 0;
int totalcost = 0;
Boat mostExpensiveBoat = null;
for (Boat anyBoat : AL) {
if (anyBoat instanceof SailBoat) {
totalcost += anyBoat.calcPrice();
if (anyBoat.calcPrice() > max) {
max = anyBoat.calcPrice();
mostExpensiveBoat = anyBoat;
}
}
}
}
}
I am really confused on how to finish up this program, the results I am supposed to get after all the boat information is printed is this..
Total price of all boats is $ 170,500.00
Most Expensive Boat: Color = red Length = 42 Number Sails = 3 Cost = $ 48,000.00
Any help will be greatly appreciated. Thank you.
There are a few design flaws you should correct:
Your Boat class should be an interface or abstract. You can't have a boat that isn't a power boat or sail boat so you should not be able to instantiate one.
Your instance variables should be private.
Make methods abstract that need to be defined by subclasses of Boat (e.g. calcPrice).
If you are able to use Java 8 then there's a nice way of getting the most expensive boat. The following code will print the most expensive boat (using Boat.toString) if one is present.
allBoats.stream()
.max(Comparator.comparingInt(Boat::calcPrince))
.ifPresent(System.out::println);
That avoids having to write the code that manually iterates through your list comparing prices. It also copes with the situation of an empty list (which means there is no maximum). Otherwise you need to initialise to null and compare to null before printing.
Your for loop should look like this:
for (Boat anyBoat : AL) {
totalcost += anyBoat.calcPrice();
if (anyBoat.calcPrice() > max) {
max = anyBoat.calcPrice();
mostExpensiveBoat = anyBoat;
}
}
It doesn't matter if it's a sailBoat or not, you just wanna print the information of the most expensive one, so you can remove the instanceof condition. After that:
NumberFormat nf = NumberFormat.getCurrencyInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
System.out.println("Total price of all boats is " + nf.format(totalcost));
System.out.println("Most expensive boat: " + mostExpensiveBoat.toString());
Should work, since you have already overriden the toString() methods.
one more thing: In your SailBoat toString() method, you are doing:
return super.toString() + "Color: " + color + " Length: " + length + " Number Sails = " + numSails + " Cost = "
+ nf.format(calcPrice());
When you call the super.toString() you are printing the color and the length twice; just call
return super.toString() + " Number Sails = " + numSails + " Cost = " + nf.format(calcPrice());

How to compare parameter values of two objects in Java?

Right now I'm working on a method for comparing the scores of athletes in the olympics. So far I've had little trouble, however now I've reached a point where i need to compare two objects (athletes) scores and I'm not sure how to do it. This is my code for the Olympic class:
// A program using the Athlete class
public class Olympics {
public static void main(String args[]) {
System.out.println("The leader is " + Athlete.leader() +
", with a score of " + Athlete.leadingScore());
Athlete meryl = new Athlete("Meryl Davis", "U.S.");
meryl.addScore(75);
System.out.println(meryl);
Athlete tessa = new Athlete("Tessa Virtue", "Canada");
System.out.println(tessa);
System.out.println(); // blank line
tessa.addScore(50);
System.out.println(tessa);
System.out.println(meryl);
System.out.println("The leader is " + Athlete.leader() +
", with a score of " + Athlete.leadingScore());
System.out.println(); // blank line
tessa.addScore(100);
meryl.addScore(65);
System.out.println(tessa);
System.out.println(meryl);
System.out.println("The leader is " + Athlete.leader() +
", with a score of " + Athlete.leadingScore());
System.out.println(); // blank line
tessa.addScore(20);
System.out.println("Tessa's final score is " + tessa.getScore());
meryl.move("France");
System.out.println(meryl);
} // end main
} // end class Olympics
And this is the constructor class "Athlete":
public class Athlete {
private String name;
private String country;
protected int score;
public static int leadScore;
public Athlete(String athName, String athCountry) {
this.name = athName;
this.country = athCountry;
score = 0;
if (score < 1) {
System.out.println("Score cannot be lower than 1");
}
}
public int addScore(int athScore) {
score += athScore;
return score;
}
public static String leader(){
//TODO
}
public static int leadingScore() {
//MUST COMPARE BOTH ATHLETES
}
public int getScore(){
return score;
}
public void move(String newCountry) {
country = newCountry;
}
public String toString() {
return name + ": " + "from " + country + ", current score " + score;
}
}
So what I'm trying to do is have the program check Meryl's score compared to Tessa's and return that Athlete's score in leadingScore() and, using that athlete, return a leader(). Any help is appreciated! Thanks.
The function must take the two Athletes you're comparing as the parameters for this to work
public static int leadingScore(Athlete a1, Athlete a2) {
if (a1.getScore() < a2.getScore()) {
// do stuff
}
}
The lead score should not be in the athlete class, but rather in main () because one instance of an Athlete class would not know of other instances unless you put a self-referential list inside the class. Similarly, leadingScore should be in main ().
It or main can call each athlete and compare:
int merylScore = meryl.getScore ();
int tessaScore = tessa.getScore ();
int leadingScore = 0;
String leaderName = "";
if (merylScore > tessaScore) {
leadingScore = merylScore;
leaderName = meryl.getName ();
} else if (tessaScore > merylScore) {
leadingScore = tessaScore;
leaderName = tessa.getName ();
} else {
leadingScore = merylScore;
leaderName = "a tie between Meryl and Tessa";
}
System.out.println ("The leader is " + leaderName + ", with a score of " + leadingScore);
You should consider using a "collection". Use an array, a list ... or even a sorted list.
Stored your individual objects in the collection, then traverse the collection to find the highest score.
For example:
// Create athlete objects; add each to list
ArrayList<Athlete> athletes = new ArrayList<Athlete>();
Athlete meryl = new Athlete("Meryl Davis", "U.S.");
meryl.addScore(75);
...
athletes.add(meryl);
Athlete tessa = new Athlete("Tessa Virtue", "Canada");
...
athletes.add(tessa );
// Go through the list and find the high scorer
Athlete highScorer = ...;
for (Athlete a : athletes) {
if (highScorer.getScore() < a.getScore())
highScorer = a;
...
}
System.out.println("High score=" + highScorer.getScore());
Here's a good tutorial:
http://www.vogella.com/tutorials/JavaCollections/article.html

Infinite while loop in java, not reading in sentinel

I've had this problem throughout multiple programs, but I can't remember how I fixed it last time. In the second while loop in my body, the second sentinel value is never read in for some reason. I've been trying to fix it for a while now, thought I might see if anyone had any clue.
import java.text.DecimalFormat; // imports the decimal format
public class Car {
// Makes three instance variables.
private String make;
private int year;
private double price;
// Makes the an object that formats doubles.
public static DecimalFormat twoDecPl = new DecimalFormat("$0.00");
// Constructor that assigns the instance variables
// to the values that the user made.
public Car(String carMake,int carYear, double carPrice)
{
make = carMake;
year = carYear;
price = carPrice;
}
// Retrieves variable make.
public String getMake()
{
return make;
}
// Retrieves variable year.
public int getYear()
{
return year;
}
// Retrieves variable price.
public double getPrice()
{
return price;
}
// Checks if two objects are equal.
public boolean equals(Car c1, Car c2)
{
boolean b = false;
if(c1.getMake().equals(c2.getMake()) && c1.getPrice() == c2.getPrice() &&
c1.getYear() == c2.getYear())
{
b = true;
return b;
}
else
{
return b;
}
}
// Turns the object into a readable string.
public String toString()
{
return "Description of car:" +
"\n Make : " + make +
"\n Year : " + year +
"\n Price: " + twoDecPl.format(price);
}
}
import java.util.Scanner; // imports a scanner
public class CarSearch {
public static void main(String[] args)
{
// initializes all variables
Scanner scan = new Scanner(System.in);
final int SIZE_ARR = 30;
Car[] carArr = new Car[SIZE_ARR];
final String SENT = "EndDatabase";
String carMake = "";
int carYear = 0;
double carPrice = 0;
int count = 0;
int pos = 0;
final String SECSENT = "EndSearchKeys";
final boolean DEBUG_SW = true;
// Loop that goes through the first list of values.
// It then stores the values in an array, then uses the
// values to make an object.
while(scan.hasNext())
{
if(scan.hasNext())
{
carMake = scan.next();
}
else
{
System.out.println("ERROR - not a String");
System.exit(0);
}
if(carMake.equals(SENT))
{
break;
}
if(scan.hasNextInt())
{
carYear = scan.nextInt();
}
else
{
System.out.println("ERROR - not an int" + count);
System.exit(0);
}
if(scan.hasNextDouble())
{
carPrice = scan.nextDouble();
}
else
{
System.out.println("ERROR - not a double");
System.exit(0);
}
Car car1 = new Car(carMake, carYear, carPrice);
carArr[count] = car1;
count++;
}
// Calls the method debugSwitch to show the debug information.
debugSwitch(carArr, DEBUG_SW, count);
// Calls the method printData to print the database.
printData(carArr, count);
// Loops through the second group of values and stores them in key.
// Then, it searches for a match in the database.
**while(scan.hasNext())**
{
if(scan.hasNext())
{
carMake = scan.next();
}
else
{
System.out.println("ERROR - not a String");
System.exit(0);
}
if(carMake.equals(SECSENT))
{
break;
}
if(scan.hasNextInt())
{
carYear = scan.nextInt();
}
else
{
System.out.println("ERROR - not an int" + count);
System.exit(0);
}
if(scan.hasNextDouble())
{
carPrice = scan.nextDouble();
}
else
{
System.out.println("ERROR - not a double");
System.exit(0);
}
Car key = new Car(carMake, carYear, carPrice);
// Stores the output of seqSearch in pos.
// If the debug switch is on, then it prints these statements.
if(DEBUG_SW == true)
{
System.out.println("Search, make = " + key.getMake());
System.out.println("Search, year = " + key.getYear());
System.out.println("Search, price = " + key.getPrice());
}
System.out.println("key =");
System.out.println(key);
pos = seqSearch(carArr, count, key);
if(pos != -1)
{
System.out.println("This vehicle was found at index = " + pos);
}
else
{
System.out.println("This vehicle was not found in the database.");
}
}
}
// This method prints the database of cars.
private static void printData(Car[] carArr, int count)
{
for(int i = 0; i < count; i++)
{
System.out.println("Description of car:");
System.out.println(carArr[i]);
}
}
// Searches for a match in the database.
private static int seqSearch(Car[] carArr, int count, Car key)
{
for(int i = 0; i < count; i++)
{
boolean b = key.equals(key, carArr[i]);
if(b == true)
{
return i;
}
}
return -1;
}
// Prints debug statements if DEBUG_SW is set to true.
public static void debugSwitch(Car[] carArr, boolean DEBUG_SW, int count)
{
if(DEBUG_SW == true)
{
for(int i = 0; i < count; i++)
{
System.out.println("DB make = " + carArr[i].getMake());
System.out.println("DB year = " + carArr[i].getYear());
System.out.println("DB price = " + carArr[i].getPrice());
}
}
}
}
I think this is your problem, but I might be wrong:
Inside your while loop, you have these calls:
next()
nextInt()
nextDouble()
The problem is that the last call (nextDouble), will not eat the newline. So to fix this issue, you should add an extra nextLine() call at the end of the two loops.
What happens is that the next time you call next(), it will return the newline, instead of the CarMake-thing.

Categories