Reputation: 41
This is class Roulette.java
public static void main(String[] args) {
System.out.println("Welcome to roulette " + Casino.player());
}
This is class Casino.java
public static String player() {
Scanner sc = new Scanner(System.in);
String name;
System.out.println("Please enter your name : ");
name = sc.nextLine();
return name;
}
When running Roulette.java
it's not printing Casino.player()
as a variable of your name, but running the function and asking for your name. I want to run Casino.java
first,ask your name, then run roulette and welcome you with your name. NOT ASK YOUR NAME AGAIN.
Note: New to programming
Upvotes: 0
Views: 42
Reputation: 3118
The player()
method in the Casino
class prints out the message to input the users name. This will happen every time the method is called. To do what you want to do you need to create a conditional that checks if the player has already been set.
NOTE: This is not good practice or class design and in the future you should look into proper practice for class design and setting fields in a class. I would suggest posting this code on Code Review once you get it working to get a full answer on how this design can be improved.
Your Casino
class should look something like this:
public class Casino {
private static String player = "";
public static String player() {
if (player.equals("")) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your name : ");
this.player = sc.nextLine();;
}
return player;
}
}
Upvotes: 2
Reputation: 4384
Try something like this
String player = Casino.player();
System.out.println("Welcome to roulette " + player);
Upvotes: 0