Java code written but no expected output after running - java

This is a programming assignment I am working on. It takes a single string input that represents a sequence of transactions and prints total gain/loss in the end.
I have my code written and think it should do what I want...but doesn't. I don't get any kind of output after running the program with the specified input.
The input I'm using is:
buy 100 share(s) at $20 each;buy 20 share(s) at $24 each;buy 200
share(s) at $36 each;sell 150 share(s) at $30 each;buy 50 share(s) at
$25 each;sell 200 share(s) at $35 each;
import java.util.*;
import java.text.*;
public class Stocks {
private int shares;
private int price;
private int temp;
private static int total;
private int finalPrice;
private int finalShares;
private Queue<Stocks> StockList = new LinkedList<Stocks>();
private static NumberFormat nf = NumberFormat.getCurrencyInstance();
public Stocks()
{
shares = 0;
price = 0;
}
public Stocks(int shares, int price)
{
this.shares = shares;
this.price = price;
}
public int getShares()
{
return this.shares;
}
public int getPrice()
{
return this.price;
}
public void setShares(int shares)
{
this.shares = shares;
}
public void setPrice(int price)
{
this.price = price;
}
public void sell() {
int sharesToSell = this.getShares();
int priceToSell = this.getPrice();
while (!StockList.isEmpty()) {
int numShares = StockList.peek().getShares();
int sharePrice = StockList.peek().getPrice();
if (numShares < sharesToSell || numShares == sharesToSell) {
temp = sharesToSell - numShares; // remaining shares to sell
finalShares = sharesToSell - temp; // # shares selling at price
finalPrice = priceToSell - sharePrice; // shares sold at adjusted price
total += (finalPrice * finalShares); // Calculates total price
StockList.remove();
sharesToSell = temp; // Remaining shares needed to be sold # price
}
if (numShares > sharesToSell) {
temp = numShares - sharesToSell; // Remaining shares that were bought
finalPrice = priceToSell - sharePrice; // Shares sold at adjusted price
total += (finalPrice * sharesToSell); // adds to running total
StockList.peek().setShares(temp);
}
}
}
public void buy() {
int numShares = this.getShares();
int priceToBuy = this.getPrice();
Stocks newStock = new Stocks(numShares,priceToBuy);
StockList.add(newStock); // adds stock to list
int temptotal = (numShares * priceToBuy); // decreases running total
total += (-1 * temptotal);
}
public static int getTotal() { // gets total profit (or loss)
return total;
}
// *****MAIN METHOD*****
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter transaction sequence:");
String input = scan.nextLine().trim();
String[] inputArray = new String[50];
String[] inputArray2 = new String[50];
int numShares, sharePrice;
inputArray = input.split(";");
for (String i : inputArray) {
if (i.toUpperCase().contains("BUY")) {
inputArray2 = i.split(" ");
inputArray2[4] = inputArray2[4].substring(1);
try {
numShares = Integer.parseInt(inputArray2[1]);
sharePrice = Integer.parseInt(inputArray2[4]);
Stocks newStock = new Stocks(numShares,sharePrice);
newStock.buy();
} catch (NumberFormatException e) {
System.out.println("Error");
return;
}
}
else if (i.toUpperCase().contains("SELL")) {
inputArray2 = input.split(" ");
inputArray2[4] = inputArray2[4].substring(1);
try {
numShares = Integer.parseInt(inputArray2[1]);
sharePrice = Integer.parseInt(inputArray2[4]);
Stocks newStock = new Stocks(numShares,sharePrice);
newStock.sell();
} catch (NumberFormatException e) {
System.out.println("Error");
return;
}
} else {
System.out.println("Error - input does not contain buy/sell");
}
} System.out.println(nf.format(getTotal()));
}
}

You can clean up your parsing a lot by taking a look at java.util.regex.Matcher and java.util.regex.Pattern. They will let you match input against regular expressions. In addition, you can place parens in the regex to extract certain parts. So in your example, you really only care about three things: the operation(buy or sell), the quantity, and the price.
Here's a small example
String sentence = "john programs 10 times a day";
// here's our regex - each set of parens is a "group"
Pattern pattern = Pattern.compile("([A-Za-z]+) programs ([0-9]+) times a day");
Matcher matcher = pattern.matcher(sentence);
String person = matcher.group(1); // here we get the first group
String number = Integers.parseInt(matcher.group(2)); // here we get the second group
System.out.println("Person: " + person + " Number: " + number);

