We are trying to use the array to store the locations and then call them in the if else statements in the first class. We want to be able to call the grid locations so we do not have to type the description of the room in the if else statements.
package ProjectTwo;
import java.util.Scanner;
public class ProjectTwo {
// ----------------------------------------
// Main method, calls location (loc) method, which controls navigation
// ----------------------------------------
public static void main(String[] args){
loc();
}
// This method allows the user to view a list of actions that are used throughout the game
public static void help() {
System.out.println("Enter the letter 'n' to move north, the letter 's' to move south, or type the word 'quit' to end the game. Also, you can enter the letter 'm' to see an image of the map.");
}
// -------------------------------------
// Loc method
// Prints on-load message (intro)
// Defines global variables
// -------------------------------------
public static void loc() {
location.locMove();
int location = 0;
System.out.println("The Search" + "\n" + "\n" + "You have awoken in a laboratory. There is a door to your north and a door to your south." + "/n+" + "Enter 'n' and 's' to navigate, or type 'quit' to end the game. Also, enter the letter 'h'.");
String userInput = new String();
boolean stillPlaying = true;
// ------------------------------------
// Moves player while user is still playing
// Tells user his/her location
// ------------------------------------
while (stillPlaying) {
Scanner scan = new Scanner(System.in);
userInput = scan.nextLine();
if (location == 0){
if (userInput.equals("n")) {
System.out.println("You entered the dungeon.");
location = 1; // Moves user from location 0 to 1
}
else if (userInput.equals("s")) {
System.out.println("You cannot move south.");
location = 0; // Keeps user at location 0
} else if (userInput.equals("quit")){
System.out.println("Thanks for playing");
stillPlaying = false;
}
else if (userInput.equals("h")) {
help(); // calls the help method
}
else if (userInput.equals("m")) {
map(); // calls the map method
}
else {
System.out.println("Command not understood.");
}
} else if (location == 1) {
if (userInput.equals("n")) {
System.out.println("You have escaped out the back door of the dungeon.");
location = 2; // Moves user from location 1 to location 2
}
else if(userInput.equals("s")) {
System.out.println("You're back in the laboratory.");
location = 0; // Moves user from location 1 to location 0
} else if (userInput.equals("quit")){
System.out.println("Thanks for playing");
stillPlaying = false;
}
else if (userInput.equals("h")) {
help(); // calls the help method
}
else if (userInput.equals("m")) {
map(); // calls the map method
}
else {
System.out.println("Command not understood");
}
}
else if (location == 2) {
if (userInput.equals("n")) {
System.out.println("You cannot go that way...yet!");
location = 2; // Lets the user know that they cannot go that way
}
else if (userInput.equals("s")) {
System.out.println("You're back in the dungeon");
location = 1; // Mover from location 2 to location 1
}
else if (userInput.equals("quit")){
System.out.println("Thanks for playing");
stillPlaying = false;
}
else if (userInput.equals("h")) {
help(); // calls help method
}
else if (userInput.equals("m")) {
map(); // calls map method
}
else {
System.out.println("Command not understood.");
}
}
}
}
}
//This is our main class
-------------------------------------------------------------------------
// This is our class with the 2d array
package ProjectTwo;
public class location {
public int location;
public String name;
public static String message;
public location(String name, int location, String message){
this.name = name;
this.location = location;
this.message = message;
System.out.println(message);
}
public static void locMove() {
location [][] grid = new location[4][4];
{
grid [1][0] = new location("LABORATORY", 0, "You're in the lab.");
grid [2][0] = new location("DUNGEON", 1, "You entered the dungeon.");
grid [3][0] = new location("COURTYARD ENTRANCE",2,"You have left the dungeon out the backdoor. Either head east and search the courtyard maze, or travel north back to the dungeon");
grid [3][1] = new location("FIRST PATH", 3,"You have now entered the courtyard, either continue east or move north.");
grid [3][2] = new location("DEADEND", 4,"You have reached a deadend that has a Magic Shop. Go inside and explore it.");
grid [3][3] = new location ("MAGIC SHOP", 5, "Search around the Magic Shop and see what there is. When you're done searching continue through the maze.");
grid [2][1] = new location("SECOND PATH",6,"Search the surroundings for items that will help you get into the locked room, then keep moving.");
grid [2][2] = new location("END MAZE", 7, "You've made it to the end of the courtyard. There seems to be a cave in the distance; go check it out.");
grid [1][2] = new location("CAVE",8,"Explore the cave to find the remaining items that will lead to your freedom.");
grid [0][0] = new location("EXIT",9,"This room will lead to your freedom, but you need the three essential items that will open this door.");
}
while (grid.equals(0)) {
System.out.println(message.toString());
}
}
}
There are many ways to do what you say but look your code, think this is really fits your code without changing much but just my opinion:
"try using, Location not location to name classes but not nesesario"
package ProjectTwo;
public class location {
In Your Class location:
//Your other code
public static location [][] locMove() { // <--- change void for location [][]
location [][] grid = new location[4][4];
{
grid [1][0] = new location("LABORATORY", 0, "You're in the lab.");
grid [2][0] = new location("DUNGEON", 1, "You entered the dungeon.");
grid [3][0] = new location("COURTYARD ENTRANCE",2,"You have left the dungeon out the backdoor. Either head east and search the courtyard maze, or travel north back to the dungeon");
grid [3][1] = new location("FIRST PATH", 3,"You have now entered the courtyard, either continue east or move north.");
grid [3][2] = new location("DEADEND", 4,"You have reached a deadend that has a Magic Shop. Go inside and explore it.");
grid [3][3] = new location ("MAGIC SHOP", 5, "Search around the Magic Shop and see what there is. When you're done searching continue through the maze.");
grid [2][1] = new location("SECOND PATH",6,"Search the surroundings for items that will help you get into the locked room, then keep moving.");
grid [2][2] = new location("END MAZE", 7, "You've made it to the end of the courtyard. There seems to be a cave in the distance; go check it out.");
grid [1][2] = new location("CAVE",8,"Explore the cave to find the remaining items that will lead to your freedom.");
grid [0][0] = new location("EXIT",9,"This room will lead to your freedom, but you need the three essential items that will open this door.");
}
while (grid.equals(0)) {
System.out.println(message.toString());
}
return grid;
}
//Your other code
In your other class:
package ProjectTwo;
public class ProjectTwo {
//your other code
location [][] testGrid = null; //<--- add variable
//your other code
public static void main(String[] args){
loc();
}
//your other code
public static void loc() {
testGrid = location.locMove();
//testGrid <-- this your array
//your other code
I have not test, but I think it can work, but not the way I usually do, I hope you can help.
P.S: You could look at this, if you want https://stackoverflow.com/tour
I definitely agree with the comments about code style and formatting. Anyway here are the suggestions how you can refactor your code.
Probably the simplest way to avoid writing lots of if-else construction is to use switches. You loc() code might look something like that (I would also move duplicated h/m/quit commands to a single place):
Solution 1:
...
while (stillPlaying) {
Scanner scan = new Scanner(System.in);
userInput = scan.nextLine();
switch (userInput) {
case "quit":
System.out.println("Thanks for playing");
stillPlaying = false;
break;
case "h":
help(); // calls the help method
break;
case "m":
map(); // calls the map method
break;
case "n":
case "s":
switch (location) {
case 0:
switch (userInput) {
case "n":
System.out.println("You entered the dungeon.");
location = 1; // Moves user from location 0 to 1
break;
case "s":
System.out.println("You cannot move south.");
location = 0; // Keeps user at location 0
break;
}
break;
case 1:
switch (userInput) {
case "n":
System.out.println("You have escaped out the back door of the dungeon.");
location = 2; // Moves user from location 1 to location 2
break;
case "s":
System.out.println("You're back in the laboratory.");
location = 0; // Moves user from location 1 to location 0
break;
}
break;
case 2:
switch (userInput) {
case "n":
System.out.println("You cannot go that way...yet!");
location = 2; // Lets the user know that they cannot go that way
break;
case "s":
System.out.println("You're back in the dungeon");
location = 1; // Mover from location 2 to location 1
break;
}
break;
default:
System.out.println("no such location");
}
break;
default:
System.out.println("Command not understood.");
}
}
...
However the better way is to try to encapsulate the locations-commands-actions stuff to a different classes. That how it might look:
Solution 2:
public static interface Action {
// return the next location or an error
int action();
}
public static class LocationsMap {
public Map<Integer, Map<String, Action>> locations = new HashMap<>();
public void registerAction(int location, String userInput, Action action) {
Map<String, Action> actionsMap = locations.get(location);
if (actionsMap == null) {
actionsMap = new HashMap<>();
locations.put(location, actionsMap);
}
actionsMap.put(userInput, action);
}
public int executeAction(int location, String userInput) {
Map<String, Action> currentLocation = locations.get(location);
if (currentLocation == null) {
return -1;
}
Action currentAction = currentLocation.get(userInput);
if (currentAction == null) {
return -2;
}
return currentAction.action(); // move to next location
}
}
then you can define your actions (per location and user input) like that:
...
public static LocationsMap locationsMap = new LocationsMap();
static {
// location 0
locationsMap.registerAction(0, "n", new Action() {
#Override
public int action() {
System.out.println("You entered the dungeon.");
return 1; // Moves user from location 0 to 1
}
});
locationsMap.registerAction(0, "s", new Action() {
#Override
public int action() {
System.out.println("You cannot move south.");
return 0; // Keeps user at location 0
}
});
// location 1
locationsMap.registerAction(1, "n", new Action() {
#Override
public int action() {
System.out.println("You have escaped out the back door of the dungeon.");
return 2; // Moves user from location 1 to location 2
}
});
locationsMap.registerAction(1, "s", new Action() {
#Override
public int action() {
System.out.println("You're back in the laboratory.");
return 0; // Moves user from location 1 to location 0
}
});
// location 2
locationsMap.registerAction(2, "n", new Action() {
#Override
public int action() {
System.out.println("You cannot go that way...yet!");
return 2; // Lets the user know that they cannot go that way
}
});
locationsMap.registerAction(2, "s", new Action() {
#Override
public int action() {
System.out.println("You're back in the dungeon");
return 1; // Mover from location 2 to location 1
}
});
}
...
and then the code in the loc() function will look like that:
...
while (stillPlaying) {
Scanner scan = new Scanner(System.in);
userInput = scan.nextLine();
switch (userInput) {
case "quit":
System.out.println("Thanks for playing");
stillPlaying = false;
break;
case "h":
help(); // calls the help method
break;
case "m":
map(); // calls the map method
break;
default:
int actionResult = locationsMap.executeAction(location, userInput);
if (actionResult == -1) {
System.out.println("no such location");
break;
}
if (actionResult == -2) {
System.out.println("Command not understood.");
break;
}
location = actionResult; // move to next location
}
}
...
That is not the best solution, but it is much better and readable.
I would also define an enum for locations instead of using ints.
Also you can think about storing this locations-inputs-actions information in some file, parse it and then use in the app/game, but that will be more complicated to implement.
Related
I've been following Tim Buchalka's course Java Programming Masterclass for Software Developers and I've been modifying his program from lesson 118.
I want to update my list at the runtime while using the list iterator (navigate method). The program runs fine, but if I update my list, Java throws an error: ConcurrentModificationException
I have come up with the following solution:
Whenever a user performs a modification of the list, other methods run, and update the list and pass it to the navigate() method. By doing this, my program enters multi-level nested methods, and the problem comes up when a user wants to exit from the program (case 0: in navigate() method). User has to press 0 as many times as many nested methods were ran.
My initial idea was to count how many times navigate() was nested, then using for loop return as many times as it was nested. But later I understood it does not make sense
What can I do to exit from the program by using case 0: just once?
package com.practice;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Scanner;
public class List extends Traveler {
private LinkedList<String> linkedList;
private String tripName;
public List(String travelerName, int travelerAge, String tripName) {//it has to have same amount of parameters or more with super constructor!
super(travelerName, travelerAge);
this.tripName = tripName;
this.linkedList = new LinkedList<>();
}
public List(){} //it has to have same amount of parameters or more with super constructor!
public LinkedList<String> getLinkedList() {
return linkedList;
}
public String getTripName() {
return tripName;
}
private void removeCity(LinkedList<String> cityList, String deletedCity) {
if(cityList.remove(deletedCity)) {
System.out.println(deletedCity + " has been removed");
} else System.out.println("Could not find the city you want to remove");
List.navigate(cityList);
}
//adds a new city and update the list without an error
private void noExceptionError(LinkedList<String> listOfCities, String cityName) {
ListIterator<String> listIterator = listOfCities.listIterator();
while((listIterator.hasNext())) {
int comparison = listIterator.next().compareTo(cityName);
if(comparison == 0) {
System.out.println(cityName + " has been already added to the list");
return;
} else if(comparison > 0) {
listIterator.previous();
break;
}
}
listIterator.add(cityName);
List.navigate(listOfCities);
}
private void loadToList(LinkedList<String> listOfCities) {
alphabeticallyAdd(listOfCities, "Poznan");
alphabeticallyAdd(listOfCities, "Gdansk");
alphabeticallyAdd(listOfCities, "Szczeczin");
alphabeticallyAdd(listOfCities, "Warszawa");
alphabeticallyAdd(listOfCities, "Lodz");
alphabeticallyAdd(listOfCities, "Wroclaw");
List.navigate(listOfCities);
}
private void alphabeticallyAdd(LinkedList<String> listOfCities, String cityName) {
ListIterator<String> listIterator = listOfCities.listIterator(); //just a setup; doesn't point to the 1st element
while((listIterator.hasNext())) {
//if value is greater, the word that is in the list is alphabetically bigger, thus, put it before the list element
//if equal, it is duplicate! return false
// else it is less, thus, we have to move further in the list
int comparison = listIterator.next().compareTo(cityName); //retrieves the 1st value and goes to the next
if(comparison == 0) {
System.out.println(cityName + " has been already added to the list");
return;
} else if(comparison > 0) {
listIterator.previous(); //because we've used .next() in the int comparison initialization
listIterator.add(cityName); //don't use linkedList.add because it doesn't know the int comparison, so cannot properly add!!!
return;
}
}
listIterator.add(cityName); //adding at the end of the list
}
public static void navigate(LinkedList<String> listOfCities) {
Scanner userChoice = new Scanner(System.in);
List travelListObject = new List();
ListIterator<String> listIterator = listOfCities.listIterator();
boolean goingForward = true;
while(true) {
Main.menu();
int choice = userChoice.nextInt();
userChoice.nextLine(); //takes care of enter key problem
switch(choice) {
case 0:
System.out.println("Goodbye");
//possible improvement
/* for(int i = 0; i <= List.amountNestedMethods; i++) {
return;
}*/
return;
case 1: //moving forward
if(!goingForward) {
if(listIterator.hasNext()) {
listIterator.next();
}
}
if(listIterator.hasNext()) {
System.out.println(listIterator.next());
Traveler.setNumberVisitedCities(Traveler.getNumberVisitedCities() + 1);
goingForward = true;
} else {
System.out.println("No more cities in the list");
goingForward = false;
}
break;
case 2: //moving back
if(goingForward) {
if(listIterator.hasPrevious()) {
listIterator.previous();
}
goingForward = false;
}
if(listIterator.hasPrevious()) {
Traveler.setNumberVisitedCities(Traveler.getNumberVisitedCities() + 1);
System.out.println(listIterator.previous());
} else {
System.out.println("You're at the beginning of the list");
goingForward = true;
}
break;
case 3:
Main.printCities(listOfCities);
break;
case 4:
break;
case 5:
System.out.println("Write new city");
String addedCity = userChoice.next();
travelListObject.noExceptionError(listOfCities, addedCity);
break;
case 6:
System.out.println("Write the city you want to delete");
String deletedCity = userChoice.next();
travelListObject.removeCity(listOfCities, deletedCity);
break;
case 7:
System.out.println("You have been in " + Traveler.getNumberVisitedCities() + " cities in total");
break;
case 9:
travelListObject.loadToList(listOfCities);
break;
default:
System.out.println("Something weird happened. Try to choose an option again");
}
}
}
}
If you want to exit the program you can simply call System.exit(n), where the n is an integer return code (the convention being that code 0 means normal execution and other values indicate some sort of error).
I'm trying to implement a monopoly-style game in java as part of a school project but I've run into an issue that I cant resolve or seem to find an answer to the question that I have. The problem is that I'm getting a classCastException in my code, I think I've figured out why I'm getting it (i was originally trying to cast type Property onto the newPosition variable below)but now I need to find a way to implement the code so that I can avoid it.
The issue is i have a superclass Square which has 3 possible subclasses Property, Go and FreeParking. I'm storing my board as an ArrayList but I need to access the methods pertaining to Property objects to calculate rent etc. How can I access these methods if when I access the property from the ArrayList it it of type Square.
Apologies in advance if this doesn't make too much sense.
public abstract class Square {
private String name;
private boolean isAvailable;
private Player owner;
//getters and setters
}
public class Property extends Square{
private String colour;
private int buyHouset;
private int rent1House;
private int rent2House;
private int rent3House;
private int rentHotel;
private int numHouses;
private int rent;
private int price;
//getters and setters
}
public static void takeTurn(Player player, Dice die, ArrayList<Square> board) {
System.out.println(player.getGamertag() + "'s turn");
//get value from roll of die
int move = askToRoll();
String gamertag = player.getGamertag();
//if player does not quit continue with turn
if(move > 0) {
//get player current position and add roll of die
int newSpaceIndex = player.getPosition() + move;
//if players new position exceeds the array of squares, return to 0 index and add remainder
//add credits for passing Go
//else update position
if (newSpaceIndex > 11) {
player.setPosition(newSpaceIndex - 12);
Go.passGoAction(player);
}else {
player.setPosition(newSpaceIndex);
}
if(player.getPosition() == 1) {
Square newPosition = board.get(player.getPosition());
System.out.println(gamertag + " new position " + newPosition.getName());
}else if(player.getPosition() == 6) {
FreeParking.freeParkingAction();
} else {
Square newPosition = board.get(player.getPosition());
System.out.println("____________________");
System.out.println("Land on " + newPosition.getName());
if(newPosition.getOwner() != null) {
Player owner = newPosition.getOwner();
/* *****THIS IS WHERE THE ERROR IS STEMING FROM*****
*THE newPosition.getRent() method can not be accessed as newPosition
*is defines as Square
*/
System.out.println(owner.getGamertag() + " demands you pay " + newPosition.getRent() + " credits!");
}else {
System.out.println("What would you like to do now? ...\n"
+ "1. Buy property\n"
+ "2. End turn");
int input = in.nextInt();
boolean valid = false;
do {
switch(input) {
case 1:
System.out.println("You now own controlling stock of " + newPosition.getName());
player.setOwnsProperty(newPosition);
newPosition.setOwner(player);
valid = true;
break;
case 2:
System.out.println("Ending turn");
valid=true;
break;
default:
System.out.println("Invalid input, please select one of the options 1-2");
valid = false;
break;
}
}while(!valid);
}
}
}
System.out.println("END TURN: " + player);
System.out.println();
}
If you know that a particular Square is a Property, cast it and assign it to the appropriate type.
Property newPosition = (Property)board.get(player.getPosition());
Edit: In future, you might also want to consider putting the logic that goes with a particular type of Square into a subclass. In other words, something like square.process(player), where Property, Go, and FreeParking each implements the process(player) method with appropriate logic. That goes into more detailed concepts around object-oriented design, and may not be relevant to you right now.
I hope that this snippet helps you to understand the concept
public static void main(String[] args) {
Square newPosition = new Property();
if (newPosition instanceof Property) {
System.out.println("newPosition cast as Property");
Property newPositionAsProperty = ((Property) newPosition);
int newRent = newPositionAsProperty.getRent();
// or
newRent = ((Property) newPosition).getRent();
}
// To understand better
if (newPosition instanceof Square) {
System.out.println("newPosition instanceof Square");
((Square)newPosition).getName();
}
if (Square.class.isAssignableFrom(Property.class)) {
System.out.println("Square.class.isAssignableFrom(Property.class)");
((Square)newPosition).getName();
}
if (Property.class.isInstance(newPosition)) {
System.out.println("Property.class.isInstance(newPosition)");
((Property)newPosition).getName();
}
if (Square.class.isInstance(newPosition)) {
System.out.println("Square.class.isInstance(newPosition)");
((Square)newPosition).getName();
}
}
Result:
newPosition cast as Property
newPosition instanceof Square
Square.class.isAssignableFrom(Property.class)
Property.class.isInstance(newPosition)
Square.class.isInstance(newPosition)
This is a program I'm writing for school, its a 2D array adventure game. I need help with the blank if statement. It needed to know if a valid direction was entered. I'm just not sure where to go from here. I also want to make it so there is an amount of keys to access the locked rooms. I'm not very talented at coding so this may seem messy, but I'ts the best I have. How can i do this?
package hauntedhouse;
import java.util.Scanner;
public class HauntedHouse {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner c = new Scanner(System.in);
String room[][] = new String[2][2]; // allocate 2 dimensional array of strings
//This section of code fills the 2D array with room names
room[0][0] = "Entry Hall";
//code to fill the rest of the rooms here
room[1][0] = "Dining Room";
room[2][0] = "Master Bedroom";
room[0][1] = "Storage [locked]";
room[1][1] = "Grand Hall";
room[2][1] = "Bedroom";
room[0][2] = "Garage [locked]";
room[1][2] = "Back Door";
room[2][2] = "";
int x = 0; // the coordinates of the room to start
int y = 0;
String di = ""; // variable used to hold the direction they entered
System.out.println("Theres a secret in this house,");
System.out.println("go into the locked rooms to find");
System.out.println("out what it is, have these two keys!");
do {
System.out.println("You are now in the " + room[x][y]);
//this next loop will repeat until a valid direction is entered
while (true) //this loop continues until the "break" statement is executed
{
System.out.println("Enter your direction");
if () //figure this out!!
{
break; //exits while loop
}
} // end while (true)
if (di.equals("W"))
{
y = y+1;
} else if (di.equals("A")) {
x = x-1;
} else if (di.equals("S")) {
y = y-1;
} else if (di.equals("D")) {
x = x+1;
} else {
//an illegal direction has been entered
}
}
while (x>=2); }// end when you make it to the locked room SOMEHOW
} // TODO code application logic here
To validate a 2D array you can simply use .equals() function
String room [][] = new String [2][2];
room[0][0] = "Entry Hall";
if(room[0][0].equals("Entry Hall")){
System.out.println("Inside Entry Hall");
}
The purpose of this project is to make a pokedex that adds and holds all the pokemon passed in by user input. When the user inputs a pokemon that is already stored in the pokedex the word "duplicate" is supposed to be printed to the console. The word duplicate is printed even though there are no actual duplicates within the object array. Here is my output from the console :
Welcome to your new PokeDex!
How many Pokemon are in your region?: 3
Your new Pokedex can hold 3 Pokemon. Let's start using it!
List Pokemon
Add Pokemon
Check a Pokemon's Stats
Sort Pokemon
Exit
What would you like to do? 2
Please enter the Pokemon's Species: red
Duplicate
Now here is all the code used that could possibly be making this error
import java.util.Scanner;
public class Project4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to your new PokeDex!");
System.out.print("How many Pokemon are in your region?: ");
int size = input.nextInt();
Pokedex pokedex = new Pokedex(size);
System.out.println("\nYour new Pokedex can hold " + size + " Pokemon. Let's start using it!");
int choice = 0;
boolean done = false;
while (!done) {
System.out.println("\n1. List Pokemon\n2. Add Pokemon\n3. Check a Pokemon's Stats" + "\n4. Sort Pokemon\n5. Exit");
System.out.print("\nWhat would you like to do? ");
choice = input.nextInt();
switch (choice) {
case 1:
String[] pokemonList = pokedex.listPokemon();
if (pokemonList == null)
System.out.println("Empty");
else
for (int i = 0; i < pokemonList.length; i++) {
System.out.println((i + 1) + ". " + pokemonList[i]);
}
break;
case 2:
System.out.print("\nPlease enter the Pokemon's Species: ");
String species = input.next();
pokedex.addPokemon(species);
break;
}
}
}
}
In the following class I have the actual method that adds the pokemon and the constructor for Pokedex
public class Pokedex {
Pokemon[] pokedex;
String pokeArray[];
public Pokedex(int size) {
pokedex = new Pokemon[size];
pokeArray = new String[size];
}
public boolean addPokemon(String species) {
Pokemon stuff = new Pokemon(species);
for (int i = 0; i < pokedex.length; i++) {
if (pokedex[i] == null) {
pokedex[i] = stuff;
}
else if (i < pokedex.length && pokedex[i] != null) {
System.out.println("Max");
}
if (pokedex[i].getSpecies().equalsIgnoreCase(species)) {
System.out.print("Duplicate");
break;
}
}
return false;
}
}
Sorry for the mass amounts of code I just need help tracing where this unexpected result is coming from.
The reason it's doing that is because of this bit of code here:
public boolean addPokemon(String species)
{
Pokemon stuff = new Pokemon(species);
for (int i = 0; i < pokedex.length; i++)
{
if (pokedex[i] == null)
pokedex[i] = stuff;
else if (i < pokedex.length && pokedex[i] !=null)
System.out.println("Max");
if(pokedex[i].getSpecies().equalsIgnoreCase(species))
{
System.out.print("Duplicate");
break;
}
}
return false;
}
The problem is just a little bit of syntax missing. In your for loop, you check to see if
A) there are any empty spots in the array
B) if every element in the array up to the user inputted size is full
and C) if any element in the array matches the one we're trying to add.
The problem you're encountering is because your C is an if instead of an else if. Because A sees the index is null, it assigns the new Pokemon to the Pokedex. Then because C is an if instead of an else if, it runs after you assign the new Pokemon and sees the Pokemon we just added and says it's a duplicate. Changing it to an else if would fix this.
Also, since there was no break; in A, it would assign every element of the array to the first one entered, causing any further additions to call Max. I edited the code and this is what I had that worked for me:
public boolean addPokemon(String species)
{
Pokemon stuff = new Pokemon(species);
for (int i = 0; i < pokedex.length; i++)
{
if(pokedex[i] !=null && pokedex[i].getSpecies().equalsIgnoreCase(species))
{
System.out.println("Duplicate");
break;
}
else if (pokedex[i] == null)
{
pokedex[i] = stuff;
break;
}
else if(i + 1 == pokedex.length)
{
System.out.println("Max");
break;
}
}
return false;
}
Also, out of curiosity, why is the addPokemon() function a boolean? You return a value (albeit arbitrarily) and then never do anything with that value. You could just make it a void, have it return nothing, and it would work just as fine.
I am making a text based launcher for a number of programs. I am using the
Runtime.getRuntime().exec("path//to//file.exe")) method.
The program will run, it always will, but some act weirdly or fail to find critical .dll files that are there. Others have text messed up while running etc. As you can see, these are all games which are complex and use a number of engines I don't understand. Thanks!
Dead Space 3: Screen is black, game runs though. Only display seems to not be working
MW3: TeknoMW3.exe cant find teknomw3.dll even though they are in the same folder(and launching it normally makes it run fine).
Endless Space: Text is displayed strangely. Exit is %getuserexit% or something akin to that for every space where text should and normally is displayed. Only occurs on main menu.
Splinter Cell Blaclist: Dir is correct, cant find the specified file. Ill jut work around that one.
Bioshock 1: Straight up crashes(might be due to a .dll problem again, I dont actualy know though)
Bioshock 2: Never runs. file is executed but doesnt run.
public class Main {
static int launcherNum = 14;
static Launchers launchers[] = new Launchers[launcherNum];
static Launchers assassinsCreed3 = new Launchers("G://Games//ROMS//Assassins Creed III//AC3SP.exe", "Assassians Creed III (AC3)");
static Launchers bioshock = new Launchers("G://Games//ROMS//Bioshock//Builds//Release//Bioshock.exe", "Bioshock");
static Launchers bioshock2 = new Launchers("G://Games//ROMS//Bioshock 2//SP//Builds//Binaries//Bioshock2.exe", "Bioshock 2");
static Launchers bioshock3 = new Launchers("G://Games//ROMS//Bioshock Infinite//Binaries//Win32//BioShockInfinite.exe", "Bioshock Infinite");
static Launchers borderlands2 = new Launchers("G://Games//ROMS//Borderlands 2//Binaries//Win32//Borderlands2.exe", "Borderlands 2");
static Launchers mw3 = new Launchers("G://Games//ROMS//Call of Duty- Modern Warfare 3//TeknoMW3.exe", "Call of Duty: Modern Warefare 3 (MW3)");
static Launchers deadSpace3 = new Launchers("G://Games//ROMS//Dead Space 3//deadspace3.exe", "Dead Space 3");
static Launchers endlessSpace = new Launchers("G://Games//ROMS//Endless Space//EndlessSpace.exe", "Endless Space");
static Launchers prototype2 = new Launchers("G://Games//ROMS//PROTOTYPE 2//Prototype2.exe", "Prototype 2");
static Launchers leagueOfLegends = new Launchers("G://Games//ROMS//lol.launcher.exe", "League of Legends");
static Launchers rct3 = new Launchers("G://Games//ROMS//RCT3//RCT3plus.exe", "Rollercoaster Tycoon 3");
static Launchers splitSecond = new Launchers("G://Games//ROMS//Split Second//SplitSecond.exe", "Split Second");
static Launchers skyrim = new Launchers("G://Games//ROMS//The Elder Scrolls V Skyrim//TESV.exe", "The Elder Scrolls: Skyrim");
static Launchers tcSplinterCell = new Launchers("G://Games//ROMS//Tom Clancys Splinter Cell Blacklist//src//SYSTEM//Blacklist_DX11_game.exe", "Tom Clancy's: Splinter Cell Blacklist");
public static void initLauncher() {
//adds AC3
launchers[0] = assassinsCreed3;
//Adds all 3 Bioshocks. God its hard to write "Bioshock"
launchers[1] = bioshock;
launchers[2] = bioshock2;
launchers[3] = bioshock3;
//Adds Borderlands 2
launchers[4] = borderlands2;
//Adds MW3
launchers[5] = mw3;
//Adds Dead Space 3
launchers[6] = deadSpace3;
//Adds Endless Space
launchers[7] = endlessSpace;
//Adds Prototype 2
launchers[8] = prototype2;
//Adds League of Legends... yeah, I know.
launchers[9] = leagueOfLegends;
//Adds RCT3
launchers[10] = rct3;
//Adds Split Second
launchers[11] = splitSecond;
//Adds skyrim
launchers[12] = skyrim;
//Adds Splinter Cell
launchers[13] = tcSplinterCell;
}
public static void runLaunchers() {
boolean done = false;
String input1;
Scanner input = new Scanner(System.in);
while(done == false) {
System.out.println("Welcome to the Cracked Game Launcher, also know as CSteam. This is a product of the labors of ASIGTX. Do not redistribute.\n Ever");
System.out.println("Please select a game from our libraires.");
System.out.println();
for (Launchers l: launchers) {
if (l.launcherName != null) {
System.out.println(l.launcherName);
System.out.println();
}//end of if loop
}//end of for loop
input1 = input.nextLine();
switch (input1) {
case "Assassins Creed 3":
case "AC3":
launchers[0].launchEXE();
if (launchers[0].hasLaunched == true) {
done = true;
}//end of if
break;
case "Bioshock":
launchers[1].launchEXE();
if (launchers[1].hasLaunched == true) {
done = true;
}//end of if
break;
case "Bioshock 2":
launchers[2].launchEXE();
if (launchers[2].hasLaunched == true) {
done = true;
}//end of if
break;
case "Bioshock Infinite":
launchers[3].launchEXE();
if (launchers[3].hasLaunched == true) {
done = true;
}//end of if
break;
case "Borderlands 2":
launchers[4].launchEXE();
if (launchers[4].hasLaunched == true) {
done = true;
}//end of if
break;
case "MW3":
case "Call of Duty: Modern Warefare 3":
launchers[5].launchEXE();
if (launchers[5].hasLaunched == true) {
done = true;
}//end of if
break;
case "Dead Space 3":
launchers[6].launchEXE();
if (launchers[6].hasLaunched == true) {
done = true;
}//end of if
break;
case "Endless Space":
launchers[7].launchEXE();
if (launchers[7].hasLaunched == true) {
done = true;
}//end of if
break;
case "Prototype 2":
launchers[8].launchEXE();
if (launchers[8].hasLaunched == true) {
done = true;
}//end of if
break;
case "League of Legends":
launchers[9].launchEXE();
if (launchers[9].hasLaunched == true) {
done = true;
}//end of if
break;
case "Rollercoaster Tycoon 3":
launchers[10].launchEXE();
if (launchers[10].hasLaunched == true) {
done = true;
}//end of if
break;
case "Split Second":
launchers[11].launchEXE();
if (launchers[11].hasLaunched == true) {
done = true;
}//end of if
break;
case "The Elder Scrolls: Skyrim":
case "Skyrim":
launchers[12].launchEXE();
if (launchers[12].hasLaunched == true) {
done = true;
}//end of if
break;
case "Tom Clancy's: Splinter Cell Blacklist":
case "Splinter Cell Blacklist":
launchers[13].launchEXE();
if (launchers[13].hasLaunched == true) {
done = true;
}//end of if
break;
}//end of switch
}//end of while loop
}
public static void main(String[] args) {
initLauncher();
runLaunchers();
}//end of main
}//end of class
public class Launchers {
public boolean hasLaunched = false;
public String launcherName;
private String dir;
public Launchers(String dir, String namein) {
setName(namein);
this.dir = dir;
}//end of constructor
public void setName(String s) {
launcherName = s;
}//end of setname
public String getDir() {
return dir;
}
public void launchEXE() {
String runtimeName = launcherName;
try {
Runtime.getRuntime().exec( getDir() );
} catch (IOException e) {
System.out.println("Dir is invalid");
e.printStackTrace();
}
hasLaunched = true;
System.out.println(launcherName +" has launched!");
}//end of launchEXE
}
It is likely that the programs have an expectation about their execution context.
From your example, it's likely that every program is being started within the same context/execution location that you run your program from, meaning that they can't find libraries or resources that they need.
Instead of using Runtime#exec directly, try using ProcessBuilder instead. This will allow you to change the execution location of the process.
For example...
String cmd = getDir();
File cmdFile = new File(cmd);
// Maybe check that the cmdFile.exists...;)
File parentFile = cmdFile.getParentFile();
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.directory(parentFile);
pb.redirectError();
Process p = pb.start();
It would also be advisable to read the process's InputStream as some process get upset when you don't ;)
InputStream is = p.getInputStream();
// This simple reads the contents from the InputStream and discards it
// You could change it to actually dump the output if wanted ;)
while (is.read() != -1);
int exitValue = p.waitFor();