So I'm currently trying make a simple rpg game, it's my first time so I'm learning haha, but my question is that, I am trying to reference a variable in another class I have for the player's choice of their class. P.S. I couldn't figure out what to look up so I'm sorry if this is a repeat question.
this is the main
public static void main(String[] args) {
Scanner inputRace = new Scanner(System.in);
player player1 = new player(race.valueOf(inputRace), profession.ranger);
}
and here is the race class I'm trying to reference
public enum race {
orc, elf, human, dwarf
}
So all I'm trying to do is be able to take the user's input and do like race.("whatever their choice is"), but I haven't been able to figure it out. Thanks for any help and sorry if it's confusing.
In other to access input data you must use scanner methods like next, nextInt, nextDouble etc.
In your case you are looking for string so it should look like this:
try {
Race race = Race.valueOf( inputRace.next() ); // next returns string
Player player1 = new Player(race, profession.ranger);
} catch ( IllegalArgumentException ex ) {
System.err.println( "That race doesn't exsist" );
}
Note that I used upper case for Race and Player, this is standard way of naming your classes.
Also you should put your code in some kind of loop until he doesn't write correct race.
If I understand correctly, you need to get race.orc if the user enters orc, and henceforth.
You're on the right track, you just need to input the String from the user, like
String s = inputRace.next();
player player1 = new player(race.valueOf(s), profession.ranger);
Related
I Have a question abouth the code for handling erros made by the user.
So the thing is, I need my user to add a name of a program, to add the memory that program takes in the RAM and to add the time he will have that program open.
I need to add in my code defensive programming, so I thought maybe I could do it by checking if the user actually add the type of the variables that the program need, or if it didn't.
Either way I am confused on how to use the try and catch blocks, for now this is what I have...
System.out.println("add program Id");
String programID = scan.next();
try{
String check;
check = programID;
}catch(Exception e){
System.out.println("add a value of String type");
}
That doesn't work.
anything you can type is a string. I can type '5'. That's a string. You may think it is a number, but this entire block of text is a String, and '5' is in it.
No text is a string too. String x = ""; compiles fine.
Thus, no exception would ever occur here, and it's not clear what scenario you are trying to detect.
Perhaps a programID is of the form: "one capital letter (and only english capitals, not Ü for example), and then up to 3 different digits". For example, 'Z5' or 'Y495'.
You'd need to write code to detect this, no need for try/catch. For example, regular expressions:
private static final Pattern PROGRAM_ID_PATTERN = Pattern.compile("^[A-Z]\\d{1,3}$");
public static void main(String[] args) {
....
String programId;
do {
programId = scanner.next();
if (!PROGRAM_ID_PATTERN.matcher(programId).matches()) {
System.err.println("Enter a valid program ID, e.g. A123");
} else {
break;
}
} while (true);
}
Exceptions are for when a method has multiple different ways to exit.
For example, imagine this method:
byte[] contentsOfFile = Files.readFileFully("myfile.txt");
The readFileFully method seems simple: You provide the name of a file, and it returns a byte array with its contents.
However, that's just one way that could go. What if the file doesn't exist? What if the file exists, but your process doesn't have read access rights? What if the disk is failing or it's a removable drive and it's yanked out halfway through reading it?
These somewhat predictable potential alternate ways out are generally done by exceptions. That method would be throwing FileNotFoundException, noReadAccessException, and more generally IOException, for example.
There's no 'that is not a string' variant of scanner.next().
There is scanner.next(Pattern) which you could use:
private static final Pattern PROGRAM_ID_PATTERN = Pattern.compile("^[A-Z]\\d{1,3}$");
public static void main(String[] args) {
....
String programId;
do {
try {
programId = scanner.next(PROGRAM_ID_PATTERN);
break;
} catch (NoSuchElementException e) {
System.err.println("Enter a valid program ID, e.g. A123");
}
} while (true);
}
The javadoc generally explains what exceptions can occur; if a method doesn't mention any, you're not supposed to try/catch there.
I'm trying to get my ArrayList's index via indexOf. So far, I've got
My ArrayList: public static ArrayList<Shop> allShops = new ArrayList();
That what is supposed to get the index
Scanner editShop = new Scanner(System.in);
String shopToEdit = editShop.nextLine();
int i = allShops.indexOf(shopToEdit);
System.out.println(i); //see what our index is (returns -1 because the var doesn't seem to get the right input)
EditFunc.edit(i);
and this, that is supposed to change my arraylist
public static void edit(int index){
//change array with given input in edit
//TODO: Make it so they can choose what to edit
//with booleans if editTrueName = false and then later on make it true again
System.out.println("Enter the new shop name:");
Scanner editedShopAttribute = new Scanner(System.in);
String editedShopName = editedShopAttribute.nextLine();
System.out.println("Enter the new shop location:");
String editedShopLocation = editedShopAttribute.nextLine();
Shop EditedVar = new Shop();
EditedVar.createShop(editedShopName,editedShopLocation);
allShops.set(index, EditedVar);
}
I've copied the values that debugger showed me and replaced them with that, but it still doesn't seem to work. Am I taking in the wrong kind of data? What can I try?
If there's something that looks wrong with my code, I'm always up to try and make it better.
Can't you do it with a Map<String, Shop>? That way you could use the shopName as a key.
By the way, as I see your new with java and OOP, I strongly recommend you read Clean Code, by Robert C. Martin, its a game-changing book.
I don't believe you can make what you want work with an Array. The reason as pointed out in one of the comments is that you are looking for a String, but the Array contains Shop(s). Since a Shop contains more than just the ShopName, you will never be able to find it this way. You should use a "Map" for such purposes:
public static Map<String, Shop> allShopsMap = new HashMap<>();
If you add all the shops to this map, then when you get a ShopName as an input, you merely need to do:
Shop shopToEdit = allShopsMap.get(inputShopName);
then call the set methods on this object to alter name and location.
So this is my very first mini-javaproject and I have been stuck for days now on the basic structure and the (non existing) relation between anything within my code. I linked the code in my comment below, could not paste it in here for some reason - (Main is empty, so did not copy it.)
So I spent some time getting my head around the basics of Java (as my first programming adventure) and to be honest I felt pretty confident. (On Codewars I completed like 100+ Katas, but of course those are "single-class", so I was not prepared for the "real world.)
It is hard to exactly pinpoint my question, but I will try to give some examples.
1, (Main is empty right now, but anyway) Basically "nothing can be used" in main. Like methods of objects, like room1, or player1, etc.
2, In my Room.java line 21-22 why is the object room1 not visible? Why does Intellij say "Unknown class: RoomArray if I just created that very thing before??
3, I understand that I am supposed to have my variables set to private, which I plan to do later on. Also, I should use setter and getter methods, which I tried to do so with basically everything. But for example in Player.java I have this
Player player1 = new Player(300, 50, "Conan", 75, false);
public Player getPlayer1() {
return player1;
}
and if I try to use the getPlayer1() method in any other class it just simply can not see/access it?
3, And to make me even more confused Room1 class has access to getMyDungeon () method created in the Dungeon class. Why is that so?
(Maybe it has to do with inheritance? The fact that Room1 extends Room which extends Room? But if so, it seems strange because not all classes can have a HAS-A or IS-A relationship with something. An example - if I create all 10 Rooms later on as Room1, Room2, etc. in separate classes, how could I ever create a Room [] array containing them? No matter where I started to do that it will always give me the error "Cannot resolve smybol" for all the Room objects...)
I have spent the past few days reading up on the topic and understand it all, but still when I try to build this project it all falls apart. I realize that an experienced programmer might not even my question because how basic it is, but if anyone can help me to get this whole thing clear in my head, I would appreciate it. (Really not looking for the complete code, but just some direction I should go, or the missing step, etc.)
It seems you to be trying to create an object within the class of that object The correct use is:
public static void main(String[] args){
Player player1 = new Player(300, 50, "Conan", 75, false);
}
or if you want your Room class to have a lot of players
public class Room {
//this object will be create when you do Room room = new Room();
List<Player> players = new ArrayList<>();
public void createPlayer(){
players.add(new Player());
}
//this is a getter
public List<Player> getPlayers() {
return players;
}
}
your Player:
public class Player {
//Fields and Methods
}
and your main:
public static void main(String[] args)
{
Room room =new Room();
room.createPlayer();
for (Player p:room.getPlayers()) {
//p.doSomething
}
}
if you want an object to be created without the need to create an instance from the outside you need to use the static keyword (don't do that unless you know what you are doing)
static Player player1 = new Player(300, 50, "Conan", 75, false);
public static Player getPlayer1() {
return player1;
}
I am still fairly new to coding in java and I am trying to build a text game to help me learn. I am having issues transferring a variable to help me test out specs.
String a = user.next();
if(a.equals("warrior")){
System.out.println("You start to feel stronger, feels like you could run through a brick wall and keep on going without a scrath on you.\n" +
"Of course you might want to wait on that for awhile.\n" +
"********************************************************\n*\t\tAchievement got: Dumb as a rock!\t\t\t\t\t\t *\n********************************************************");
String specW = ("warrior");
comW (warrior);
}
public static void comW (warrior){
System.out.println("Testing1");
}
is anyone able to help me figure out why I keep having errors?
comW (specW);
}
public static void comW (String warrior){
System.out.println(warrior);
}
Do above changes in your code.
Basically you are passing a variable in comW method but the variable is not declared.
Secondly, in your comW method you didn't give parameter type.
I would recommend you to follow some tutorials carefully before posting question here.
You are creating a string variable with name specW but passing a variable warrior to comW function. So change the function parameter to specW. Also in the definition of function comW the parameter warrior is not given any type so give it a String type.
String a = user.next();
if(a.equals("warrior")){
System.out.println("You start to feel stronger, feels like you could run through a brick wall and keep on going without a scrath on you.\n" +
"Of course you might want to wait on that for awhile.\n" +
"********************************************************\n*\t\tAchievement got: Dumb as a rock!\t\t\t\t\t\t *\n********************************************************");
String specW = ("warrior");
comW (specW); // 1st Change
}
public static void comW (String warrior){ // 2nd Change
System.out.println("Testing1");
}
New to Java-
I'm building a poker program and I've created a player class with some instance variables including "toppair", "highcardst",etc... I tried to use a placeholder variable to refer to the appropriate player's instance variable rather than relying on if statements.
int handsdealt=0;
int straightval=0;
String placeholder="blank";
player playerone = new player("Richard");
player playertwo = new player("Negreanu");
//code omitted
if (handsdealt==1) placeholder="playerone";
else placeholder="playertwo";
//code to determine if hand is a straight -if it is it sets straightval to 1
**if(straightval==1) placeholder.highcardst=straightHigh;**
I receive an error on that last line- it looks like java doesn't accept this syntax. Essentially, since this hand is a straight I want to append the value of the "highcardst" instance variable of the "n" th player as n hands have been dealt.
Thank you.
You seem to be uses a String for your placeholder variable where you actually want to refer to a player object.
player playerone = new player("Richard");
player playertwo = new player("Negreanu");
//code omitted
player placeholder;
if (handsdealt==1) placeholder=playerone;
else placeholder=playertwo;
//code to determine if hand is a straight -if it is it sets straightval to 1
if(straightval==1) placeholder.highcardst=straightHigh;
Also, it will make your code easier to follow if you follow normal Java code conventions, such as capitalising the first letter of a class name (e.g. Player, not player).
You could make a list of players and get the instance of the player from the list as required.
List<player> players = new ArrayList<player>();
players.add(new player("Richard"));
players.add(new player("Negreanu"));
if(straightval==1) {
players.get(handsdealt).highcardst=straightHigh;
}
Or something like that.
I think the problem could be in this statement:
placeholder.highcardst=straightHigh;
You've defined placeholder of type String, so the property called highcardst does not exist.
if(straightval==1) placeholder.highcardst=straightHigh;
Error is here. place holder is String type not Player type. Make temp variable as Player variable and assign
Player placeholder;
if (handsdealt==1) placeholder=playerone;