Looks like the main method is returning immediately when it parses a BUY transaction. You probably intended to put the return statement inside the catch block.

Related

Why does it display the value "null" if the conditions of the method are met?

I'm trying to compile my first major program. Unfortunately in getBestFare() I get "null" coming out all the time. And it shouldn't! I'm asking you guys for help what's wrong.
I rebuilt the entire getBestFare() method but unfortunately it keeps coming up with "null". The earlier code was a bit more messy. Now it's better, but it still doesn't work.
public class TransitCalculator {
public int numberOfDays;
public int transCount;
public TransitCalculator(int numberOfDays, int transCount) {
if(numberOfDays <= 30 && numberOfDays > 0 && transCount > 0){
this.numberOfDays = numberOfDays;
this.transCount = transCount;
} else {
System.out.println("Invalid data.");
}
}
String[] length = {"Pay-per-ride", "7-day", "30-day"};
double[] cost = {2.75, 33.00, 127.00};
public double unlimited7Price(){
int weekCount = numberOfDays/7;
if (numberOfDays%7>0){
weekCount+=1;
}
double weeksCost = weekCount * cost[1];
return weeksCost;
}
public double[] getRidePrices(){
double price1 = cost[0];
double price2 = ((cost[1]*unlimited7Price()) / (unlimited7Price() * 7));
double price3 = cost[2] / numberOfDays;
double[] getRide = {price1, price2, price3};
return getRide;
}
public String getBestFare(){
int num = 0;
for (int i = 0; i < getRidePrices().length; i++) {
if(getRidePrices()[i] < getRidePrices()[num]){
return "You should get the " + length[num] + " Unlimited option at " + getRidePrices()[num]/transCount + " per ride.";
}
}
return null;
}
public static void main(String[] args){
TransitCalculator one = new TransitCalculator(30, 30);
System.out.println(one.unlimited7Price());
System.out.println(one.getRidePrices()[2]);
System.out.println(one.getBestFare());
}
}

Search in Hashmap

Using for loop to compare the input value with the hashmap if it matches any value in the hash-map then the code prints all the related values with that time.
The result shows out for me NULL
System.out.println("Please enter time :");
Scanner scan = new Scanner(System.in);
String value = scan.nextLine();//Read input-time
Measurement measurement = measurements.get(value);//there can only be 1 Measurement for 1 time
if(measurement != null){
System.out.println(measurement);
}}
Class Measurement:
public void getTimeInfo(String value)
{
value = Measurements.get(time);
if (value == null) {
throw new MeasurementException();
}
System.out.println("The detailed info : " + this.time + "-" + this.temp+ " "+ this.wind+ "-" + this.humid );
}
}
}
Following the 3 steps (ignoring the Json part) u mentioned and reusing some of your code i can provide u this code:
Main.java:
public class Main {
static HashMap<String, Measurement> measurements = new HashMap();
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {//Create 3 measurements
String time = ""+i;
measurements.put(time, new Measurement(time, (float) i, (float) i, (float) i));
}
System.out.println("Please enter time :");
Scanner scan = new Scanner(System.in);
String value = scan.nextLine();//Read input-time
Measurement measurement = measurements.get(value);//there can only be 1 Measurement for 1 time
if(measurement != null){
System.out.println(measurement);
}
}
}
Measurement.java:
public class Measurement {
String time ;
Float temp;
Float wind;
Float humid;
int iD;
public Measurement(String d, Float t, Float w, Float h){
this.time = d;
this.temp = t;
this.wind = w;
this.humid = h;
}
#Override
public String toString() {
return "The detailed info : " + this.time + "-" + this.temp+ " "+ this.wind+ "-" + this.humid;
}
}
It might not fit exactly your needs but it can be a help.

Creating an object with a constructor

