I am at the end with this Java console. I can place one word when I add new text but when I try to add a sentence, I get errors! If someone can see something I missed or the problem I would appreciate it very much. It will work for one word just not two or more words.
This is two classes
The first class
package Billboard;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Paul
*/
import java.util.Scanner;
public class BillboardMain {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
Billboard billboard = new Billboard();
while (true) {
System.out.println();
System.out.println();
System.out.println("\t Billboard Menu");
System.out.println();
System.out.println("Please select from the following billboard texts");
for (int i = 0; i < billboard.getMessages().size(); i++) {
System.out.println((i + 1) + ": "
+ billboard.getMessages().get(i));
}
System.out.println((billboard.getMessages().size() + 1)
+ ": Add new message.");
System.out.println((billboard.getMessages().size() + 2)
+ ": Show current text.");
System.out.println((billboard.getMessages().size() + 3) + ": Exit.");
System.out.println();
System.out.print("Choice: ");
int code = console.nextInt();
if (code == billboard.getMessages().size()+1) {
System.out.print("Enter new text here: ");
String newText = console.next();
billboard.addNewText(newText);
System.out.println("The new text message has been set to billboard");
} else if (code == billboard.getMessages().size() + 2) {
System.out.println("Current text is: " + billboard.getText());
} else if (code == billboard.getMessages().size() + 3) {
System.exit(0);
} else {
billboard.setText(code);
System.out.println("The text message has been set to billboard.");
}
}
}
}
The second class
package Billboard;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Paul
*/
import java.util.ArrayList;
import java.util.List;
public class Billboard {
private String text;
private List<String> messages = new ArrayList<String>();
public Billboard() {
super();
messages.add("Neutral.");
messages.add("Enemies.");
messages.add("Friends.");
}
public List<String> getMessages() {
return messages;
}
public boolean addNewText(String newText) {
text = newText;
return messages.add(newText);
}
public String getText() {
return text;
}
public void setText(int index) {
if (index <= messages.size())
this.text = messages.get(index - 1);
else
throw new IndexOutOfBoundsException("Invalid message code.");
}
public String reverse() {
if (isEmpty())
return null;
else {
char[] chars = text.toCharArray();
char[] reverse = new char[chars.length];
for (int i = chars.length - 1, j = 0; i < 0; i--, j++) {
reverse[j] = chars[i];
}
return new String(reverse);
}
}
public String replace(char oldChar, char newChar) {
return text.replace(oldChar, newChar);
}
public String substring(int begin, int end) {
if (begin >= 0 && end < text.length()) {
return text.substring(begin, end);
} else
return null;
}
public boolean isEmpty() {
return text == null || text.isEmpty();
}
}
define another Scanner
Scanner console1 = new Scanner(System.in);
and replace: String newText = console.next();
with: String newText = console1.nextLine();
it should work
Related
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.
I am trying to make a Connect 5 game, where the game logic is held on the server side, with the client side influencing the current game state. So far, I have the game logic implemented and it works just fine if you were to run it. I am running into issues when trying to implement the actual client/server sider of things.
I am not exactly sure how to go about doing it. What I can do at the moment is get the player names and the size of the board. When it comes to actually playing the game, I run into some issues such as keeping the game running and getting the player's move. Currently the server will stop running after a short period of time. I have tried using a while(true) to keep it running but it doesn't seem to work.
Another issue is displaying the actual board on the client side - while I am able to display the board if you were to just play the game from the server class using System.out.println(fiveInARow);, which displays the board after every move. I have tried using How to send String array Object over Socket? to display the board (testing if I can even just get the empty board at the start of the game to display on the client side), I get an error.
Should I be doing something like How to get input from Console in Java Client Server Program to get an input from the user inside the for (int player = 0; moves-- > 0; player = 1 - player)?
UPDATED: So I'm able to make a move and the move will be played accordingly. However, the second player is unable to make a move (unable to enter input on client side after first input).
Server
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
class FiveInARow implements Runnable {
private ArrayList<String> playerNames = new ArrayList<String>();
private String currPlayer;
private Socket socket;
private Scanner scanner;
private int width, height;
private static final char[] PLAYERS = { 'X', 'O' };
private char[][] gameBoard;
private int lastCol = -1, lastRow = -1;
public FiveInARow(Socket socket) {
this.socket = socket;
}
/**
*
* #param w - Width
* #param h - Height
* #param p1 - Player 1
* #param p2 - Player 2
*/
public FiveInARow(int w, int h, String p1, String p2) {
width = w;
height = h;
gameBoard = new char[h][];
playerNames.add(p1);
playerNames.add(p2);
for (int i = 0; i < h; i++) {
Arrays.fill(gameBoard[i] = new char[w], '.');
}
}
// Display the game board
public String toString() {
return IntStream.range(0, width).mapToObj(Integer::toString).collect(Collectors.joining("")) + "\n"
+ Arrays.stream(gameBoard).map(String::new).collect(Collectors.joining("\n"));
}
// Get string representation of the row containing the last play of the user
public String horizontal() {
return new String(gameBoard[lastRow]);
}
// Get string representation of the column containing the last play of the user
public String vertical() {
StringBuilder stringBuilder = new StringBuilder(height);
for (int h = 0; h < height; h++) {
stringBuilder.append(gameBoard[h][lastCol]);
}
return stringBuilder.toString();
}
// Get string representation of the "/" diagonal containing the last play of the
// user
public String fowardSlashDiagonal() {
StringBuilder stringBuilder = new StringBuilder(height);
for (int h = 0; h < height; h++) {
int w = lastCol + lastRow - h;
if (w >= 0 && w < width) {
stringBuilder.append(gameBoard[h][w]);
}
}
return stringBuilder.toString();
}
/**
* Get string representation of the "\" diagonal containing the last play of the
* user
*
* #return
*/
public String backSlashDiagonal() {
StringBuilder stringBuilder = new StringBuilder(height);
for (int h = 0; h < height; h++) {
int w = lastCol - lastRow + h;
if (0 <= w && w < width) {
stringBuilder.append(gameBoard[h][w]);
}
}
return stringBuilder.toString();
}
public static boolean contains(String str, String subString) {
return str.indexOf(subString) >= 0;
}
// Determine if a game as been won
public boolean hasWon() {
if (lastCol == -1) {
System.err.println("No move has been made yet");
return false;
}
char symbol = gameBoard[lastRow][lastCol];
String streak = String.format("%c%c%c%c%c", symbol, symbol, symbol, symbol, symbol);
return contains(horizontal(), streak) || contains(vertical(), streak) || contains(fowardSlashDiagonal(), streak)
|| contains(backSlashDiagonal(), streak);
}
/**
*
* #param symbol - Symbol/piece to be played
* #param scanner - Input
*/
public void playMove(char symbol, Scanner scanner) {
do {
if (symbol == PLAYERS[0]) {
currPlayer = playerNames.get(0);
} else {
currPlayer = playerNames.get(1);
}
System.out.println("\n" + currPlayer + "'s turn: ");
int col = scanner.nextInt();
// Check if input is valid
if (!(0 <= col && col < width)) {
System.out.println("Column must be between 0 and " + (width - 1));
continue;
}
for (int h = height - 1; h >= 0; h--) {
if (gameBoard[h][col] == '.') {
gameBoard[lastRow = h][lastCol = col] = symbol;
return;
}
}
// If column has already been filled, we need to ask for a new input
System.out.println("Column " + col + " is full");
} while (true);
}
// public static void main(String[] args) {
// try (Scanner input = new Scanner(System.in)) {
// String player1Name, player2Name;
// int height = 6;
// int width = 9;
// int moves = height * width;
//
// System.out.println("Player 1 name: ");
// player1Name = input.next();
//
// System.out.println("Player 2 name: ");
// player2Name = input.next();
//
// FiveInARow fiveInARow = new FiveInARow(width, height, player1Name, player2Name);
//
// System.out.println("Enter 0 - " + (width - 1) + " to play a piece\n");
//
// System.out.println(fiveInARow);
//
// for (int player = 0; moves-- > 0; player = 1 - player) {
// char symbol = PLAYERS[player];
//
// fiveInARow.playMove(symbol, input);
//
// System.out.println(fiveInARow);
//
// if (fiveInARow.hasWon()) {
// System.out.println("\nPlayer " + symbol + " wins!");
//
// return;
// }
// }
//
// System.out.println("Game over. Draw game!");
// }
// }
#Override
public void run() {
int height = 6;
int width = 9;
int moves = height * width;
System.out.println("Connected: " + socket);
try {
FiveInARow fiveInARow = new FiveInARow(width, height, "Kevin", "Fasha");
Scanner scanner = new Scanner(socket.getInputStream());
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
// while (scanner.hasNextInt()) {
// printWriter.println(scanner.nextInt());
// }
System.out.println(fiveInARow);
// while (scanner.hasNextInt()) {
for (int player = 0; moves-- > 0; player = 1 - player) {
char symbol = PLAYERS[player];
fiveInARow.playMove(symbol, scanner);
System.out.println(fiveInARow);
if (fiveInARow.hasWon()) {
System.out.println("\nPlayer " + symbol + " wins!");
return;
}
// }
}
} catch (Exception exception) {
System.out.println("Error: " + socket);
} finally {
try {
socket.close();
} catch (IOException e) {
}
System.out.println("Closed: " + socket);
}
}
public static void main(String[] args) throws Exception {
try (ServerSocket serverSocket = new ServerSocket(59898)) {
System.out.println("The game server is running...");
ExecutorService pool = Executors.newFixedThreadPool(20);
while (true) {
pool.execute(new FiveInARow(serverSocket.accept()));
}
}
}
}
Client
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class FiveInARowClient {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Pass the server IP as the sole command line argument");
return;
}
try (Socket socket = new Socket(args[0], 59898)) {
System.out.println("Enter lines of text then Ctrl+D or Ctrl+C to quit");
Scanner scanner = new Scanner(System.in);
Scanner in = new Scanner(socket.getInputStream());
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
while (scanner.hasNextLine()) {
out.println(scanner.nextLine());
System.out.println(in.nextLine());
}
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication7.ai;
import javaapplication7.model.Move;
import javaapplication7.model.TicTacToeGame;
/**
*
* #author Harshal
*/
public class NegaScout extends Strategy{
#Override
public Move makeMove(TicTacToeGame game) {
System.out.println("Negascout");
Move move = game.getAvaiableMoves().get(0);
int best = Integer.MIN_VALUE;
for(int i=0; i<game.getAvaiableMoves().size(); i++){
System.out.print(game.getAvaiableMoves().get(i) + ",");
}
System.out.println();
for (int i = 0; i < game.getAvaiableMoves().size(); i++) {
//int result = negaMax(game);
//TicTacToeGame tmp = game.clone();
//tmp.playMove(game.getAvaiableMoves().get(i));
int result = negaScout(game, Integer.MIN_VALUE, Integer.MAX_VALUE);
//System.out.println("for i = " + i + " : " + game.getAvaiableMoves().get(i) + " result : " + result);
System.out.printf("%d %d\n",best,result);
if (result > best) {
move = game.getAvaiableMoves().get(i);
best = result;
}
}
System.out.println();
return move;
}
private int negaScout(TicTacToeGame game, int a, int b){
if (Move.isWon(game.getCurrentPlayer().getMoves())) {
return 1;
}
if (Move.isWon(game.getNonCurrentPlayer().getMoves())) {
return -1;
}
//int score;
int score = Integer.MIN_VALUE;
for (int i = 0; i < game.getAvaiableMoves().size(); i++) {
//Move move = game.getAvaiableMoves().get(i);
//TicTacToeGame tmp = game.clone();
Move move = game.getAvaiableMoves().get(i);
TicTacToeGame tmp = game.clone();
tmp.switchPlayers();
tmp.playMove(move);
if(i==0){
score = -negaScout(tmp,-b,-a);
}else{
score = -negaScout(tmp, ((-a)-1), -a);
if(a<score && score<b)
score = -negaScout(tmp, -b, -score);
}
a = Math.max(a,score);
if(a >= b){
break;
}
}
return a;
}
}
I am trying to implement negascout for tic-tac-toe, but the alglorithm doesn't do anything.
It only chooses the first move in the set of available moves.
It returns values but i couldn't trace them.
Some help will be appreciated.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sim;
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import static jdk.nashorn.internal.objects.NativeMath.max;
/**
*
* #author admin
*/
public class Sim {
public String[][] bigramizedWords = new String[500][100];
public String[] words = new String[500];
public File file1 = new File("file1.txt");
public File file2 = new File("file2.txt");
public int tracker = 0;
public double matches = 0;
public double denominator = 0; //This will hold the sum of the bigrams of the 2 words
public double res;
public double results;
public Scanner a;
public PrintWriter pw1;
public Sim(){
intialize();
// bigramize();
results = max(res);
System.out.println("\n\nThe Bigram Similarity value between " + words[0] + " and " + words[1] + " is " + res + ".");
pw1.close();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Sim si=new Sim();
// TODO code application logic here
}
public void intialize() {
int j[]=new int[35];
try {
File file1=new File("input.txt");
File file2=new File("out.txt");
Scanner a = new Scanner(file1);
PrintWriter pw1= new PrintWriter(file2);
int i=0,count = 0;
while (a.hasNext()) {
java.lang.String gram = a.next();
if(gram.startsWith("question")|| gram.endsWith("?"))
{
count=0;
count-=1;
}
if(gram.startsWith("[")||gram.startsWith("answer")||gram.endsWith(" ") )
{
//pw1.println(count);
j[i++]=count;
count=0;
//pw1.println(gram);
//System.out.println(count);
}
else
{
// System.out.println(count);
count+=1;
//System.out.println(count + " " + gram);
}
int line=gram.length();
int sa_length;
//int[] j = null;
int refans_length=j[1];
//System.out.println(refans_length);
for(int k=2;k<=35;k++)
// System.out.println(j[k]);
//System.out.println(refans_length);
for(int m=2;m<=33;m++)
{
sa_length=j[2];
//System.out.println(sa_length);
for(int s=0;s<=refans_length;s++)
{
for(int l=0;l<=sa_length;l++)
{
for (int x = 0; x <= line - 2; x++) {
int tracker = 0;
bigramizedWords[tracker][x] = gram.substring(x, x + 2);
System.out.println(gram.substring(x, x + 2) + "");
//bigramize();
}
// bigramize();
}
}
}
bigramize();
words[tracker] = gram;
tracker++;
}
//pw1.close();
}
catch (FileNotFoundException ex) {
Logger.getLogger(Sim.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void bigramize() {
//for(int p=0;p<=sa_length;p++)
denominator = (words[0].length() - 1) + (words[1].length() - 1);
for (int k = 0; k < bigramizedWords[0].length; k++) {
if (bigramizedWords[0][k] != null) {
for (int i = 0; i < bigramizedWords[1].length; i++) {
if (bigramizedWords[1][i] != null) {
if (bigramizedWords[0][k].equals(bigramizedWords[1][i])) {
matches++;
}
}
}
}
}
matches *= 2;
res = matches / denominator;
}
}
I have tried the above code for bigramizing the words in the file "input.txt" i have got the result of bigram but i didnt get the similarity value.
for e.g:
input file contains as
answer:
high
risk
simulate
behaviour
solution
set
rules
[2]
rules
outline
high
source
knowledge
[1]
set
rules
simulate
behaviour
in the above example I have to compare the words under answer with every word under [2] as {high,rules} {high,outline} {high,high} {high,source} {high,knowledge} and I have to store the maximum value of the above comparison and again the second word from answer is taken and then similar process is taken. At last, mean of maximum value of each iteration is taken.
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.