Exception in thread "main" java.util.InputMismatchException when input double - java

import java.util.*;
class OverdueChecker {
private static enum Response {YES, NO};
private static final String DATE_SEPARATOR = "/";
private Scanner scanner;
private BookTracker bookTracker;
//---------------------
// Constructor
//---------------------
public OverdueChecker() {
scanner = new Scanner(System.in);
scanner.useDelimiter("\\n");
bookTracker = new BookTracker();
}
//-----------------
// Main Method
//-----------------
public static void main(String[] args) {
OverdueChecker checker = new OverdueChecker();
checker.start();
}
//-------------------------
// Public Method
//-------------------------
public void start() {
GregorianCalendar returnDate;
String table;
double charge;
Response response;
inputBooks();
table = bookTracker.getList();
System.out.println(table);
System.out.print("\nNow check the over due charges...\n");
//try different return dates
do {
//read return date
returnDate = readDate("\nReturn Date: ");
charge = bookTracker.getCharge(returnDate);
displayTotalCharge(charge);
response = prompt("\nRun Again (yes/no)? ");
} while (response == Response.YES);
System.out.println("\n\nThank you for using Library Overdue Checker");
}
//----------------------------
// Private Method
//-----------------------------
private LibraryBook createBook(String title, double chargePerDay, double maxCharge, GregorianCalendar dueDate) {
if(dueDate == null) {
dueDate = new GregorianCalendar(); //set today as due date
}
LibraryBook book = new LibraryBook(dueDate);
if(title.length() > 0) {
book.setTitle(title);
}
if(chargePerDay > 0.0) {
book.setChargePerDay(chargePerDay);
}
if (maxCharge > 0.0) {
book.setMaximumCharge(maxCharge);
}
return book;
}
private void display(String text) {
System.out.print(text);
}
private void displayTotalCharge(double charge) {
System.out.format("\nTOTAL CHARGE:\t $%8.2f", charge);
}
private void inputBooks() {
double chargePerDay, maxCharge;
String title;
GregorianCalendar dueDate;
LibraryBook book;
//Keeps on reading input from a console
//until stopped by the end user
while(!isContinue()) {
System.out.println("\n");
title = readString("Title : ");
chargePerDay = readDouble("Charge per day : ");
maxCharge = readDouble("Maximum charge : ");
dueDate = readDate ("Due date : ");
book = createBook(title, chargePerDay, maxCharge, dueDate);
bookTracker.add(book);
}
}
private boolean isContinue() {
Response response = prompt("\nMore books to enter (y/n) ? ");
return(response == Response.YES);
}
private Response prompt(String question) {
String input;
Response response = Response.NO;
System.out.print(question + "(Yes - y; No - n) : ");
input = scanner.next();
if(input.equals("Y") || input.equals("y")) {
response = Response.YES;
}
return response;
}
private double readDouble(String prompt) {
display(prompt);
return scanner.nextDouble();
}
private GregorianCalendar readDate(String prompt) {
GregorianCalendar cal;
String yearStr, monthStr, dayStr, line;
int sep1, sep2;
display(prompt);
line = scanner.next();
if(line.length() == 0) {
cal = null;
} else {
sep1 = line.indexOf(DATE_SEPARATOR);
sep2 = line.lastIndexOf(DATE_SEPARATOR);
monthStr = line.substring(0, sep1);
dayStr = line.substring(sep1 + 1, sep2);
yearStr = line.substring(sep2 + 1, line.length());
cal = new GregorianCalendar(Integer.parseInt(yearStr), Integer.parseInt(monthStr)-1, Integer.parseInt(dayStr));
}
return cal;
}
private String readString(String prompt) {
display(prompt);
return scanner.next();
}
}
I was tried to compile the library overdue checker program that I followed from a book but ended with this error.
Title : jkj
Charge per day : 9
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at OverdueChecker.readDouble(OverdueChecker.java:130)
at OverdueChecker.inputBooks(OverdueChecker.java:101)
at OverdueChecker.start(OverdueChecker.java:40)
at OverdueChecker.main(OverdueChecker.java:28)
Actually, the program will ask the user the details of the book that overdue return (title, charge per day, due date, return date) and will compute the total charge
Oddly, when my friends run it on their laptop it does work. Can anyone give me a solution?

