I am creating a text-adventure game in Java in which the user enters commands such as 'H' for help or 'N' to move North. In certain cases, the user will need to enter something such as 'T key' to take a key that is in that room. So because of this I need to use the split method to split the command and the item that the user wants to take. I'm getting really stuck in the return part as in some cases the string returned will only be the command if they enter one letter and in other cases it will be both the command and item. All help is appreciated!
This is my code in the main class:
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
public class GameEngine {
private Scanner userInput = new Scanner(System.in);
private Player player1 = new Player("playerName", 0);
private int currentLocation = player1.currentRoom;
private boolean stillPlaying = true; //When this is true, the game continues to run
private Item[] items = {
new Item ("map","a layout of your house", 10 ),
//new Item ("battery", "a double A battery", 5),
new Item ("battery", "a double A battery", 5),
new Item ("flashlight", "a small silver flashlight", 10),
new Item ("key", "this unlocks some door in your house", 15),
};
//Locations {roomName, description, item}
private Locale[] locales = {
new Locale("bedroom","You see the outline of a bed with your childhood stuffed bear on it.",items[0]),
new Locale("hallway","A carpeted floor and long pictured walls lie ahead of you.",null),
new Locale("kitchen","The shining surface of your stove reflects the pale moonlight coming in the window over the sink.",items[1]),
new Locale("bathroom","You find yourself standing in front of a mirror, looking back at yourself.",items[2]),
new Locale("living room","You stub your toe on the sofa in the room, almost falling right into the TV.",null),
new Locale("dining room","You bump the china cabinet which holds your expensive dishes and silverware.",items[3]),
new Locale("office","The blinking light from the monitor on your desk can be seen in the dark",null),
new Locale("library","The smell of old books surrounds you.",null),
new Locale("basement","You reach the top of some stairs and upon descending down, you find the large metal generator.",null),
};
//Matrix for rooms
private int[][] roomMap = {
// N,E,S,W
{6,1,-1,-1}, //Bedroom (room 0)
{4,2,3,0}, //Hallway (room 1)
{-1,-1,5,1}, //Kitchen (room 2)
{1,-1,-1,-1}, //Bathroom (room 3)
{-1,7,1,-1}, //Living Room (room 4)
{2,-1,-1,-1}, //Dining Room (room 5)
{-1,-1,0,-1}, //Office (room 6)
{8,-1,-1,4}, //Library (room 7)
{-1,-1,7,-1} //Basement (room 8)
};
private BreadcrumbTrail trail = new BreadcrumbTrail();
//Move method
private String[] dirNames = {"North", "East", "South", "West"};
//Welcome Message
public void displayIntro(){
System.out.println("\tWelcome to Power Outage!");
System.out.println("=================================================");
System.out.print("\tLet's start by creating your character.\n\n\tWhat is your name? ");
//Will read what name is entered and return it
player1.playerName = userInput.nextLine();
System.out.println("\n\tHello, " +player1.playerName+ ". Let's start the game! \n\n\tPress any key to begin.");
System.out.print("=================================================");
//Will move to next line when key is pressed
userInput.nextLine();
System.out.println("\tYou wake up in your bedroom. \n\n\tThe power has gone out and it is completely dark.");
System.out.println("\n\tYou must find your way to the basement to start the generator.");
}
private void displayMoveInfo(){
System.out.println("\n\tMove in any direction by typing, 'N', 'S', 'E', or 'W'.");
System.out.println("\n\tTake an item from a room by pressing 'T'.");
System.out.println("\n\tTo go back to the room you were just in type 'B'.");
System.out.println("\n\tType 'H' at any time for help and 'Q' to quit the game. Good luck!");
System.out.println("\n\tPress any key.");
}
private void move(int dir) {
int dest = roomMap[currentLocation][dir];
if (dest >= 0 && dest != 8) {
System.out.println("=================================================");
System.out.println("\tYou have moved " + dirNames[dir]);
currentLocation = dest;
System.out.println("\n\tYou are in the "+locales[currentLocation].roomName+".");
System.out.println("\n\t"+locales[currentLocation].description);
Locale locale = locales[currentLocation];
itemPresent();
//Drop breadcrumb at current location
trail.dropCrumb(currentLocation);
}
//If the player reaches the basement and wins
else if (dest == 8){
System.out.println("\tCongratulations!! You have found the basement and turned on the generator! \n\n\tYou have won the game!");
System.out.println("\n\tTHANKS FOR PLAYING!!!!!!");
System.out.println("\n\tCopyright 2016 \n\n");
stillPlaying = false;
}
//If dest == -1
else {
System.out.println("\tThere is no exit that way, please try again.");
}
}//End of Move
private void itemPresent(){
Locale locale = locales[currentLocation];
if(locale.item != null){
System.out.println("\n\tThere is a " + locale.item + " in this room.");
}
else{
System.out.println("\n\tThere is no item in this room.");
}
}
public Command getCommandFromResponse(String response) throws IllegalArgumentException{
String[] split = response.split(" ");
if(split.length < 1){
throw new IllegalArgumentException("Invalid command.");
}
Command command = new Command(split[0]);
if(split.length >= 2) {
command.setItem(split[1]);
}
return command;
}
//All possible responses to keys pressed
public void processInput(){
displayMoveInfo();
Command userCommand = getCommandFromResponse(userInput.nextLine());
while(stillPlaying){
if(player1.currentRoom != 8 && !"Q".equalsIgnoreCase(userCommand.getCommand()) ){
//Map
if(userCommand.command.equalsIgnoreCase("M")){
//only print if the player has the map
//String[] inventory = player1.inventory;
int mapFoundAt = -1;
if(player1.inventory != null){
for(int i=0; i < player1.inventory.size(); i++){
Item checkItem;
checkItem = player1.inventory.get(i);
if(checkItem.itemName.equals("map")){
mapFoundAt = i;
break;
}
}
if(mapFoundAt >=0 ){
System.out.println("Here is your map: \n\n\t\t\tbasement\n\noffice\t living room\tlibrary\n\nbedroom\t hallway\tkitchen\n\n\t bathroom \tdining room");
}
else{
System.out.println("\tYou do not have the map in your inventory.");
}
}
else{
System.out.println("\tYou don't have any items in your inventory.");
}
break;
}//End of Map
//Take
else if(userCommand.command.equalsIgnoreCase("T")){
Locale locale = locales[currentLocation];
if(userCommand.command.equalsIgnoreCase("T")){
}
if(locale.item != null){
//-User must enter item name with the command
System.out.println("Enter the command and item you would like to take.");
userCommand = getCommandFromResponse(userInput.nextLine());
if(userCommand.command.equals(locale.item.itemName)){
//-add the item to the player's inventory
player1.inventory.add(locale.item);
System.out.println("\tA " + locale.item + " was added to your inventory");
if(locale.item.itemName.equals("map")){
System.out.println("\n\tTo view the map press 'M'.");
}
//-remove the item from the current location
locale.item = null;
System.out.println("\n\tYou can view your inventory by pressing 'I' or drop an item by pressing 'D'.");
//-Add the item's worth to the score and set the items worth to zero to prevent double scoring
player1.score += locale.item.value;
System.out.println(locale.item.value + " points have been added to your score.");
System.out.println("\n\tThis is your current score: "+player1.score);
}
else{
System.out.println("That item is not at this location.");
}
}
else{
System.out.println("There is no item to pick up here");
}
}//End of Take
//Help
else if(userCommand.command.equalsIgnoreCase("H")){
displayMoveInfo();
break;
}
//Inventory
else if(userCommand.command.equalsIgnoreCase("I")){
if(player1.inventory != null){
System.out.println("\tThese are the items in your inventory: "+player1.inventory+".");
}
else{
System.out.println("\tYou currently have no items in your inventory.");
System.out.println("\tTo pick up an item in a room, press 'T'.");
}
break;
}
//Drop
else if(userCommand.command.equalsIgnoreCase("D")){
//Show the list of items in the player's inventory with numbers associated with them
if(player1.inventory.size() != 0){
System.out.println("\tThese are the items available to drop: " +player1.inventory);
}
else if(player1.inventory.size() == 0){
System.out.println("\tYou have no items in your inventory to drop.");
break;
}
System.out.println("\tEnter the name of the item you would like to drop.");
String itemToDrop = userInput.nextLine();
Locale locale = locales[currentLocation];
if(locale.item == null){
for(int i=0; i < player1.inventory.size(); i++){
Item checkItem;
checkItem = player1.inventory.get(i);
if(checkItem.itemName.equalsIgnoreCase(itemToDrop)){
//Remove item entered from a player's inventory
System.out.println("\tYou have dropped the " +checkItem.itemName+ ".");
player1.inventory.remove(i);
//Place the item at the player's current location so it can be picked up again
locale.item = checkItem;
//Subtract five points from the player's score
player1.score -= 5;
System.out.println("\tFive points have been subtracted from your score.");
System.out.println("\n\tThis is your current score: "+player1.score);
}
else if(i==player1.inventory.size() && checkItem.itemName != itemToDrop){
System.out.println("\tThat is not an item in your inventory.");
break;
}
}
}
else{
System.out.println("\tThere is already an item at this location, you can't drop an item.");
}
break;
}//End of Drop
//Backtrack
else if(userCommand.command.equalsIgnoreCase("B")){
//Pick up breadcrumb
trail.pickupCrumb();
if(trail.hasMoreCrumbs() == false){
//Move to previous crumb
currentLocation = trail.currentCrumb();
System.out.println("\n\tYou are in the "+locales[currentLocation].roomName+".");
System.out.println("\n\t"+locales[currentLocation].description);
itemPresent();
}
//When the trail is empty, drop the last breadcrumb, don't move the player again
else{
trail.dropCrumb(currentLocation);
System.out.println("\tYou are at the beginning of your breadcrumb trail, you can't backtrack any more.");
}
break;
}//End of Backtrack
//North
else if(userCommand.command.equalsIgnoreCase("N")){
move(0);
break;
}
//East
else if(userCommand.command.equalsIgnoreCase("E")){
move(1);
break;
}
//South
else if(userCommand.command.equalsIgnoreCase("S")){
move(2);
break;
}
//West
else if(userCommand.command.equalsIgnoreCase("W")){
move(3);
break;
}
//If any key is pressed other than those above
else{
System.out.println("\tInvalid command!");
break;
}
}//End of Quit if statement
else if(userCommand.command.equalsIgnoreCase("Q")){
System.out.println("Thanks for playing!\n\n");
stillPlaying = false;
}
}//End of while
}//End of pressedKey method
public void play(){
displayIntro();
System.out.println("=================================================");
System.out.println("\tYou are in the bedroom.");
Locale locale = locales[currentLocation];
itemPresent();
trail.dropCrumb(currentLocation);
//This makes the game continue to loop
while(stillPlaying){
System.out.println("=================================================");
System.out.println("\tMove in any direction.");
processInput();
} //End of while
}
public static void main(String[] args) {
GameEngine game = new GameEngine();
game.play();
} //End of main
} //End of class
This is my Player Class:
import java.util.ArrayList;
public class Player {
//Player class must have name, location, inventory, and score
public String playerName;
public ArrayList<Item> inventory;
public int score;
public int currentRoom;
public Player(String playerName, int currentRoom){
this.playerName = playerName;
this.inventory = new ArrayList<Item>();
this.score = 0;
this.currentRoom = currentRoom;
}
}
This is the Command class:
class Command{
String command;
String item;
public Command(String comm){
command = comm;
}
public Command(String comm, String item){
this.command = comm;
this.item = item;
}
public void setCommand(String command){
this.command = command;
}
public void setItem(String item){
this.item = item;
}
public String getCommand(){
return this.command;
}
public String getItem(){
return this.item;
}
public String toString(){
return this.command + ":" + this.item;
}
}
This is my Locale class:
public class Locale {
//Locale must have name, description, and Item
public static int roomNumber;
public String roomName;
public String description;
public Item item;
public Locale(String roomName, String description, Item item){
this.roomName = roomName;
this.description = description;
this.item = item;
}
}
This is my Item class:
public class Item {
//item must have a name and a description (both strings)
public String itemName;
public String itemDes;
public boolean isDiscovered;
public int value;
public Item (String itemName, String itemDes, int value){
this.itemName = itemName;
this.itemDes = itemDes;
this.isDiscovered = false;
this.value = value;
}
public String toString(){
return itemName + "(" + itemDes + ")";
}
}
This is my BreadcrumbTrail class:
public class BreadcrumbTrail {
//dropCrumb (push)
//pickupCrumb (pop)
//currentCrumb (peek)
//hasMoreCrumbs (empty)
//Drop a new breadcrumb whenever the player arrives at a local
class Node{
int data;
Node link;
Node(int s, Node l){
this.data = s; //element stored at the node
this.link = l; //link to another node
}
}//End of Node class
private Node currentCrumb;
//Constructor
public BreadcrumbTrail(){
this.currentCrumb = null;
}
//pop
public void pickupCrumb(){
this.currentCrumb = this.currentCrumb.link;
}
//push
public void dropCrumb(int s){
Node newNode = new Node(s, this.currentCrumb);
this.currentCrumb = newNode;
}
//top or peek
public int currentCrumb(){
return this.currentCrumb.data;
}
//isEmpty
public boolean hasMoreCrumbs(){
return this.currentCrumb == null;
}
}
In the pressedkey method now the if else statements obviously don't work as I now need to change the part in front of .equals.
All previous answers are decent. However, I think you are better off validating the user input and if the user enters the incorrect number of objects, throw an exception to indicate invalid input instead of just logging it. It makes the code more manageable, reads better, and give you an opportunity to deal with invalid input properly:
public Command getCommandFromResponse(String response) throws IllegalArgumentException{
String[] split = response.split(" ");
if(split.length < 1){
throw new IllegalArgumentException("Invalid command.");
}
if(split.length < 2){
throw new IllegalArgumentException("You must enter an item.");
}
return new Command(split[0], split[1]);
}
class Command{
String command;
String item;
public Command(){
command = null;
item = null;
}
public Command(String comm, String item){
this.command = comm;
this.item = item;
}
public void setCommand(String command){
this.command = command;
}
public void setItem(String item){
this.item = item;
}
public String getCommand(){
return this.command;
}
public String getItem(){
return this.item;
}
public String toString(){
return this.command + ":" + this.item;
}
}
Create a class like this:
class UserInput {
private String command;
private String item;
public UserInput() {
command = "";
item = "";
}
public void setCommand(String command) {
this.command = command;
}
public void setItem(String item) {
this.item = item;
}
}
And return an instance of it.
String response = userInput.nextLine();
String[] split = response.split(" ");
UserInput input = new UserInput();
if (split.length > 0) {
input.setCommand(split[0]);
if (split.length == 2) {
input.setItem(split[1]);
}
return input;
}
System.out.println("Invalid command");
return null;
Scanner userInput = new Scanner(System.in);
String response = userInput.nextLine();
String command = null;
String item = null;
String[] split = response.split(" ");
if (split.length == 1) {
command = split[0];
} else if (split.length == 2) {
command = split[0];
item = split[1];
} else {
System.out.println("Invalid command");
}
System.out.println(command + "/" + item);
userInput.close();
if user input contains only command, then don't run the loop. Move your
if(split.length == 0){
String command = split[0];
return command;
}
before the loop.
String response = userInput.nextLine();
String[] split = response.split(" ");
if(split.length == 0){
String command = split[0];
return command;
}
for(int i=0; i < split.length; i++){
//use simple java class to store the result
if(split.length == 1){
String item = split[1];
return item;
}
else{
System.out.println("Invalid command");
}
}
Related
I am a beginner in Java, and I've been creating a practicing project for a game. For this purpose, I've already put some features in this project, and I separate the entire project into three files: Nimsys, NimPlayer, NimGame.
I've created these features.
addplayer into playerList in the NimPlayer.
removeplayer
editplayer
Now, I want two of the players to join the game, and do the following:
Score record
The times the player has played.
What I did was trying to store the user data (addplayer) from the prompt input, and brought the game to be played (last part of the incomplete code).
import java.util.Scanner;
public class Nimsys {
public static String[] splitName(String inName) {
String[] splittedLine = inName.split(",");
String[] name = null;
if (splittedLine.length==3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
name = new String[3];
name[0] = userName;
name[1] = familyName;
name[2] = givenName;
}
return name;
}
public static String [] splitData(String dataIn) {
String[] splittedLine = dataIn.split(",");
String[] data = null;
if (splittedLine.length==4) {
String initialStone = splittedLine[0];
String stoneRemoval = splittedLine[1];
String player1 = splittedLine[2].trim();
String player2 = splittedLine[3].trim();
data = new String[4];
data[0] = initialStone;
data[1] = stoneRemoval;
data[2] = player1;
data[3] = player2;
}
return data;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
System.out.print('$');
String commandin = in.next();
if (commandin.equals("addplayer")) {
String inName = in.nextLine();
String[] name = splitName(inName);
//Make sure the vadality of in name
if (name!=null && name.length==3) {
for (int i = 0; i < NimPlayer.getId(); i ++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName();
if (userCheck.contains(name[0])) {
System.out.println("The player already exist");//Test if player has been created
}
}
NimPlayer.createPlayer(name[0], name[1], name[2]);
System.out.println("The player has been created.");
} else {
System.out.println("Not Valid! Please enter again!");
}
}
if (commandin.equals("removeplayer")) {
//cannot loop through the entire null array, would be NullPointerException
String removeUserName = in.nextLine().trim();
/*System.out.println("Are you sure you want to remove all players? (y/n) \n");
//System.out.print('$');
commandin = in.next();
if (commandin.equals("y")) {
for (int i = 0; i < NimPlayer.getId(); i++) {
NimPlayer.getPlayer()[i] = null;
System.out.println("Remove all the players");
}
} else {
System.out.print('$');
}*/
//commandin = in.next();
for (int i = 0; i < NimPlayer.getId(); i++) {
String userName = NimPlayer.getPlayer()[i].getUserName().trim();
if (removeUserName != null && userName.equals(removeUserName)) {
NimPlayer.getPlayer()[i] = null;
System.out.println("Remove successfully!");// A test to see if the code runs
} else {
System.out.println("The player does not exist");
}
}
}
if (commandin.equals("editplayer")) {
String inName = in.nextLine();
String[] splittedLine = inName.split(",");
if (splittedLine!=null && splittedLine.length==3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
//System.out.println(userName+","+familyName+","+givenName);//Test if in name in the if loop
for (int i = 0; i < NimPlayer.getId(); i++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName().trim();
if (userName != null && userCheck.equals(userName)) {
NimPlayer.getPlayer()[i].setFamilyName(familyName);
NimPlayer.getPlayer()[i].setGivenName(givenName);
System.out.println("Edit successfully");
} else {
System.out.println("The player does not exist.");
}
}
} else {
System.out.println("Invalid in! Please enter again.");
}
}
if (commandin.equals("displayplayer")) {
for (int i = 0; i < NimPlayer.getId(); i++) {
String userName = NimPlayer.getPlayer()[i].getUserName();
String familyName = NimPlayer.getPlayer()[i].getfamilyName();
String givenName = NimPlayer.getPlayer()[i].getGivenName();
System.out.println(userName+","+familyName+""+givenName);
}
}
if (commandin.equals("startgame")) {
String dataIn = in.nextLine();
String [] data = splitData(dataIn);
//Check if player in the array
if (data.length==4 && data !=null) {
for (int i = 0; i < NimPlayer.getId(); i++) {
for (int j = i + 1; j < NimPlayer.getId(); j++) {
String player1 = NimPlayer.getPlayer()[i].getUserName();
String player2 = NimPlayer.getPlayer()[j].getUserName();
if (player1==null || player2==null) {
System.out.println("One of the players does not exist. Please enter again");
} else {
System.out.println("Data built successfully.Game starts!");
break;
}
}
}
dataIn = in.nextLine();
}
int dataStone = Integer.parseInt(data[0]);
int dataRemoval = Integer.parseInt(data[1]);
}
}}
//username, given name, family name, number of game played, number of games won
public class NimPlayer {
private String userName;
private String familyName;
private String givenName;
static NimPlayer[] playerList = new NimPlayer[10]; // set an array here
static int id;
//define NimPlayer data type
public NimPlayer(String userName,String surName, String givenName) {
this.userName = userName;
this.familyName = surName;
this.givenName = givenName;
}
// create new data using NimPlayer data type
public static void createPlayer(String userName, String familyName, String givenName) {
if (id<10) {
playerList[id++] = new NimPlayer(userName, familyName, givenName);
} else {
System.out.println("Cannot add more players.");
}
}
public static int getId() {
return id;
}
public static NimPlayer [] getPlayer() {
return playerList;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getUserName() {
return userName;
}
public String getfamilyName() {
return familyName;
}
public String getGivenName() {
return givenName;
}
}
Above are my Nimsys and NimPlayers class. So far, I have a question:
Is it wrong to manipulate the players in the Nimplayer?
Or it is better to create an object in Nimsys if I want to store the record and the times game played?
public class NimGame {
int stoneBalance;
int stars;
public int initializeStone(int startStones) {
stoneBalance = startStones;
return stoneBalance;
}
public void removeStones(int stonesTaken) {
int updatedBalance = stoneBalance - stonesTaken;
stoneBalance = updatedBalance;
}
public void printStar(int star) {
stars = star;
stars = stoneBalance;
for (int stars = 1; stars <= star; stars++) {
System.out.print(" *");
}
System.out.println();
}
Scanner in = new Scanner(System.in);
String playOrNot;
do {
System.out.println("Initial stone count: "+datastone);
System.out.println("Maximum stone removal: "+dataRemoval);
System.out.println("Player 1: "+player1.getUserName());
System.out.println("Player 2: "+player2.getUserName());
// while stoneBalance > 0, two players keep playing the game
while (stoneBalance > 0) {
System.out.print(initialStone + " stones left:");
printStar(initialStone);
// player1's turn and remove the stones; decision of winning
System.out.println(player1 + "'s turn - remove how many?\n");
int takeStone = in.nextInt();
while (takeStone > dataRemoval || takeStone <= 0) {
System.out.println(
"Invalid, you need to remove stones under upper "+
"bound limit or above 0. \n Please enter again.");
takeStone = in.nextInt();
}
removeStones(takeStone); //remove the stone
if (stoneBalance > 0) {
//show the remaining stones
System.out.print(stoneBalance + " stones left:");
printStar(stoneBalance);
} else if (stoneBalance <= 0) {
System.out.println("Game Over\n" + player2 + " wins!\n");
break;
}
// player2's turn and remove the stones; decision of winning
System.out.println(player2 + "'s turn - remove how many?\n");
takeStone = in.nextInt();
while (takeStone > dataRemoval || takeStone <= 0) {
System.out.println(
"Invalid, you need to remove stones under upper " +
"bound limit or above 0. \n Please enter again.");
takeStone = in.nextInt();
}
removeStones(takeStone);
if (stoneBalance > 0) {
System.out.print(stoneBalance + " stones left:");
printStar(stoneBalance);
} else if (stoneBalance <= 0) {
System.out.println("Game Over\n" + player1 + " wins!\n");
break;
}
}
// ask players to play again
in.nextLine();
System.out.println("Do you want to play again (Y/N):");
playOrNot = in.nextLine();
} while (playOrNot.equals("Y"));
}
And this above is my NimGame class. It's the process of the classical Nim game. What should I do to introduce the player? What I did in Nimsys is only to check if players are inside the playerList.
Thanks for taking the time to review my code. Any help is highly appreciated!
On a side note (because it won't affect the execution of the program), the name of an identifier should be self-explanatory e.g. your getPlayer method should be named as getPlayerList as it is returning the playerList, not a single player.
Your logic for startgame should be as follows:
if (commandin.equals("startgame")) {
String dataIn = null, player1 = null, player2 = null;
do {
dataIn = in.nextLine();
String [] data = splitData(dataIn);
//Check if player in the array
if (data !=null && data.length==4) {
NimPlayer[] players = NimPlayer.getPlayerList();
for (int i = 0; i < players.length; i++) {
if(players[i].getUserName().equals(data[2])) {// Checking player1
player1 = players[i].getUserName();
break;
}
}
for (int i = 0; i < players.length; i++) {
if(players[i].getUserName().equals(data[3])) {// Checking player2
player2 = players[i].getUserName();
break;
}
}
}
} while(player1 == null || player2 == null)
//...
}
You can put the repeated code in a function to make your program modular e.g.
String findPlayerByName(String name){
String player = null;
NimPlayer[] players = NimPlayer.getPlayerList();
for (int i = 0; i < players.length; i++) {
if(players[i].getUserName().equals(name)) {
player = players[i].getUserName();
break;
}
}
return player;
}
Then, the logic for startgame will reduce to:
if (commandin.equals("startgame")) {
String dataIn = null, player1 = null, player2 = null;
do {
dataIn = in.nextLine();
String [] data = splitData(dataIn);
//Check if player in the array
if (data !=null && data.length==4) {
player1 = findPlayerByName(data[2]);
player2 = findPlayerByName(data[3]);
}
} while(player1 == null || player2 == null)
//...
}
Another thing I would like you to understand is the problem with the following line:
if (data.length==4 && data !=null)
It should be
if (data !=null && data.length==4)
This way, if data is null, the condition, data.length==4 will not be checked because && operator allows to proceed further only if the condition on its left side evaluates to true.
The problem with your line is that if data is null, you will get the NullPointerException because you will be checking .length on a null reference.
Now, I want two of the players to join the game, and do the following:
Score record
The times the player has played.
Currently, you have userName, familyName, and givenName attributes in NimPlayer class. You need to create two more attributes, private int score and private int numbersOfGamesPlayed with their public getters and setters. You need to use these attributes to store the value of score and the numbers of time a player has played the game.
I'm making a reservation feature for my events, and I can successfully add the attendee, however when I want to display the details for every attendee, it gives me a ArrayIndexOutOfBounds exception error, which I'm not quite sure how to fix.
Main.java
private static Scanner sc = new Scanner(System.in);
private static int eventCreationLimit = 5;
private static Event[] events = new Event[eventCreationLimit];
private static int eventsCreated;
public static void main(String args[]) {
String input;
// Main menu.
do {
System.out.println("\n~ BOOKING SYSTEM ~");
System.out.println("------------------");
System.out.println("A. Schedule an Event");
System.out.println("B. Add an Attendee");
System.out.println("C. View Reservations");
System.out.println("X. Exit\n");
System.out.print("Select an option: ");
input = sc.nextLine();
switch (input.toUpperCase()) {
case "A":
scheduleAnEvent();
break;
case "B":
addAttendee();
break;
case "C":
displayReservations();
break;
case "X":
System.out.println("INFO: You have exited the booking system.");
break;
default:
System.out.println("ERROR: Invalid input!");
}
} while (!input.equalsIgnoreCase("X"));
}
private static void scheduleAnEvent() {
System.out.println("\n~ SCHEDULE A EVENT ~");
System.out.println("--------------------");
System.out.print("Enter the ID: ");
String ID = sc.nextLine();
...
System.out.print("Enter the attendee limit: ");
int attendeeLimit = Integer.parseInt(sc.nextLine());
// Add the new event to the array.
events[eventsCreated++] = new Event(ID, ..., attendeeLimit, attendeeLimit, ...);
for (int i = 0; i < eventsCreated; i++)
// Set the places available for the specific event being created to subtract it later when an attendee is added.
if (ID.equals(events[i].getID()))
// The number of places available left in the event can be displayed by going to "B. View All Events".
events[i].setPlacesAvailable(attendeeLimit);
// Give the user a confirmation message.
System.out.println("\nINFO: Sucessfully created Event: " + ID + ".");
}
private static void addAttendee() {
Event event = null;
boolean result = false;
System.out.println("\n~ ADD AN ATTENDEE ~");
System.out.println("-------------------");
System.out.print("Enter attendee name: ");
String name = sc.nextLine();
System.out.print("Enter attendee phone number: ");
String phone = sc.nextLine();
Attendee a = new Attendee(name, phone);
System.out.print("Enter event ID: ");
String eventID = sc.nextLine();
// Check if the given ID matches an event.
for (int i = 0; i < eventsCreated; i++)
if (events[i].getID().equals(eventID))
event = events[i];
if (event != null) {
if (event.getID().equals(eventID)) {
result = ((Event) event).addAttendee(a);
if (result) {
// If the event has enough room, then add the attendee.
System.out.println("INFO: Attendee successfully added to Event: " + eventID + ".");
displayReservations();
}
else
// If the event is full, then the attendee will not be added.
System.out.println("ERROR: The Event: " + eventID + " is full, the attendee could not be added.");
} else
System.out.println("ERROR: The given ID does not match any existing event.");
} else
System.out.println("ERROR: The event was not found.");
}
private static void displayReservations() {
System.out.println("\n~ RESERVATIONS ~");
System.out.println("----------------");
String pattern = "%-18s %-18s %-22s %-1s\n";
System.out.printf(pattern, "NAME", "PHONE", "EVENT ID", "FEE");
System.out.println("----------------------------------------------------------------");
// Display all reservations for events.
for (int i = 0; i < events[i].getAttendeeCount(); i++)
events[i].displayReservations();
}
Event.java
...
private String ID;
private int attendeeLimit;
private int attendeeCount;
private int placesAvailable;
private Attendee[] a = new Attendee[attendeeCount];
public Demonstration(..., String ID, int placesAvailable, int attendeeLimit, ...) {
this.ID = ID;
this.placesAvailable = placesAvailable;
this.attendeeLimit = attendeeLimit;
}
public String getID() { return this.ID; }
public int getPlacesAvailable() { return this.placesAvailable; }
public int getAttendeeLimit() { return this.attendeeLimit; }
public void setPlacesAvailable(int placesAvailable) { this.placesAvailable = placesAvailable; }
public boolean addAttendee(Attendee at) {
// Proceed to add the attendee if there is enough room.
if (attendeeCount <= placesAvailable) {
attendeeCount++;
// Decrease the number of places available by one.
setPlacesAvailable(placesAvailable - 1);
return true;
}
return false;
}
public void displayReservations() {
System.out.println("ID: " + ID);
if (attendeeCount > 0)
for (int i = 0; i < attendeeCount; i++)
a[i].attendeeDetails();
}
Attendee.java
private String name;
private String phone;
public Attendee(String name, String phone) {
this.name = name;
this.phone = phone;
}
public String getName() { return this.name; }
public String getPhone() { return this.phone; }
public void attendeeDetails() {
System.out.println("Name: " + name);
System.out.println("Phone: " + phone);
}
The above code gives me a ArrayIndexOutOfBoundsException error in the displayReservations() method (a[i].attendeeDetails()) whenever I try to add an attendee to an event.
Problem: How do I display all reservation details for all events? Thank you for your help!
EDIT
The error:
Index 0 out of bounds for length 0.
There are a couple of issues with your code:
You are maintaining an attendeeCount separately than the size of the Attendee[], but in your addAttendee() method, you never actually add the new Attendee to the array
Because Attendee[] is an array, it can't grow larger than the size when first initialized. If you want to use an array, instead of an ArrayList that can grow dynamically, you need to initialize the array to the maximum size: placesAvailable:
So, my recommendation would be to switch from using an array to an ArrayList by importing java.util.Arraylist, changing the declaration of the Attendee[] to an ArrayList, and updating the rest of the Event.java code to use the ArrayList, as well as making sure you add the new Attendee in the addAttendee() method. Finally, you don't need to maintain the attendee count separately, just ask the attendees ArrayList it's current size.
Event.java
...
import java.util.*; //You can import all java.util classes
private String ID;
private int attendeeLimit;
private int placesAvailable;
private List<Attendee> attendees = new ArrayList<>(); //Initialize the attendees ArrayList
public Demonstration(..., String ID, int placesAvailable, int attendeeLimit, ...) {
this.ID = ID;
this.placesAvailable = placesAvailable;
this.attendeeLimit = attendeeLimit;
}
public String getID() { return this.ID; }
public int getPlacesAvailable() { return this.placesAvailable; }
public int getAttendeeLimit() { return this.attendeeLimit; }
public void setPlacesAvailable(int placesAvailable) { this.placesAvailable = placesAvailable; }
public boolean addAttendee(Attendee at) {
// Proceed to add the attendee if there is enough room.
if (attendeeCount <= placesAvailable) {
attendees.add(at); //Make sure you add the new Attendee to the list
// Decrease the number of places available by one.
setPlacesAvailable(placesAvailable - 1);
return true;
}
return false;
}
public void displayReservations() {
System.out.println("ID: " + ID);
int attendeeCount = attendees.size(); //Calculate the number of Attendees
if (attendeeCount > 0)
for (int i = 0; i < attendeeCount; i++)
attendees.get(i).attendeeDetails();
}
attendeCount does not have a value as at the time you creating the Array "a". For what you are trying to achieve, I suggest:
i. Use an Arraylist.
ii. Initialize you array in the constructor to attendeLimit.
If possible, I also suggest you use parameter methods where neccessary.
I am having trouble finishing this problem. I cannot get the console to print the names in the problem. This is a program that creates a roshambo game.
Here is my code.
public enum Roshambo {
rock {
public String toString() {
return "rock";
}
},
paper {
public String toString() {
return "paper";
}
},
scissors {
public String toString() {
return "scissors";
}
}
}
public abstract class Player {
String name;
Roshambo value;
abstract Roshambo generateRoshambo();
void setName(String name) {
this.name = name;
}
void setRoshambo(Roshambo value) {
this.value = value;
}
String getName() {
return name;
}
Roshambo getRoshambo() {
return value;
}
}
class Bart extends Player {
public Roshambo generateRoshambo() {
super.name = "Bart";
return Roshambo.rock;
}
}
public class Lisa extends Player {
public Roshambo generateRoshambo() {
super.name = "Lisa";
Random r = new Random();
int ch = r.nextInt(3);
if (ch == 0) return Roshambo.rock;
else if (ch == 1) return Roshambo.paper;
else return Roshambo.scissors;
}
}
public class Player1 extends Player {
char value;
Player1(char value) {
this.value = value;
}
public Roshambo generateRoshambo() {
if (value == 'r')
return Roshambo.rock;
else if (value == 's')
return Roshambo.scissors;
else
return Roshambo.paper;
}
}
import java.util.Scanner;
public class RoshamboApp {
public static void main(String args[]) {
char choice = 'y';
char player;
Scanner s = new Scanner(System.in);
System.out.println("Welcome to the game of Roshambo");
Bart b = new Bart();
Lisa l = new Lisa();
Player p = null;
String name;
System.out.println("Enter your name : ");
name = s.next();
System.out.println("Would you like to play Bart or Lisa?(B/L):");
player = s.next().charAt(0);
if (player == 'b')
p = b;
else if (player == 'l')
p = l;
while (choice != 'n') {
System.out.println("Rock, paper or scissors?(R/P/S)");
char ch = s.next().charAt(0);
Player1 p1 = new Player1(ch);
System.out.println(name + ":" + p1.generateRoshambo());
System.out.println(player + ":" + p.generateRoshambo());
if (p1.generateRoshambo() == p.generateRoshambo())
System.out.println("Draw!");
else if (p1.generateRoshambo() == Roshambo.paper && p.generateRoshambo() == Roshambo.rock)
System.out.println(p1.getName() + "Wins");
else if (p1.generateRoshambo() == Roshambo.paper && p.generateRoshambo() == Roshambo.scissors)
System.out.println(p.getName() + "Wins!");
else if (p1.generateRoshambo() == Roshambo.scissors && p.generateRoshambo() == Roshambo.rock)
System.out.println(p.getName() + "Wins");
System.out.println("Play again?(y/n):");
choice = s.next().charAt(0);
}
}
}
The console prints out like this:
Welcome to the game of Roshambo
Enter your name :
sean
Would you like to play Bart or Lisa?(B/L):
b
Rock, paper or scissors?(R/P/S)
paper
sean:paper
b:rock
nullWins
Play again?(y/n):
I am trying to get the b:rock to become Bart: rock and null wins to become sean wins.
First of all, there is overly complicated code around, like here:
public enum Roshambo {
ROCK("rock"), ... other constants ;
private final String stringRepresentation;
private Roshambo(String stringRepresentation) {
this.stringRepresentation = stringRepresentation;
}
#Override
public String toString() { return stringRepresentation; }
for example.
Regarding your actual problem in main: your Player1 class again is 10 times more complicated than required. Simply ask the user: "what do you want to play"; and depending on his input, select a Roshambo.
In other words: I would recommend you to
Change your Player class to ComputerPlayer to indicate that this one is somehow computing a Roshambo value
Change your Player1 class into a UserPlayer or something alike.
Long story short: your main problem is that you are doing things too complicated. So you can't focus on the problem you try to solve. Another example; you could change the selection of the computer player like
char playerSelection = ... coming from user
if (playerSelection == 'b') {
player = new Bart();
} else {
player = new Lisa();
}
Those single-char named variables dont say anything; they just help to confuse what you intend to do.
Your issue is you are printing player, which is just the character of the player they want to play:
player = s.next().charAt(0);
...
System.out.println(name + ":" + p1.generateRoshambo());
System.out.println(player + ":" + p.generateRoshambo());
you should print the players name:
System.out.println(p.getName() + ":" + p.generateRoshambo());
Note
This code is overly complicated, the same task can be done in fewer lines of code and much clearer. Look into refactoring.
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;
}
}
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.