Java Input Validation - java

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

Related

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

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.

Having trouble creating an object

When i try to create a specific object for the bot class I get the following error, and i do not understand what the problem is:
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:454)
at java.lang.Integer.parseInt(Integer.java:527)
at Bot.<init>(Bot.java:10)
at PlayGame.<clinit>(PlayGame.java:5)
My code for my main class is as follows:
import java.util.Scanner;
public class PlayGame {
static GameLogic GLObject = new GameLogic();
static Bot botObject = new Bot();
public static void main(String [] args){
System.out.println("Enter the file name and extension in the form file_name.extension:");
Scanner scanner = new Scanner(System.in);
String fileName = scanner.nextLine();
Map mapObject = new Map();
mapObject.readMap(fileName);
while(true){
getMove();
}
}
public static void getMove(){
System.out.println("Enter what you wish to do:");
Scanner scanner_1 = new Scanner(System.in);
String move = scanner_1.nextLine();
move = move.toUpperCase();
useMove(move);
}
public static void useMove(String move){
if(move.equals("N")){
GLObject.MOVE('N');
}
else if(move.equals("E")){
GLObject.MOVE('E');
}
else if(move.equals("S")){
GLObject.MOVE('S');
}
else if(move.equals("W")){
GLObject.MOVE('W');
}
else if(move.equals("HELLO")){
GLObject.HELLO();
}
else if(move.equals("PICKUP")){
GLObject.PICKUP();
}
else if(move.equals("LOOK")){
GLObject.LOOK();
}
else if(move.equals("QUIT")){
GLObject.QUIT();
}
else if(move.equals("BOT")){
botObject.getMap();
}
else{
System.out.println("This is not a valid input!!");
}
}
}
The code for the bot class currently is:
public class Bot {
GameLogic GLObject = new GameLogic();
char [][] Array;
int Column = GLObject.Column;
int Row = GLObject.Row;
boolean goldMarker = false;
int goldNumber = Integer.parseInt(Map.goldNumber);
int goldCount = 0;
boolean exitSet = false;
public void getMap(){
Array = GameLogic.mapArrayGlobal;
GameLogic.printArray(Array);
traverseMap();
}
public void traverseMap(){
int direction = (int) (Math.random() * 4);
if(direction == 0){
MOVE('N');
}
else if(direction == 1){
MOVE('S');
}
else if(direction == 2){
MOVE('E');
}
else if(direction == 3){
MOVE('W');
}
}
Could anyone advise as to what is causing this problem.
Thank very much :)
Your problem is that Map.goldNumber is not an integer when you construct the Bot, causing the initialization to fail when you try to use parseInt. It should work if you make sure that there is a valid numerical string in Map.goldNumber.

Can't get push method to work