1. Change the definition of readDouble as follows:
private double readDouble(String prompt) {
boolean valid;
double d = 0;
do {
valid = true;
display(prompt);
try {
d = Double.parseDouble(scanner.nextLine());
} catch (NumberFormatException | NullPointerException e) {
System.out.println("Invalid input. Try again");
valid = false;
}
} while (!valid);
return d;
}
2. Change all occurrences of scanner.next(); to Scanner.nextLine();
Check Scanner is skipping nextLine() after using next() or nextFoo()? for more information.

Change the Scanner.nextDouble() in readDouble() to read a String using Scanner.next() instead and output it with System.out.println(). You'll probably see that you're reading something else due to the wrong setup of a delimiter in your Scanner.
This is not the specific problem answer, rather a general technique for debugging input parsing here.

Related

Error message when I attach a textfile to my code

I need to create program to offer the user the ability to produce the report as show about in alphabetical order by
township name or in size order by township square mile.
But I get error message when I run the text file with the code.
Without the text file, my code works, but when I try to use the text file with the code, I get this error.
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:678)
at java.base/java.lang.Integer.parseInt(Integer.java:786)
at Main.main(Mice.java:76)
My code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
// create mice class
class Mice {
private final double micepopulation;
private final int sizetown;
private final String town;
// =-=-=-=-=-=-=-=-=--==-=
public Mice(double population, int sizetown, String town) {
this.town = town;
this.micepopulation = population;
this.sizetown = sizetown;
}
// --==--=-=-=-=-=-=-=-=-=--=
public String miceelseif() {
if (micepopulation > 75) {
return "Blue";
} else if (micepopulation > 65) {
return "Green";
} else if (micepopulation > 50) {
return "Yellow";
} else if (micepopulation > 35) {
return "Orange";
} else {
return "Red";
}
// -=-=-=-=-=-=-=-=-=-=-=-=-
}
public String getTOWN() {
return town;
}
public String toString() {
return String.format("%-25s%-20.2f%-20d%-20s", town, micepopulation, sizetown, miceelseif());
}
}
public class Main {
public static void main(String[] args) {
int numRecords = getNumRecords();
String[] township = new String[numRecords];
double[] population = new double[numRecords];
int[] townsize = new int[numRecords];
try {
Scanner fileScanner = new Scanner(new File("Micepopulation.txt"));
int index = 0;
while (fileScanner.hasNextLine()) {
township[index] = fileScanner.nextLine();
String[] popTwonSizeContents = fileScanner.nextLine().trim().split("");
population[index] = Double.parseDouble(popTwonSizeContents[0]);
townsize[index] = Integer.parseInt(popTwonSizeContents[1]);
// increment the index
index++;
}
fileScanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Mice[] micePop = new Mice[numRecords];
for (int index = 0; index < micePop.length; index++) {
micePop[index] = new Mice(population[index], townsize[index], township[index]);
}
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("1: Mice by Town");
System.out.println("2: Mice by size");
System.out.println("3- Town name");
System.out.println("0- Exit");
System.out.print(" Please enter your choice: ");
choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 0 -> System.out.println("thank you, have a good day");
case 1, 2 -> bytown(micePop);
case 3 -> {
System.out.print("please enter town ");
String town = scanner.nextLine();
int foundIndex = townLookUp(micePop, town);
if (foundIndex == -1) {
System.out.println("no town");
} else {
System.out.printf("%-25s%-20s%-20s%-20s\n", "Town", "Mice Population", "Town Size",
"Alerts");
System.out.println(micePop[foundIndex].toString());
}
}
default -> System.out.println("Invalid choice");
}
System.out.println();
} while (choice != 0);
scanner.close();
}
// ==-=-=-===--==-=-=-=-=-=-=-=-=-=--==-
private static void bytown(Mice[] micePop) {
for (int index = 0; index < micePop.length; index++) {
for (int innerIndex = 0; innerIndex < micePop.length - index - 1; innerIndex++) {
if (micePop[innerIndex].getTOWN().compareTo(micePop[innerIndex + 1].getTOWN()) > 0) {
Mice temp = micePop[innerIndex];
micePop[innerIndex] = micePop[innerIndex + 1];
micePop[innerIndex + 1] = temp;
}
}
}
System.out.println("\nREPORT BY TOWN");
printMicePopulation(micePop);
}
// -=-===-=-=-=--==-=-=--==-=-
// =-=--=-==-=-=-=--==-=-=-=-=-=-=--==-=-=--
private static int townLookUp(Mice[] micePop, String township) {
for (int index = 0; index < micePop.length; index++) {
if (micePop[index].getTOWN().equalsIgnoreCase(township)) {
return index;
}
}
return -1;
}
// -=-==-=-=-=--==--==-=-==-=-=-=-=-=-=--==-=-=-----=
private static void printMicePopulation(Mice[] micePop) {
System.out.printf("%-25s%-20s%-20s%-20s\n", "Town", "Mice Population", "Town Size", "Threat Alert");
for (Mice mice : micePop) System.out.println(mice.toString());
}
// -=-==--==--==-==-=-=-===-=-=-=-=-=-=-=-
public static int getNumRecords() {
try {
Scanner scanner = new Scanner(new File("Micepopulation.txt"));
int numRecords = 0;
while (scanner.hasNextLine()) {
numRecords++;
scanner.nextLine();
}
scanner.close();
return numRecords / 2;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return 0;
}
}
Text File I'm trying to attach
City of Red
70.81 2137
Boro of Orange
101.77 71
Yellow City
83.13 1034
Green Town
54.79 1819
Blueville
45.71 1514
Indigo Village
4.15 1442
Violeton
119.27 2225
Redburg
7.46 977
Orange Park
16.72 133
Yellow Falls
94.5 4556
Green Haven
326.12 1105242
Blue City
44.69 1979
Indigo Township
113.56 365
Violet Point
35.27 4161
java.lang.NumberFormatException: For input string: "" means you are trying to parse a number that isn't a valid number. In your case, you are trying to convert an empty string to an integer.
You are running into this problem because population and townSize numbers have one or more spaces in your text file. Just using split(" ") will not be sufficient, you will have to use split("\\s+) to split on one or more spaces.
Blueville's numbers have two spaces, whereas Indigo Village's numbers have one space.

Java Input Validation

So I am working with a program that is supposed to incorporate try-catch blocks for exception handling. What I can't figure out is how to write a simple if statement for checking input from the user via Scanner to make sure it is a double and not a letter or a character so that if it is the program will catch it, display the error message, and tell the user to re-enter another value until a suitable input is entered. What I am looking for is a simple if(_width equals a letter/character) then return false along with an error message to go along with my already present if statement that checks whether the input is greater than zero.
my current code is below:
public class Rectangle {
//two double data fields width and height, default values are 1 for both.
private double width = 1;
private double height = 1;
private String errorMessage = "";
//no-arg constructor creates default rectangle
public Rectangle() {
}
//fpzc, called by another program with a statement like Rectangle rec = new Rectangle(#, #);
public Rectangle (double _width, double _height) throws Exception {
setWidth(_width);
setHeight(_height);
}
//get functions
public double getArea(){
return (width * height);
}
public double getPerimeter() {
return (2*(width + height));
}
public String getErrorMessage() {
return errorMessage;
}
//set functions
public void setWidth(double _width) throws Exception {
if( !isValidWidth(_width)){
Exception e = new Exception(errorMessage);
throw e;
//System.out.println(errorMessage);
//return false;
}
width = _width;
}
public void setHeight(double _height) throws Exception {
if ( !isValidHeight(_height)){
Exception e = new Exception(errorMessage);
throw e;
//System.out.println(errorMessage);
//return false;
}
height = _height;
}
//isValid methods
public boolean isValidWidth(double _width) {
if(_width > 0){
return true;
}
else {
errorMessage = "Invalid value for width, must be greater than zero";
return false;
}
if ()
}
public boolean isValidHeight(double _height) {
if(_height > 0){
return true;
}
else {
errorMessage = "Invalid value for height, must be greater than zero";
return false;
}
}
}
My class is being called by another test program that i have written correctly. Any help is appreciated! Thank you.
maybe something like:
String errorMessage = "error";
Scanner in = new Scanner(System.in);
String str = in.nextLine();
try {
Double.parseDouble(str);
}
catch( Exception e ){
System.out.println(errorMessage);
}
or iterate through the input and check if each character is digit:
String errorMessage = "error";
Scanner in = new Scanner(System.in);
String str = in.nextLine();
for(int i=0;i<str.length();i++){
char token = str.charAt(i);
if(!Character.isDigit(token) && token!='.' ) {
System.out.println(token + " doesnt work");
break;
}
}
On declaring your scanner you could also:
double num;
String errorMessage = "error";
while(true) {
Scanner in = new Scanner(System.in);
if (in.hasNextDouble()) {
num = in.nextDouble();
System.out.println(num);
break;
}
else System.out.println(errorMessage);
}
Maybe this code helps you:
double Input=0;
while(!(Input > 0)){{
System.out.println("Enter Valid Number");
Input = new Scanner(System.in).nextDouble();
}

Java - changing data fields?

There are two things I need help with but I'm having a hard time figuring out. They are listed below - any assistance is greatly appreciated.
1) I need to add a method that prompts the user to enter an int (1-3) to change the volume (default set to 2). I'm really having trouble figuring out how to make this work.
2) I need to add a similar method that prompts the user to enter an int (1 or 2) to plug the head phones in.
Here's my code; one is the test class:
//Open Package
package headphone_wk6;
//Import scanner since this will require user input
import java.util.Scanner;
// Creat class for headphones
public class HeadPhone_WK6 {
//Call scanner
Scanner stdin = new Scanner(System.in);
//Initialize input variable
int Input;
//Declare constant Variables
public static final int LOW = 1;
public static final int MEDIUM = 2;
public static final int HIGH = 3;
//Declare Private variables
private int volume;
private boolean pluggedIn;
private String manufacturer;
private String headPhoneColor;
//Declare Strings
String pluggedInStat;
String volumeNow;
// Constructor for class
public HeadPhone_WK6(int volume, boolean pluggedIn, String manufacturer, String headPhoneColor) {
this.volume = volume;
this.pluggedIn = pluggedIn;
this.manufacturer = manufacturer;
this.headPhoneColor = headPhoneColor;
}
// Default Constructor for default settings
public HeadPhone_WK6() {
volume = MEDIUM;
pluggedIn = false;
manufacturer = "";
headPhoneColor = "";
}
// setVolume
public void setVolume(int volume) {
this.volume = volume;
}
// getVolume
public int getVolume() {
if (volume == 1) {
volumeNow = "LOW";
}
else if (volume == 2) {
volumeNow = "MEDIUM";
}
else {
volumeNow = "HIGH";
}
return volume;
}
// setPluggedIn
public void setPluggedIn(boolean pluggedIn) {
this.pluggedIn = pluggedIn;
}
// getPluggedIn
public boolean getPluggedIn() {
if(pluggedIn == true) {
pluggedInStat = "Plugged In";
}
else {
pluggedInStat = "Not Plugged In";
}
return pluggedIn;
}
// setManufacturer
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
// getManufacturer
public String getManufacturer() {
return manufacturer;
}
// setHeadPhoneColor
public void setHeadPhoneColor(String headPhoneColor) {
this.headPhoneColor = headPhoneColor;
}
// getHeadPhoneColor
public String getHeadPhoneColor() {
return headPhoneColor;
}
// method to create string
public String toString() {
boolean phonesPluggedIn = this.getPluggedIn();
String phoneManufacturer = this.getManufacturer();
String phoneColor = this.getHeadPhoneColor();
String currentVolume = this.volumeNow;
//Build String for characteristics of phones
StringBuilder characteristics = new StringBuilder();
characteristics.append(String.format("\nThe Head Phone Manufacturer "
+ "is: %s", phoneManufacturer));
characteristics.append(String.format("\nThe Color of the Head Phone Set "
+ "is: %s", phoneColor));
characteristics.append(String.format("\nThe Head Phones are Currently: "
+ " %s", phonesPluggedIn));
characteristics.append(String.format("\nThe Head Phone Volume is "
+ "Currently Set on: %s", currentVolume));
//return string for characteristics
return characteristics.toString();
}
}
package headphone_wk6;
//Import scanner since this will require user input
import java.util.Scanner;
//Test class for head phone
public class HeadPhone_WK6_Test {
//Command line arguments
public static void main(String[] args) {
//Initialize input variable
int Input;
//Call scanner
Scanner stdin = new Scanner(System.in);
HeadPhone_WK6 bestPair = new HeadPhone_WK6(2, false, "SONY", "BLUE");
HeadPhone_WK6 worstPair = new HeadPhone_WK6(2, false, "BOSE", "BLACK");
HeadPhone_WK6 decentPair = new HeadPhone_WK6(2, false, "RCA", "ORANGE");
int bestPairVolume = bestPair.getVolume();
boolean bestPairPluggedIn = bestPair.getPluggedIn();
String bestPairManufacturer = bestPair.getManufacturer();
String bestPairHeadPhoneColor = bestPair.getHeadPhoneColor();
String bestPairVolumeNow = bestPair.volumeNow;
String bestPairPluggedInStat = bestPair.pluggedInStat;
int worstPairVolume = worstPair.getVolume();
boolean worstPairPluggedIn = worstPair.getPluggedIn();
String worstPairManufacturer = worstPair.getManufacturer();
String worstPairHeadPhoneColor = worstPair.getHeadPhoneColor();
String worstPairVolumeNow = worstPair.volumeNow;
String worstPairPluggedInStat = worstPair.pluggedInStat;
int decentPairVolume = decentPair.getVolume();
boolean decentPairPluggedIn = decentPair.getPluggedIn();
String decentPairManufacturer = decentPair.getManufacturer();
String decentPairHeadPhoneColor = decentPair.getHeadPhoneColor();
String decentPairVolumeNow = decentPair.volumeNow;
String decentPairPluggedInStat = decentPair.pluggedInStat;
//Introduce HeadPhone helper
System.out.print("Hi there! Let's have you try a pair of head phones "
+ "on and we'll see what you think of them! \nStart by choosing a "
+ "random pair of head phones. To do this, enter 1, 2, or 3: ");
//Get user input for random pair of headphones
Input = stdin.nextInt();
//Loop for random headphone selection
if (Input == 1){
//echo user input
System.out.println("You have chosen the best pair of "
+ "headphones! Here is a list of the characteristics: ");
System.out.println(bestPair.toString());
//End if
}
else if (Input == 2){
System.out.println("You have chosen the worst pair of "
+ "headphones. Here is a list of the characteristics: ");
System.out.println(worstPair.toString());
//End If
}
else if(Input == 3){
System.out.println("You have chosen a decent pair of "
+ "headphones. Here is a list of the characteristics:");
System.out.println(decentPair.toString());
//End If
}
else{
System.out.println("You have expressed that you want to see "
+ "the default pair of headphones. They are the "
+ "decent pair! Here's a list of the characteristics:");
System.out.println(decentPair.toString());
}
}
}
Maybe try something like this, first get input via scanner, then create HeadPhone objects:
//Initialize input variable
int Input;
//Call scanner
Scanner stdin = new Scanner(System.in);
//Introduce HeadPhone helper
System.out.print("Hi there! Let's have you try a pair of head phones "
+ "on and we'll see what you think of them! \nStart by choosing a "
+ "random pair of head phones. To do this, enter 1, 2, or 3: ");
//Get user input for random pair of headphones
Input = stdin.nextInt();
System.out.println("Now give me value of plug in 1 or 2");
int plugInState = stdin.nextInt();
boolean pluggedIn=true;
if(plugInState==1) pluggedIn = false;
if(plugInState==2) pluggedIn = true;
System.out.println("Now give me value volume (1/2/3");
int volumeState = stdin.nextInt();
HeadPhone_WK6 bestPair = new HeadPhone_WK6(volumeState, pluggedIn, "SONY", "BLUE");
HeadPhone_WK6 worstPair = new HeadPhone_WK6(volumeState, pluggedIn, "BOSE", "BLACK");
HeadPhone_WK6 decentPair = new HeadPhone_WK6(volumeState, pluggedIn, "RCA", "ORANGE");
You can put if clause in the end, based on your input, you can create one object that you need. If you need separate methods, do this in main():
HeadPhone_WK6 hp = new HeadPhone_WK6();
//Initialize input variable
int Input;
//Call scanner
Scanner stdin = new Scanner(System.in);
//Introduce HeadPhone helper
System.out.print("Hi there! Let's have you try a pair of head phones "
+ "on and we'll see what you think of them! \nStart by choosing a "
+ "random pair of head phones. To do this, enter 1, 2, or 3: ");
//Get user input for random pair of headphones
Input = stdin.nextInt();
System.out.println("Now give me value of plug in 1 or 2");
int plugInState = stdin.nextInt();
hp.setPluggedIn(plugInState);
System.out.println("Now give me value volume (1/2/3");
int volumeState = stdin.nextInt();
hp.setVolume(volumeState);
HeadPhone_WK6 bestPair = new HeadPhone_WK6(hp.getVolume(), hp.getPluggedIn(), "SONY", "BLUE");
HeadPhone_WK6 worstPair = new HeadPhone_WK6(hp.getVolume(), hp.getPluggedIn(), "BOSE", "BLACK");
HeadPhone_WK6 decentPair = new HeadPhone_WK6(hp.getVolume(), hp.getPluggedIn(), "RCA", "ORANGE");
Where
setPluggedIn(int pluggedInState) {
if(plugInState==1) pluggedIn = false;
else if(plugInState==2) pluggedIn = true;
else {
pluggedIn = false;
}
}

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.

Java code written but no expected output after running

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.

Categories