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.
So I have seen alot of similar questions to this one but can't seem to find the answer so sorry if this is a duplicate. So I am creating a java program for black jack that I would like to have a system in place to save the chips the user has. I can get it to work but whenever I try to get it to save it just seems to overwrite what was already previously there.
Example
User enters there name: Bob
The system automatically knows there chips so when they press the button to save game it writes there name and chips like so...
Bob
200 (or however many chips they have)
The problem comes up when a new user enters there name and saves so say sally was saving instead of going
Bob
200
Sally
300
It does
Sally
300
And completly deletes bob
public void newSave(String user){
this.user = user;
user = user;
String Chip = Integer.toString(chips);
try{
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(user);
fileWriter.write("\n");
fileWriter.write(Chip);
fileWriter.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
Here is my code that I have that is where my issue lies.
Here is the whole code of the program method.
import java.util.*;
import java.io.*;
class BlackJackPlayer{
//Keep the data secure by using private
private String hand;
private String user;
private int betNum;
private int sum;
private int numAces;
private int chips = 100;
private String bet;
private static Random gen = new Random();
private String result = "";
public String Win = "Win", Lose = "Lose", Split = "Split";
private final int ACE = 1;
private final int JACK = 11;
private final int QUEEN = 12;
private final int KING = 13;
//Scanner for fileIn
Scanner fileIn;
//File For Saves!
File file = new File("Saves.txt");
//Array For Saves!
private ArrayList<String> User = new ArrayList<>();
private ArrayList<Integer> Chips = new ArrayList<>();
//constructor
public BlackJackPlayer(){
hand = "";
sum = 0;
numAces = 0;
//Create a file if save file does not exist//
try{
if (file.createNewFile()){
System.out.println("Save File Created!");
}
else{
//Say Nothing//
}
}//End Try
catch(Exception e){
System.out.println(e.getMessage());
}
//End File Create//
//Read File //
try{
fileIn = new Scanner(new FileReader(file, true));
while(fileIn.hasNext()){
User.add( fileIn.nextLine().trim() );
Chips.add( fileIn.nextInt() );
}//End While
fileIn.close();
}//End Try
catch(Exception e){
System.out.println(e.getMessage());
}//End Catch
//End Read File//
}//End public
//checkSaveStatus//
//See if save exists already in text than send to proper scenario//
public boolean checkSaveStatus(String user){
for(String u: User){
if (user == u){
return true;
}//end if
}//end for
return false;
}//end checkSaveStatus
//End checkSaveStatus//
//overWriteSave if save already exists//
public void overWriteSave(String user){
}//end overWriteSave
//End overWriteSave//
//newSave scnenario if save dosent exist//
public void newSave(String user){
this.user = user;
user = user;
String Chip = Integer.toString(chips);
try{
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(user);
fileWriter.write("\n");
fileWriter.write(Chip);
fileWriter.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
public boolean checkBet(String bet, int chips){
this.bet = bet;
int betNum = Integer.parseInt(bet);
if(betNum <= chips){
return true;
}
return false;
}
public String setBet(String bet){
this.bet = bet;
betNum = Integer.parseInt(bet);
return "You Bet: " + betNum;
}
public String updateChips(){
chips -= betNum;
return "You have: " + chips + " chips";
}
//Getter for hand variable
public String getHand(){
return hand;
}
public String setHand(){
hand = " ";
return hand;
}
//Getter for sum variable
public int getSum(){
return sum;
}
public void hit(){
//local variable
int currentCard = gen.nextInt(13) + 1;
if(currentCard > ACE && currentCard < JACK){
sum += currentCard;
hand += currentCard + " ";
}
else if(currentCard == ACE){
sum += 11;
numAces++;
hand += "A ";
}
else if(currentCard == QUEEN){
sum += 10;
hand += "Q ";
}
else if(currentCard == QUEEN){
sum += 10;
hand += "Q ";
}
else if(currentCard == KING){
sum += 10;
hand += "K ";
}//Ends Else If
//Is Ace 1 or 11
if(sum > 21 && numAces > 0){
numAces--;
sum -= 10;
}
}//ENDS HIT
public void stand(){
sum = sum;
return;
}//ends stand
public String getWin(BlackJackPlayer other) {
if(sum > 21){
result = Win;
}
else if(sum < other.getSum()){
result = Lose;
}
else if(sum == other.getSum()){
result = Split;
}
return result;
}
}//end class
Use following code.
FileWriter fileWriter = new FileWriter(file, true);
Here true signifies that you want to append data to existing file.
For more details : https://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.io.File,%20boolean)
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");
}
}
I have a problem, I am not looking for answers to my problem I would like some help finding why my array even though specified in main unders switch: case1, case2, case3. I used a for loops with an array that stops at the 5th iteration. However when I run the program it only runs once, am I specifying correctly to make it run 5 times or should it be declared another way? thanks in advance. I should also include there are no errors reported by eclipse at this time until it is ran and only after the first input.
The text files contains
##B##
#---#
#-M-#
#---#
##B##
##B##########
#-----------#
#-----------#
#-----------B
#-----------#
#------M----#
#-----------#
#-----------#
#-----------#
#-----------#
#-----------#
#-----------#
#############
##B#####
#------#
#-M----#
#------#
#------#
#------#
#------#
#####B##
The island maps can be found here
[http://rapidshare.com/share/9704FE33EFF98F1C1E71F6F1DF2DC0D4]
This is the array (int i=0;i<5;i++) however I do not think this is the problem, I can also provide the text files if needed
This is the console out
CS1181 Mouse Island
1. mouseIsland1.txt
2. mouseIsland2.txt
3. mouseIsland3.txt
9. Exit
Please make your selection: 2
Filename: mouseIsland2.txt
Bridge1: 0,0
Bridge2: 0,0
Mouse: 0,0
OUCH! The Mouse fell into the water and died at: 1|1
01
0100000000000
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at MouseEscape.runMouseIsland(MouseEscape.java:349)
at MouseEscape.main(MouseEscape.java:71)
End console
import java.io.File;
import java.util.Scanner;
public class MouseEscape {
public static Scanner input = new Scanner(System.in);
public static MouseEscape island1;
public static MouseEscape island2;
public static MouseEscape island3;
private String islandTxt;
private boolean moveDebug;
private int mouseEscaped;
private int mouseDrowned;
private int mouseStarved;
private int islandRows;
private int [] islandCols;
private int runCount;
private int [][] mousePosition;
private int [][] bridgePosition;
private int [][] islandIntArray;
private char [][] islandCharArray;
// main
// Allows the user to select which mouse island map to simulate
public static void main(String[] args) throws Exception
{
System.out.println("CS1181 Mouse Island");
int choice = 0, continueRun = 1;
boolean runResponce = false, correctInput = false;
while (continueRun == 1)
{
System.out.print("\n 1. mouseIsland1.txt"
+ "\n 2. mouseIsland2.txt"
+ "\n 3. mouseIsland3.txt"
+ "\n 9. Exit\n\nPlease make your selection: ");
continueRun = 9;
runResponce = false;
while (correctInput == false){
while (!input.hasNextInt()) {
input.next();
System.out.print("Enter a number 1-3 or 9 to exit.\nPlease make your selection: ");
}
choice = input.nextInt();
if (choice>=1 && choice <=3 || choice == 9){
correctInput = true;
break;
}
}
switch(choice)
{
case 1:
MouseEscape island1 = new MouseEscape("mouseIsland1.txt");
System.out.println("\nFilename: "+island1.getIslandTxt()
+"\nBridge1: "+island1.getBridgePosition(0,0)+","+island1.getBridgePosition(0,1)
+"\nBridge2: "+island1.getBridgePosition(1,0)+","+island1.getBridgePosition(1,1)
+"\nMouse: "+island1.getMousePosition(1,0)+","+island1.getMousePosition(1,1)+"\n");
//island1.drawCharIsland();
for (int i=0;i<5;i++) island1.runMouseIsland();
island1.printIslandStats();
correctInput=false; continueRun=1; break;
case 2:
MouseEscape island2 = new MouseEscape("mouseIsland2.txt");
System.out.println("\nFilename: "+island2.getIslandTxt()
+"\nBridge1: "+island2.getBridgePosition(0,0)+","+island2.getBridgePosition(0,1)
+"\nBridge2: "+island2.getBridgePosition(1,0)+","+island2.getBridgePosition(1,1)
+"\nMouse: "+island2.getMousePosition(1,0)+","+island2.getMousePosition(1,1)+"\n");
//island1.drawCharIsland();
for (int i=0;i<5;i++) island2.runMouseIsland();
island2.printIslandStats();
correctInput=false; continueRun=1; break;
case 3:
MouseEscape island3 = new MouseEscape("mouseIsland3.txt");
System.out.println("\nFilename: "+island3.getIslandTxt()
+"\nBridge1: "+island3.getBridgePosition(0,0)+","+island3.getBridgePosition(0,1)
+"\nBridge2: "+island3.getBridgePosition(1,0)+","+island3.getBridgePosition(1,1)
+"\nMouse: "+island3.getMousePosition(1,0)+","+island3.getMousePosition(1,1)+"\n");
//island1.drawCharIsland();
for (int i=0;i<5;i++) island3.runMouseIsland();
island3.printIslandStats();
correctInput=false; continueRun=1; break;
}
if (runResponce == false)
{
if (continueRun == 1)
{
runResponce = true;
correctInput = false;
}
}
}
input.close();
}
// MouseIslandClass
// Constructs a mouseIslandClass without specifying which mouseIsland to load
public MouseEscape() {
islandTxt = "";
mouseEscaped = 0;
mouseDrowned = 0;
mouseStarved = 0;
islandRows = 0;
runCount = 0;
mousePosition = null;
bridgePosition = null;
islandIntArray = null;
islandCharArray = null;
}
// MouseIslandClass
// Constructs a mouseIslandClass given a mouseIsland map name
public MouseEscape(String _islandTxt) throws Exception{
islandTxt = _islandTxt;
loadIsland();
}
// setIslandTxt
// Sets the mouseIsland filename for the current mouseIsland
public void setIslandTxt(String _islandTxt) throws Exception{
islandTxt = _islandTxt;
}
// getIslandTxt
// Gets the mouseIsland filename for the current mouseIsland
public String getIslandTxt(){
return islandTxt;
}
// getMouseEscaped
// Returns the total number of times a mouse has escaped from the current mouseIsland
public int getMouseEscaped(){
return mouseEscaped;
}
// getMouseDrowned
// Returns the total number of times a mouse has drowned on the current mouseIsland
public int getMouseDrowned(){
return mouseDrowned;
}
// getMouseStarved
// Returns the total number of times a mouse has starved on the current mouseIsland
public int getMouseStarved(){
return mouseStarved;
}
// getBridgePosition
// Returns the coordinate row(x) or column(y) to either of the bridges on the current mouseIsland
public int getBridgePosition(int x, int y){
return bridgePosition[x][y];
}
// getMousePosition
// Returns the coordinate row(x) or column(y) of the mouse on the current mouseIsland
public int getMousePosition(int x, int y){
return mousePosition[x][y];
}
// loadIsland
// Populates any information needed to run the simulation for the current mouseIsland
public void loadIsland() throws Exception{
if (islandTxt == "" || islandTxt == null){
System.out.println("loadIsland() failed! 'islandTxt' variable is empty!");
return;
}
findIslandRow();
findIslandCol();
setCharIslandArray();
findIslandVariables();
}
// printIslandStats
// Prints to the console the statistics for this mouseIsland at its current state
public void printIslandStats(){
System.out.println("Run count: " + runCount + " times\n"
+ "Drowned: " + mouseDrowned + " times\n"
+ "Starved: " + mouseStarved + " times\n"
+ "Escaped: " + mouseEscaped + " times \n");
}
// maxValue
// This function returns the max value of an integer array.
public int maxValue(int [] inArray){
int value = 0;
for (int i=0;i<inArray.length;i++)
if (value<inArray[i]) value = inArray[i];
return value;
}
// findIslandRow
// Counts the number of rows for the current mouseIsland
public void findIslandRow() throws Exception {
Scanner input = new Scanner(new File(islandTxt));
islandRows = 0;
while(input.hasNext()){
input.nextLine();
islandRows++;
}
//System.out.println("Rows: "+islandRows);
input.close();
}
// findIslandCol
// Counts and stores the number of columns for each row in the current mouseIsland
public void findIslandCol() throws Exception {
Scanner input = new Scanner(new File(islandTxt));
String inputLine = ""; int row = 0; islandCols = new int [islandRows];
while(input.hasNext()){
inputLine = input.nextLine();
islandCols[row] = inputLine.length();
//System.out.println("Col"+row+": "+islandCols[row]);
row++;
}
input.close();
}
// loads a mouse island map into a 2 dimensional character array
public void setCharIslandArray() throws Exception {
Scanner input = new Scanner(new File(islandTxt));
islandCharArray = new char [islandRows+1][maxValue(islandCols)+1];
String islandRow ="";
for(int row=0;row<islandRows;row++){
islandRow = input.nextLine();
for (int col=0;col<islandRow.length();col++) {
islandCharArray[row][col] = islandRow.charAt(col);
}
}
input.close();
}
// drawCharIsland
// Draws a character array to the console for testing
public void drawCharIsland() throws Exception{
String ln = "";
for (int row= 0;row<islandRows;row++){
for (int col= 0;col<islandCols[row];col++){
if (col == islandCols[row]-1) ln = "\n"; else ln ="";
System.out.print(islandCharArray[row][col]+ln);
}
}
System.out.println("");
}
// drawIntIsland
// Draws an integer array to the console for testing
public void drawIntIsland() throws Exception{
String ln = "";
for (int row= 0;row<islandRows;row++){
for (int col= 0;col<islandCols[row];col++){
if (col == islandCols[row]-1) ln = "\n"; else ln ="";
System.out.print(islandIntArray[row][col]+ln);
}
}
System.out.println("");
}
// drawBigIntIsland
// Draws an integer array with special formatting for larger numbers the console for testing
public void drawBigIntIsland() throws Exception{
String ln = ""; String rowZero = ""; String colZero = "";
int i=0;
for (int row= 0;row<islandRows;row++){
if (row <= 9) rowZero = " "; else rowZero ="";
for (int col= 0;col<islandCols[row];col++){
if (row == 0)
while (i<islandRows){
if (i == 0) System.out.print("XY");
if (i <= 9) colZero = " "; else colZero ="";
if (i == islandCols[row]-1) ln = "\n"; else ln ="";
System.out.print(colZero+i+ln);
i++;
}
if (col == islandCols[row]-1) ln = "\n"; else ln ="";
if (islandIntArray[row][col] <= 9) colZero = "|"; else colZero ="";
if (col == 0) System.out.print(rowZero+row);
if (row >=0 && col >=0) System.out.print(colZero+islandIntArray[row][col]+ln);
}
}
}
// findIslandVariables
// finds and stores all of the mouseIsland object variables
public void findIslandVariables() throws Exception{
int bCount = 0;
mousePosition = new int [2][2]; bridgePosition = new int [200][2];
for (int row= 0;row<islandRows;row++){
for (int col= 0;col<islandCols[row];col++){
//System.out.println(row+"|"+col);
switch(islandCharArray[row][col]) {
case 'X' : mousePosition[0][0] = row; mousePosition[0][1] = col; //current position
mousePosition[1][0] = row; mousePosition[1][1] = col; //start position
//System.out.println("Mouse found on: "+row+"|"+col);
break;
case '-' :
if (row == 0 || col == 0 || row == islandRows-1 || col == islandCols[row]-1){
bridgePosition[bCount][0] = row; bridgePosition[bCount][1] = col;
bCount++;
//System.out.println("Bridge"+bCount+": "+row+"|"+col);
} else if (col>=islandCols[row-1]-1 || col>=islandCols[row+1]-1){
bridgePosition[bCount][0] = row; bridgePosition[bCount][1] = col;
//System.out.println("Bridge found: "+row+"|"+col);
bCount++;
}
break;
}
}
}
}
// moveMouse
// Computes the movement for the mouse
// set moveDebug to 'true' to display the mouse's moves
public void moveMouse(){
moveDebug = false;
int mouseMove = (int)(Math.random() * 4);
switch(mouseMove){
case 0: mousePosition[0][0]--; if (moveDebug == true) System.out.print("Move: "+mouseMove+"[UP] "); break;
case 1: mousePosition[0][0]++; if (moveDebug == true) System.out.print("Move: "+mouseMove+"[DOWN] "); break;
case 2: mousePosition[0][1]--; if (moveDebug == true) System.out.print("Move: "+mouseMove+"[LEFT] "); break;
case 3: mousePosition[0][1]++; if (moveDebug == true) System.out.print("Move: "+mouseMove+"[RIGHT] "); break;
}
if (moveDebug == true) System.out.println(" Location:|"+mousePosition[0][0]+"|"+mousePosition[0][1]+"|");
}
// runMouseIsland
// Displays the outcome of one trial of the current mouseIsland
public void runMouseIsland() throws Exception{
islandIntArray = new int [islandRows][maxValue(islandCols)];
mousePosition[0][0] = mousePosition [1][0]; mousePosition[0][1] = mousePosition [1][1];
for (int count=0;count<100;count++){
moveMouse();
if (mousePosition[0][0] == bridgePosition[0][0] && mousePosition[0][1] == bridgePosition[0][1] || mousePosition[0][0] == bridgePosition[1][0] && mousePosition[0][1] == bridgePosition[1][1] ){
System.out.println("The mouse has escaped using the bridge at: "+mousePosition[0][0]+"|"+mousePosition[0][1]);
islandIntArray[mousePosition[0][0]][mousePosition[0][1]]++;
mouseEscaped++;
break;
} else
if (islandCharArray[mousePosition[0][0]][mousePosition[0][1]] == '#') {
System.out.println("OUCH! The Mouse fell into the water and died at: "+mousePosition[0][0]+"|"+mousePosition[0][1]);
islandIntArray[mousePosition[0][0]][mousePosition[0][1]]++;
mouseDrowned++;
break;
}
islandIntArray[mousePosition[0][0]][mousePosition[0][1]]++;
if (count == 99){
System.out.println("The mouse withered away (died) at: "+mousePosition[0][0]+"|"+mousePosition[0][1]);
mouseStarved++;
}
}
drawIntIsland();
runCount++;
}
}
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.