I am need some quick help with finishing an assignment, In short I completed an assignment that required me to make a program that allowed the user to pop(), push() and top() an array.
I did it but my tutor said that the code layout wrong as I had System.out.println statements in the stack class and these should be in the main menu app, and the stack class should only called the methods that it inherits from the array class.
Fair enough I thought and I amended the code but I cannot get the push() method to work correctly now :/
I know that I need to use the Genio.getInteger method in the menu app push()method.
Can anyone help?
Stack Class:
public class Stack extends Array
{
private int x;
public Stack()
{
super();// initialise instance variables
x = 0;
}
public Stack(int newsize)
{
super(newsize);
System.out.println("Stack Created!");
}
/**
* #push user is asked to enter value at keyboard which is then added to the top of the stack
*
*/
public boolean push(int item)
{
return add(item);
}
/**
* #pop removes the current value staored at the top of the stack
*
*/
public int pop()
{
deleteLast();
return getItemback();
}
/**
* #top displays the current value stored at the top of the stack
*
*/
public int top()
{
displayLast();
return getItemback();
}
}
Menu app:
public static void main()
{
int option;
int item;
Stack s = new Stack();
String []menuitems = {"1 - Display Stack","2 - Pop Stack", "3 - Push Onto Stack","4 - Top Of Stack","5 - Quit Program"};
Menu m = new Menu(menuitems,5);
s.add(12);s.add(2);s.add(1);s.add(13);s.add(24);
do
{
clrscr();
option = m.showMenu();
if ( option == 1 )
{
s.display();
pressKey();
}
if ( option == 2 )
{
if (!s.isEmpty())
System.out.println ("Number Popped: ");
else
System.out.println ("The Stack Is Empty! ");
pressKey();
}
// THIS IS THE PART I CANNOT GET TO WORK!! NOT SURE WHERE/HOW TO CALL PUSH
// METHOD?
if ( option == 3 )
{
item = Genio.getInteger();
if (!s.isFull())
System.out.println("Please Enter Number To be Pushed(" + item + ")");
else
System.out.println("Stack Overflow! ");
pressKey();
}
if ( option == 4 )
{
if (!s.isEmpty())
s.top();
else
System.out.println ("The Stack Is Empty! ");
pressKey();
}
}
while ( option != 5 );
System.out.println("\nDone! \n(You Can Now Exit The Program)\n");
}
/**
* #clrscr removes all text from the screen
*
*/
public static void clrscr()
{
for ( int i=1;i<=50;i++)
System.out.println();
}
/**
* #pressKey requires the user to press return to continue
*
*/
public static void pressKey()
{
String s;
System.out.print("\nPress return to continue : ");
s = Genio.getString();
}
}
EDIT: Genio class if relevant?:
public class Genio
{
/**
* Constructor for objects of class genio, but nothing needing constructed!
*/
public Genio()
{
}
/**
* getStr() is a private method which safely returns a string for use
* by the public methods getString() and getCharacter() in the class.
*
* #return String for further processing withing the class
*/
private static String getStr()
{
String inputLine = "";
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
try
{
inputLine = reader.readLine();
}
catch(Exception exc)
{
System.out.println ("There was an error during reading: "
+ exc.getMessage());
}
return inputLine;
}
/**
* getInteger() returns an integer value. Exception handling is used to trap
* invalid data - including floating point numbers, non-numeric characters
* and no data. In the event of an exception, the user is prompted to enter
* the correct data in the correct format.
*
* #return validated int value
*/
public static int getInteger()
{
int temp=0;
boolean OK = false;
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
do
{
try
{
temp = Integer.parseInt(keyboard.readLine());
OK = true;
}
catch (Exception eRef)
{
if (eRef instanceof NumberFormatException)
{
System.out.print("Integer value needed: ");
}
else
{
System.out.println("Please report this error: "+eRef.toString());
}
}
} while(OK == false);
return(temp);
}
/**
* getFloat() returns a floating point value. Exception handling is used to trap
* invalid data - including non-numeric characters and no data.
* In the event of an exception (normally no data or alpha), the user is prompted to enter
* data in the correct format
*
* #return validated float value
*/
public static float getFloat()
{
float temp=0;
boolean OK = false;
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
do
{
try
{
temp = Float.parseFloat(keyboard.readLine());
OK = true;
}
catch (Exception eRef)
{
if (eRef instanceof NumberFormatException)
{
System.out.print("Number needed: ");
}
else
{
System.out.println("Please report this error: "+eRef.toString());
}
}
} while(OK == false);
return(temp);
}
/**
* getDouble() returns a double precision floating point value.
* Exception handling is used to trap invalid data - including non-numeric
* characters and no data.
* In the event of an exception, the user is prompted to enter
* data in the correct format
*
* #return validated double precision value
*/
public static double getDouble()
{
double temp=0;
boolean OK = false;
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
do
{
try
{
temp = Double.parseDouble(keyboard.readLine());
OK = true;
}
catch (Exception eRef)
{
if (eRef instanceof NumberFormatException)
{
System.out.print("Number needed: ");
}
else
{
System.out.println("Please report this error: "+eRef.toString());
}
}
} while(OK == false);
return(temp);
}
/**
* getCharacter() returns a character from the keyboard. It does this by
* reading a string then taking the first character read. Subsequent characters
* are discarded without raising an exception.
* The method checks to ensure a character has been entered, and prompts
* if it has not.
*
* #return validated character value
*/
public static char getCharacter()
{
String tempStr="";
char temp=' ';
boolean OK = false;
do
{
try
{
tempStr = getStr();
temp = tempStr.charAt(0);
OK = true;
}
catch (Exception eRef)
{
if (eRef instanceof StringIndexOutOfBoundsException)
{
// means nothing was entered so prompt ...
System.out.print("Enter a character: ");
}
else
{
System.out.println("Please report this error: "+eRef.toString());
}
}
} while(OK == false);
return(temp);
}
/**
* getString() returns a String entered at the keyboard.
* #return String value
*/
public static String getString()
{
String temp="";
try
{
temp = getStr();
}
catch (Exception eRef)
{
System.out.println("Please report this error: "+eRef.toString());
}
return(temp);
}
}
Not sure if I understood your question correctly, but s.push isn't being called? (s.pop isn't either?)
If you'll replace
if (!s.isFull())
with
if (!s.isFull() && s.push(item))
some work will get done?
If you want it only to be a prompt, use curly brackets (use them anyway, it'll save you from horrid bugs one day). Something like this.
if (!s.isFull()) {
System.out.println("enter a number to add");
Scanner sc = new Scanner(System.in);
s.push(sc.nextInt());
}

I get an error message as follows: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0

I get an error message as follows: Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at emp.MainClass.main(MainClass.java:52)
Using the following code, how do I alleviate this problem?
public class MainClass {
//main class
public static void main(String[] args){
// variable
String input;
boolean salaryError = true;
boolean dependentError = true;
boolean nameError = true;
boolean charError = true;
Employee emp1 = new Employee();
displayDivider("EMPLOYEE INFORMATION");
do{
input = getInput(" First Name");
nameError = nameValidate(input);
if(!nameError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!nameError);
emp1.setfirstName(input);
do{
input = getInput(" Last Name");
nameError =nameValidate(input);
if(!nameError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!nameError);
emp1.setlastName(input);
do{
input = getInput(" Gender: M or F");
charError = characterChecker(input.charAt(0));
if(!charError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!charError);
char g = input.charAt(0);
emp1.setgender(g);// validates use of M or F for gender
do{
input = getInput(" number of dependents");
dependentError = integerChecker(input);
if(!dependentError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!dependentError);
emp1.setdependents(Integer.parseInt(input));
do{
input = getInput(" annual salary");
salaryError = doubleChecker(input);
if(!salaryError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
} while(!salaryError);
emp1.setannualSalary(Double.parseDouble(input));
emp1.displayEmployee();//displays data for emp1
Employee emp2 = new Employee("Speed","Racer",'M',1,500000.00);
displayDivider("EMPLOYEE INFORMATION");
emp2.displayEmployee();// displays data for emp2
terminateApplication(); //terminates application
System.exit(0);//exits program
}//end of main
// gets Input information
public static String getInput(String data)
{
String input = "";
input = javax.swing.JOptionPane.showInputDialog(null,"Enter your " + data);
return input;
}// end getInput information
// The display divider between employees
public static void displayDivider(String outputLab)
{
System.out.println("********" + outputLab + "********");
}// end display divider
// Terminates the application
public static void terminateApplication()
{ javax.swing.JOptionPane.showMessageDialog(null,"Thanks for the input!");
}// end terminateApplication
public static boolean doubleChecker(String inStr){
boolean outBool = true;
double tmpDbl = 0.0;
try{
tmpDbl = Double.parseDouble(inStr);
if(tmpDbl <= 0)
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
public static boolean integerChecker(String intStr){
boolean outBool = true;
int tmpInt = 0;
try{
tmpInt = Integer.parseInt(intStr);
if(tmpInt <= 0)
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
public static boolean nameValidate(String str){
for(char ch : str.toCharArray()){
if(!Character.isDigit(ch)){
return true;
}
}
return false;
}
public static boolean characterChecker(char gen){
boolean outBool = true;
try{
if(!( gen ==( 'M') || gen ==('F')))
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
}//end of Main Class
Your string is length 0. Make sure string.length() > 0 before accessing its elements. The problem is at the line the exception says the problem is on.
Better answer: are you using an IDE? If so, observe the line the exception tells you you have an error on. Set a breakpoint before that line, debug, and note the contents of the object on which the error happened (in this case the string). Then check the javadoc for the method that threw the exception to see if there is any problem calling that method on that string.
If you are not using an IDE, you will either need to use one or find a standalone debugger. Having a good debugger is a requirement of Java development.
This should save you a lot of SO questions going forward.
StringIndexOutofBoundsException means you're try to access the String using an index and the index is either negative or greater than the size of the string.
You're wrong in this part:
charError = characterChecker(input.charAt(0));
Because you're not check if the input length is 0.
Try to change that line to this:
charError = input != null && input.length() > 0 && characterChecker(input.charAt(0));

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