i am working on a project and am stuck and have been for awhile, i want to make two objects, one t2001 and the other t2009. I made the constructor for them being TaxFiling but i am still getting a red underline error saying cannot find symbol? Does anyone know what i am doing wrong.
package ProgrammingAssignment;
import java.util.Scanner;
/**
*
* #author Joe
*/
public class Tax {
public static final int SINGLE_FILER = 0;
public static final int MARRIED_JOINTLY_OR_QUALIFYING_WIDOW = 1;
public static final int MARRIED_SEPARATELY = 2;
public static final int HEAD_OF_HOUSEHOLD = 3;
private int filingStatus;
private int[][] brackets;
private double[] rates;
private double taxableIncome;
public Tax(int filingStatus, int[][] brackets, double[] rates, double taxableIncome) {
this.filingStatus = filingStatus;
this.brackets = brackets;
this.rates = rates;
this.taxableIncome = taxableIncome;
}
public double getTax() {
double tax;
if (taxableIncome <= brackets[filingStatus][0]) {
return Math.round(taxableIncome * rates[0]);
}
tax = brackets[filingStatus][0] * rates[0];
for (int i = 1; i < brackets[filingStatus].length; i++) {
if (taxableIncome > brackets[filingStatus][i]) {
tax += (brackets[filingStatus][i] - brackets[filingStatus][i - 1]) * rates[i];
} else {
return Math.round(tax + (taxableIncome - brackets[filingStatus][i - 1]) * rates[i]);
}
}
return Math.round(tax + (taxableIncome - brackets[filingStatus][4]) * rates[5]);
}
public void TaxFiling(int taxYear, int[][] brackets, double[] rates) {
int Year = taxYear;
int[][] bracket = brackets;
double[] rate = rates;
}
public static void main(String[] args) {
int taxYear;
int sIncome;
int eIncome;
int stepVal;
Scanner input = new Scanner(System.in);
System.out.println("Enter a tax year: ");
taxYear = input.nextInt();
if (taxYear != 2009 && taxYear != 2001) {
System.out.println("Please Enter a Valid Year!");
System.exit(1);
}
System.out.println("Enter the starting income value: ");
sIncome = input.nextInt();
System.out.println("Enter ending income value: ");
eIncome = input.nextInt();
if (eIncome < sIncome) {
System.out.println("Ending Income Cannot Be Less Then Starting");
System.exit(2);
}
System.out.println("Enter a step value: ");
stepVal = input.nextInt();
if (stepVal < 0) {
System.out.println("Please Enter a Positive Step Value!");
System.exit(3);
}
System.out.println(taxYear + " Tax Table");
System.out.println("Income range: " + sIncome + " to " + eIncome);
int[][] brackets2009 = new int[][]{
// stat 0 single
{8350, 33950, 82250, 171550, 372950},
// stat 1 Married Filing Jointly
{16700, 67900, 137050, 208850, 372950},
// stat 2 Married Filing Separately
{8350, 33950, 68525, 104425, 186475},
// stat 3 Head of Household
{11950, 45500, 117450, 190200, 372950}};
int[][] brackets2001 = new int[][]{
// stat 0 single
{27050, 65550, 136750, 297350},
// stat 1 married joint
{45200, 109250, 166500, 297350},
// stat 2 married separate
{22600, 54625, 83250, 148675},
// stat 3 head of household
{36250, 93650, 15150, 297350}
};
double[] rates2009 = new double[]{0.10, 0.15, 0.25, 0.28, 0.33, 0.35};
double[] rates2001 = new double[]{.15, .275, .305, .355, .391};
TaxFiling t2001 = new TaxFiling(2001, brackets2001, rates2001);
TaxFiling t2009 = new TaxFiling(2009, brackets2009, rates2009);
if (taxYear == 2001) {
DisplayTaxTable(t2001, sIncome, eIncome, stepVal);
} else if (taxYear == 2009) {
DisplayTaxTable(t2009, sIncome, eIncome, stepVal);
}
}
public static void displayTaxTable(Tax tObj, int incomeStart, int incomeEnd, int incomeStep) {
String s1 = "Taxable Income";
String s2 = "Single";
String s3 = "Married Joint";
String s4 = "Married Separate";
String s5 = "Head of house";
System.out.printf(
"%-20s%-12s%-4s%21s%16s\n", s1, s2, s3, s4, s5);
for (int i = 50000;
i <= 60000; i += 1000) {
System.out.printf("%4d%19.0f%16.0f%16.0f%20.0f\n", i,
new Tax(Tax.SINGLE_FILER, brackets2009, rates2009, i).getTax(),
new Tax(Tax.MARRIED_JOINTLY_OR_QUALIFYING_WIDOW, brackets2009, rates2009, i).getTax(),
new Tax(Tax.MARRIED_SEPARATELY, brackets2009, rates2009, i).getTax(),
new Tax(Tax.HEAD_OF_HOUSEHOLD, brackets2009, rates2009, i).getTax()
);
}
for (int i = 50000;
i <= 60000; i += 1000) {
System.out.printf("%4d%19.0f%16.0f%16.0f%20.0f\n", i,
new Tax(Tax.SINGLE_FILER, brackets2001, rates2001, i).getTax(),
new Tax(Tax.MARRIED_JOINTLY_OR_QUALIFYING_WIDOW, brackets2001, rates2001, i).getTax(),
new Tax(Tax.MARRIED_SEPARATELY, brackets2001, rates2001, i).getTax(),
new Tax(Tax.HEAD_OF_HOUSEHOLD, brackets2009, rates2001, i).getTax()
);
}
}
}
You are trying to declare a constructor for TaxFiling inside of your Tax class. TaxFiling needs it's own separate class file or needs to be declared in a private class inside of your Tax class.
TaxFiling is not a constructor, its a method inside the Tax class, you need to create a different class for Taxfiling and create a constructor like:
public class TaxFiling {
public TaxFiling(int taxYear, int[][] brackets, double[] rates) {
}
}
public Tax(int taxYear, int[][] brackets, double[] rates) {
int Year = taxYear;
int[][] bracket = brackets;
double[] rate = rates;
}
This is what i changed it to and it works but when i try and pass the object into displayTaxTable i get more errors.
public static void displayTaxTable(Tax tObj, int incomeStart, int incomeEnd, int stepVal) {
String s1 = "Taxable Income";
String s2 = "Single";
String s3 = "Married Joint";
String s4 = "Married Separate";
String s5 = "Head of house";
System.out.printf(
"%-20s%-12s%-4s%21s%16s\n", s1, s2, s3, s4, s5);
for (int i = incomeStart;
i <= incomeEnd; i += stepVal) {
System.out.printf("%4d%19.0f%16.0f%16.0f%20.0f\n", i,
new Tax(Tax.SINGLE_FILER, bracket, rate, i).getTax(),
new Tax(Tax.MARRIED_JOINTLY_OR_QUALIFYING_WIDOW, bracket, rate, i).getTax(),
new Tax(Tax.MARRIED_SEPARATELY, bracket, rate, i).getTax(),
new Tax(Tax.HEAD_OF_HOUSEHOLD, bracket, rate, i).getTax()
);
}
}
If you write "new TaxFiling(...)", it means you call a constructor. But in your code, TaxFiling is a method.
Three options:
1) Make a class TaxFiling with fields taxYear, brackets and double rates. Make a constructor:
public TaxFiling(int taxYear, int[][] brackets, double[] rates) {
//set taxYear, brackets, rates etc
}
2) Make method taxFiling (methods start with lowercase!) return a Tax object like so:
public Tax taxFiling(int taxYear, int[][] brackets, double[] rates) {
return new Tax(/* set your data here */);
}
3) Make TaxFiling a constructor in Tax class. But, all constructors MUST be named exactly like the class they are in, like so:
public Tax(int taxYear, int[][] brackets, double[] rates) {
//set taxYear, brackets, rates etc
}
Beware, in displayTaxTable method, you don't use the tObj that you pass. Make use of it! Use getters to get information from that object

