So I have an arrayList with rooms and im getting the user to put in the room they are looking for, im capturing this as a string and then trying to use instanceOf to match it up with the names of the java classes but cant do this due to comparing a string to a java class.
Also I am capturing there answer in a switch statement to make sure the classes are perfectly spelt and what not. just not sure how to reach in the arrayList and pull out the class they are looking for.
public static void serachRooms(ArrayList<Room> rooms) {
int option = 0;
String temp = "";
boolean flag = false;
do {
System.out.println("please Enter What room Type you would like:"
+ "\nNormal Room = 1"
+ "\nComputer Room = 2"
+ "\nBiology Lab = 3"
+ "\nBoard Room = 4"
+ "\nYou must choose one!");
option = input.nextInt();
if (option == 1 || option == 2 || option == 3 || option == 4) {
flag = true;
}
} while (!flag);
switch (option) {
case 1:
temp = "BiologyLab";
break;
case 2:
temp = "BoardRoom";
break;
case 3:
temp = "ComputerRoom";
break;
case 4:
temp = "Room";
break;
}
for (Room room : rooms) {
if (temp instanceof BiologyLab) {
}
}
}
instanceof is something pretty special that has to do with types and inheritance. Check out the Java documentation.
For your case, you want to compare the String temp to the String "BiologyLab". Just use
if ("BiologyLab".equals(temp)) {
...
}
and check out How To Compare Strings In Java for more information.
Related
In a text adventure game written in Java, I want the character race to be as follows( the number corresponds to the key the user types):
// Character Race
// 1) Human
// 2) Dwarf
// 3) Elf
// 4) Orc
How do I write that out to the player?
Like this?
So I ask the user which race they want:
System.out.print("Enter character race: ");
charRace = input.nextInt();
System.out.println("Your character's race is " + charRace);
How do I tell my program that 1 = Human, 2 = Dwarf, etc...??
Do I need to create a dictionary or something similar?
Thanks!
This might be a little out of the range of scope, but for me, when you have a limited range of possible values, I'd tend to look towards using a enum
enum Race {
HUMAN(1), DWARF(2), ELF(3), ORC(4);
private int value;
private Race(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public static Race from(int value) {
for (Race race : Race.values()) {
if (race.getValue() == value) {
return race;
}
}
return null;
}
}
Then you can do fun things like...
Race race = Race.from(1);
if (race == null) {
System.out.println("Invalid selection");
} else {
switch (race) {
case DWARF:
System.out.println("Gunghrim Dwarf!");
break;
case ELF:
System.out.println("Welcome Elf!");
break;
case HUMAN:
System.out.println("Welcome Human!");
break;
case ORC:
System.out.println("Welcome Orc!");
break;
}
}
You could even automate the menu. Start by adding something like...
public String getProperName() {
StringBuilder sb = new StringBuilder(32);
String name = name();
sb.append(name.charAt(0));
sb.append(name.substring(1).toLowerCase());
return sb.toString();
}
to the Race enum and then you could create a menu doing something like...
List<Race> races = Arrays.asList(Race.values());
races.sort(new Comparator<Race>() {
#Override
public int compare(Race o1, Race o2) {
return o1.getValue() - o2.getValue();
}
});
for (Race race : races) {
System.out.println(race.getValue() + ") " + race.getProperName());
}
which prints
1) Human
2) Dwarf
3) Elf
4) Orc
Have a look at the enums type trail for more details
You could just use some if statements to identify the entered race. Something like this
if(charRace == 1){
String race = "Human";
} else if(charRace == 2){
String race = "Dwarf";
} else if(charRace == 3){
String race = "Elf";
} else{
String race = "Orc";
}
Maybe not the most efficient way to do this though.
If you are just using integers wouldn't a simple Array be the better choice?
String races[] = {"Dwarf","Elf","Human","Orc"};
System.out.println("You selected: "+races[charRace]);
edit:
If you want error handling:
String races[] = {"Dwarf","Elf","Human","Orc"};
if(charRace>=0&&charRace<races.length)
System.out.println("You selected: "+races[charRace]);
else
System.out.println("Error: invalid input!");
Also it is definetely more efficient to use a switch case over an if-else!
Here is an example, althought I dont recommend it since you are handling integers!!
switch (charRace) {
case 1:
System.out.println("You selected Dwarf");
break;
case 2:
System.out.println("You selected Elf");
break;
case 3:
System.out.println("You selected Human");
break;
case 4:
System.out.println("You selected Orc");
break;
default:
System.out.println("Error: invalid input!");
break;
}
If you want this program more sustainable, you should use inherithence.
Like:
public class Orc extends Race{
}
public class Human extends Race{
}
After creation of the all races, you can create a method for creating new race for given number.
For example:
public static Race createRace(int raceType){
if(raceType == 1)
return new Orc();
else if(raceType == 2)
return new Human();
}
Also, you can define different variables and different methods for your races.
I am trying to make a small game:
There are 2 heroes you can choose: 1 Warrior and 2 Mage.
Next, you should choose how to travel: 1 by Horse 2 Teleportation (available to Mage only).
Finally, choose a weapon: 1 Sword 2 Staff (*Mage can only use Staff; Warrior can use both).
I created a loop for my first question (choosing a hero) so that if the user enters something else aside from 1 or 2, the program will repeat the question ("Choose your hero: ...). I need the same done for my second and third question (especially since there are some restrictions, e. g. if the user chose Warrior, he can't choose Teleportation as his travel option).
public static void main(String[] args) {
int hero, travel, weapon;
Scanner scan = new Scanner(System.in);
loop:
while (true) {
System.out.println("Choose your hero: 1 for Warrior, 2 for Mage");
hero = scan.nextInt();
switch (hero) {
case 1:
System.out.println("Choose your travel option: 1 for Horse; 2 for Teleportation");
travel = scan.nextInt();
break loop;
case 2:
System.out.println("Choose your travel option: 1 for Horse; 2 for Teleportation");
travel = scan.nextInt();
break loop;
default:
break;
}
}
}
I don't know how to use a loop inside another loop properly. I've tried several options but it always returns an error.
It is always a good idea to split things up, instead of making nested loops. Here is a simple way to split the program in 3 methods, each one dealing with a choice.
Hero choice: Offer both choices and loop until given a valid answer. Then return the answer
private static int queryHero() {
Scanner scan = new Scanner(System.in);
int hero;
while (true) {
System.out.println("Choose your hero: 1 for Warrior, 2 for Mage");
hero = scan.nextInt();
if(hero == 1 || hero == 2) {
break;
} else {
System.out.println(hero + " is not a valid choice");
}
}
return hero;
}
Travel option choice: Offer choices depending on the chosen hero and loop until given a valid answer. Then return the answer
private static int queryTravelOptionForHero(int hero) {
Scanner scan = new Scanner(System.in);
int travelOption;
while (true) {
if (hero == 1) {
System.out.println("Choose your travel option: 1 for Horse");
travelOption = scan.nextInt();
if (travelOption == 1) {
break;
} else {
System.out.println(travelOption + " is not a valid choice");
}
} else if (hero == 2) {
System.out.println("Choose your travel option: 1 for Horse; 2 for Teleportation");
travelOption = scan.nextInt();
if (travelOption == 1 || travelOption == 2) {
break;
} else {
System.out.println(travelOption + " is not a valid choice");
}
}
}
return travelOption;
}
Weapon choice: Offer choices depending on the chosen hero and loop until given a valid answer. Then return the answer
private static int queryWeaponForHero(int hero) {
Scanner scan = new Scanner(System.in);
int weapon;
while (true) {
if(hero == 1) {
System.out.println("Choose your weapon: 1 for Sword; 2 for Staff");
weapon = scan.nextInt();
if (weapon == 1 || weapon == 2) {
break;
} else {
System.out.println(weapon + " is not a valid choice");
}
} else if(hero == 2) {
System.out.println("Choose your weapon: 2 for Staff");
weapon = scan.nextInt();
if(weapon == 2) {
break;
}else {
System.out.println(weapon + " is not a valid choice");
}
}
}
return weapon;
}
Then in your main:
int hero = queryHero();
int travelOption = queryTravelOptionForHero(hero);
int weapon = queryWeaponForHero(hero);
System.out.println("hero: " + hero);
System.out.println("travelOption: " + travelOption);
System.out.println("weapon: " + weapon);
Note: I am not sure if you know about them, but there are ways to make this code nicer using enums and Lists
Your flow can be written as a simple procedural code. As so, I would write it in the most simple form I can - at least as a start.
There is no real justification for using switch labels and loops inside loops
Just write 3 simple loops, one after another - It will be simple to read, understand and debug.
I dont want to write the code for you, it is not the purpose of this site, but here's a Pseudo code:
Loop 1 (selecting heroes)
If(heroes != Warrior)
Loop 2 (selecting travel)
else travel=Horse
Loop 3 (selecing weapon)
Like the comments suggest i would not go with loops inside loops. Instead you should assign the variables one at the time. I have written a helper method selectVariable(String description, String varOne, String varTwo) that you can use to assign variables and give you a start for your story game. You could expand it if you want to give the user more choices. Also don't give the use the illusion a choice can be made, if there is no choice in that situation.
Here is the code that should do what you want:
import java.util.Scanner;
public class Story {
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
int hero = chooseHero();
int travel = chooseTravel(hero);
int weapon = chooseWeapon(hero);
//For printing purposes give your choice their respective string name again.
String heroDesc = hero == 1 ? "Warrior" : "Mage";
String travelDesc = travel == 1 ? "Horse" : "Teleportation";
String weaponDesc = weapon == 1 ? "Sword" : "Staff";
System.out.printf("you are a %s, traveling by %s, wielding a %s" + System.lineSeparator(), heroDesc, travelDesc, weaponDesc);
}
private static int chooseHero() {
return selectVariable("choose your hero class", "warrior", "mage");
}
private static int chooseTravel(int hero) {
if (hero == 1) { // if the user has no choice don't give the illusion a choice can be made
System.out.println("you are a Warrior you will travel by horse");
return 1;
} else {
return selectVariable("choose your way of travel", "by horse", "teleportation");
}
}
private static int chooseWeapon(int hero) {
if (hero == 2) {
System.out.println("you are a mage you will wield a staff");
return 2;
} else {
return selectVariable("choose your weapon", "sword", "staff");
}
}
//you can reuse this method to also assign other traits to your story
private static int selectVariable(String description, String varOne, String varTwo) {
int var;
do {
System.out.printf("%s: 1 %s, 2 for %s" + System.lineSeparator(), description, varOne, varTwo);
var = scan.nextInt();
switch (var) {
case 1:
System.out.printf("you have chosen %s" + System.lineSeparator(), varOne);
return var;
case 2:
System.out.printf("you have chosen %s" + System.lineSeparator(), varTwo);
return var;
default:
System.out.println(var + " is an invalid choice");
}
}
while (true);
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I'd like to preface this with that I've only started learning Java earlier at the beginning of this year, so I appreciate all your help! I'm currently working on a Shadowrun (3rd Edition) program that turns Decking into a Command Prompt. I'd like the user to be able to enter Blue, Green, Orange, or Red to start with a Host Color, but also give a Random option as well.
Scanner user_input = new Scanner(System.in);
String HostColor;
System.out.println("What is the color of the Host? (Blue, Green, Orange, Red, Random)"); //Get the Host's Color
HostColor = user_input.nextLine();
Random rand = new Random();
while ((!HostColor.equals("Blue")) || (!HostColor.equals("Green")) || (!HostColor.equals("Orange")) || (!HostColor.equals("Red"))) {
if (HostColor.equals("Blue")) {
...
break;
}
else if (HostColor.equals("Green")) {
...
break;
}
else if (HostColor.equals("Orange")) {
...
break;
}
else if (HostColor.equals("Red")) {
...
break;
}
else if (HostColor.equals("Random")) {
int RandomHost = (rand.nextInt(4));
if (RandomHost == 0) {
HostColor.equals("Blue");
...
break;
}
else if (RandomHost == 1) {
HostColor.equals("Green");
...
break;
}
else if (RandomHost == 2) {
HostColor.equals("Orange");
...
break;
}
else if (RandomHost == 3) {
HostColor.equals("Red");
...
break;
}
}
else {
System.out.println("Invalid Command");
System.out.println("What is the color of the Host? (Blue, Green, Orange, Red, Random)");
HostColor = user_input.nextLine();
}
}
System.out.println("Host is a " + HostColor + "...");
The code works just fine when specifying a particular color. However, when choosing the Random option and then printing the overall results, rather than printing one of the four colors, my code says the HostColor is Random. I appreciate any input to help solve this problem - thanks in advance!
HostColor.equals() is not assignment, equals() is comparision method which checks whether two strings are equals or not in this case.
else if (HostColor.equals("Random")) {
int RandomHost = (rand.nextInt(4));
if (RandomHost == 0) {
HostColor = "Blue";
}
else if (RandomHost == 1) {
HostColor = "Green";
}
else if (RandomHost == 2) {
HostColor = "Orange";
}
else if (RandomHost == 3) {
HostColor = "Red" ;
}
}
I would recommend you to use Switch statements for comparing string instead of if-elseif. Switch appears to be more clean way of writing such conditional codes.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
What I want to do is simply read a input (Char/String , preferably char), its a single char and then print some outputs based on the inputs. My problems faced is that, if i convert my input 'choice' into a char, my error messages are:
Type mismatch: cannot convert from String to char
Incompatible operand types char and String
any idea whats wrong? Thanks!
*If I leave it like this it just gives me "Invalid Choice"
import java.util.*;
public class P1 {
public static void main(String[] args) {
// Create a scanner
Scanner userInputScanner = new Scanner(System.in);
String choice = userInputScanner.nextLine();
System.out.println("Your choice is " + choice);
if ((choice == "A") || (choice == "a"))
System.out.println( " Action Movie Fan");
else if ((choice == "C") || (choice == "c"))
System.out.println( " Comedy movie fan ");
else if ((choice == "D") || (choice == "d"))
System.out.println(" Drama movie fan ");
else
System.out.println( "Invalid choice" );
}
}
You compare strings in Java using equals:
if ("A".equals(choice) || "a".equals(choice)) {
...
}
or equalsIgnoreCase:
if ("A".equalsIgnoreCase(choice)) { // "a".equalsIgnoreCase(choice) works too
...
}
However, in your case you need to compare a single character, so you can do this:
if (choice.length() == 1) {
// Convert to upper case for case insensitivity
char selection = Character.toUpperCase(choice.charAt(0));
switch (selection) {
case 'A':
...
break;
case 'C':
...
break;
case 'D':
...
break;
}
...
}
For your case, try to use String.equalsIgnoreCase.
You might want to explore usage of Enum as well.
import java.util.*;
public class P1 {
public static void main(String[] args) {
// Create a scanner
Scanner userInputScanner = new Scanner(System.in);
String choice = userInputScanner.nextLine();
System.out.println("Your choice is " + choice);
if (choice.trim().equalsIgnorecase("A"))
System.out.println( " Action Movie Fan");
else if (choice.trim().equalsIgnorecase("B"))
System.out.println( " Comedy movie fan ");
else if (choice.trim().equalsIgnorecase("D"))
System.out.println(" Drama movie fan ");
else
System.out.println( "Invalid choice" );
}
}
otherwise compare only first character of string like choice.charAt(0) == 'A'
What you should know is that "A" and "a" are not chars, they are Strings. What you should do is call String's equals() (and not the == operator) method to compare. Just like that:
if(stringOne.equalsIgnoreCase("A")) {
//methods
}
I need the syntax for adding in the variable parameter to a switch case that already has lots of parameters. The context is provided below.
I'm using a switch case to change a string answer to an integer return. Instead of having the user answer
1. This.
2. Something else.
I want the answer to look like
(y/n)
I've done it before with a code like this:
static public int getYN() {
String answer = "";
switch(keyboard.nextLine().substring(0, 1).toLowerCase()) {
case "y":
return 1;
case "n":
return 0;
default:
return 2;
}
}
And then using the statement:
int getAnswer = getYN();
System.out.println();
if (getAnswer == 1) {
System.out.println("Stuff.");
test = 1;
}
else {
System.out.println("Other stuff.");
System.out.println();
}
But, I don't know where to put the String answer variable into the switch case. Usually, if you aren't using many other parameters, it would just be
switch(answer) {
}
Check it inline, forget having a dedicated method to doing this check.
char getAnswer = keyboard.next().charAt(0);
System.out.println();
if (getAnswer == 'y' || getAnswer == 'Y')
{
System.out.println("Stuff.");
test = 1;
}
else if( getAnswer == 'n' || getAnswer == 'N')
{
System.out.println("Other stuff.");
System.out.println();
}
If you absolutely have to use a switch:
char getAnswer = keyboard.next().charAt(0);
switch(getAnswer)
{
case 'y':
System.out.println("Stuff.");
test = 1;
break;
case 'n':
System.out.println("Other stuff.");
System.out.println();
break;
}
You can achieve the same thing in one line:
public static int getYN(String s) {
return ("yn YN".indrxOf(s) + 3) % 3;
}
Both upper and lower cases are handled, and the "not found" default value of 2 is handled by adding 3 (indexOf() returns -1 when the target is not found) and modulus divusion takes care of the capital letter indexes.
Fairly neat even if I do say so myself.