Need help using an ArrayList

It seems that 20 regiments were in a continuous process of formation. The first had 1000 men, the second had 950, the third 900, and so on down to the twentieth regiment, which garrisoned only 50. During each week, 100 men were added to each regiment, and at week's end, the largest regiment was sent off to the front.This lasted for a total of 20 weeks.
For this program I have already managed to print out the original number of men for each regiment. But I am having difficult adding 100 men to each regiment.The adding men must be a method in the army class. I am getting the regiment objects using a .txt file. All this files contains is the names of regiments numbered 1-20.
I currently have no errors my only problem is that I do not know how to add men to my regiment. I have to use the addMen method in the army class which I currently have blank.
public class Regiment {
private String name; //name of regiment
private int regNumber; //regiment number
private int men; // regiment men
public Regiment(int regNumber, String name, int men) {
this.name = name;
this.regNumber = regNumber;
this.men = men;
}
public String getName() {
return name;
}
public int getregNumber() {
return regNumber;
}
public int getMen() {
return men;
}
public int addMen2(int RegNumber) {
int men = 1050 - (regNumber * 50);
return men;
}
}
ArmyDataList:
class ArmyDataList {
public ArrayList<Regiment> list;
public ArmyDataList() {
list = new ArrayList<Regiment>();
}
public void AddToList(Regiment current) {
list.add(current);
}
public void RemoveFromList(Regiment current) {
list.remove(current);
}
public Regiment getLargest() {
if (list.isEmpty()) {
return null;
}
Regiment Reg1 = list.get(0);
for (int i = 1; i < list.size(); i++) {
Regiment current = list.get(i); // get next regiment
// is current regiment > largest
if (current.getMen() > Reg1.getMen()) {
Reg1 = current;
}
}
return Reg1;
}
public void addMen() {
}
public String toString() {
String out
= String.format("%28s%12s%n", "Regiments", " Men")
+ String.format("%12s%n", "Number")
+ String.format("%12s%16s%14s%n", "=======", "===============",
"=========");
for (int i = 0; i < list.size(); i++) {
Regiment regim = list.get(i);
int regNumber = regim.getregNumber();
String name = regim.getName();
int men = regim.addMen2(regNumber);
out = out + String.format("%12s", regNumber)
+ String.format("%16s", name)
+ String.format("%10s", men)
+ "\n";
}
return out + "\n";
}
}
RegimentTest:
public class RegimentTest {
public static void main(String[] args) throws IOException
{
ArmyDataList army = new ArmyDataList();
Scanner fileScan = new Scanner(new File("regiments.txt"));
System.out.println("Report Summary:\n");
while (fileScan.hasNext()) {
String line = fileScan.nextLine();
System.out.println(line);
Scanner in = new Scanner(line) ;
int regNumber = in.nextInt();
String name = in.next();
int men = 0 ; //men is set to 0 only because I havent add the men yet
Regiment adder = new Regiment(regNumber, name, men );
army.AddToList(adder) ;
}
System.out.println(army.toString());
}
Add a setMen(int numberOfMen) method to your Regiment class. Then in your addMen() method, you can do something like this:
public void addMen(){
for(Regiment r : list){ //iterate through the list of regiments
r.setMen(r.getMen() + 100); //add 100 men to each regiment
}
}
The setMen method would look like this:
public void setMen(int numberOfMen){
men = numberOfMen;
}
There is another issue with your toString method, where the regiment's addMen2 method is called - right now you're just printing the number, not initializing the number of men. In the constructor for your Regiment class, replace the line
this.men = men;
with
this.men = addMen2(regNumber);
Then in your toString method, replace
int men = regim.addMen2(regNumber);
with
int men = regim.getMen();
Here is what your main should look like:
public static void main(String[] args) throws IOException{
ArmyDataList army = new ArmyDataList();
Scanner fileScan = new Scanner(new File("regiments.txt"));
System.out.println("Report Summary:\n");
while (fileScan.hasNext()) {
String line = fileScan.nextLine();
System.out.println(line);
Scanner in = new Scanner(line);
int regNumber = in.nextInt();
String name = in.next();
int men = 0 ; //men is set to 0 only because I havent add the men yet
Regiment adder = new Regiment(regNumber, name, men );
army.AddToList(adder);
}
System.out.println(army.toString()); //print out the initial # of men
for(int i = 0; i < 20; i++)
army.addMen();
System.out.println(army.toString()); //print the final # of men
}
in Regiment get rid of method addMen2, and replace it with
public void addMen(int men) {
this.men +=men;
}
then in your army you could have method
public void addMen(int men) {
for(Regiment regiment : list){
regiment.addMen(men);
}
}
that will be simplest solution to add 100 men to each regiment,
other thing is, your toString is bit nasty, regiment should know how meny soldiers it ghas, you shouldnt need additional method to calculate it (reason why i recommend you to trash addMen2 method)
to initiate your Regiment, use constructor. You want to have regiments in sizes 1000, 1950, 1900 etc, do it when you are creating them
while (fileScan.hasNext()) {
String line = fileScan.nextLine();
System.out.println(line);
Scanner in = new Scanner(line) ;
int regNumber = in.nextInt();
String name = in.next();
int men = 1050 - (regNumber * 50);
Regiment adder = new Regiment(regNumber, name, men );
army.AddToList(adder) ;
}

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