Calling Classes In Main Method - java

So I want to create a menu where a user can choose to play two different games. I want to create a main method and be able to make a for loop or switch statements for the different game options or for the user to quit but I am not sure how I would call the classes so that the game runs when they choose it.
Can someone explain to me how I would go about this. Thanks!
import java.util.Scanner;
import java.util.Random;
public class RpsGame {
/* Valid user input: rock, paper, scissors */
public static void main(String[] args) {
System.out.print("Please Make Your Choice (Rock, Paper or Scissors): ");
try {
Scanner sc =
new Scanner(System.in);
String userInput =
sc.next();
if (isValid( userInput )) {
game( userInput );
} else {
print("Invalid user input!\nWrite rock, paper or scissors!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void print(String text) {
System.out.println( text );
}
public static boolean isValid(String input) {
if (input.equalsIgnoreCase("rock")) {
return true;
}
if (input.equalsIgnoreCase("paper")) {
return true;
}
if (input.equalsIgnoreCase("scissors")) {
return true;
}
return false;
}
public static void game(String user) {
String computer = computerResults();
//System.out.print("Please Make Your Choice: ");
print( user + " vs " + computer + "\n");
if (user.equalsIgnoreCase(computer)) {
print("Oh, Snap! Tied - No winners.");
} else {
if (checkWin(user, computer)) {
print("You won against the computer!");
} else {
print("You lost against the computer!");
}
}
}
public static String computerResults() {
String types[] =
{"rock", "paper", "scissors"};
Random rand = new Random();
int computerChoice = rand.nextInt(3);;
return types[computerChoice];
}
public static boolean checkWin(String user, String opponent) {
if ( (!isValid( user )) && (!isValid( opponent )) ) {
return false;
}
String rock = "rock", paper = "paper", scissors = "scissors";
if ( (user.equalsIgnoreCase( rock )) && (opponent.equalsIgnoreCase( scissors )) ) {
return true;
}
if ( (user.equalsIgnoreCase( scissors)) && (opponent.equalsIgnoreCase( paper )) ) {
return true;
}
if ( (user.equalsIgnoreCase( paper )) && (opponent.equalsIgnoreCase( rock )) ) {
return true;
}
return false;
//If no possible win, assume loss.
}
}

The easiest method that I am familiar with is using something called a Driver Class. A Driver Class is a class that is designed to run code from other classes - perfect for running two different games. Check this post if you need more info: What is a driver class? (Java)

Try something like this:
public class MyGameApp {
public static final String OPTION_1 = "1";
public static final String OPTION_2 = "2";
public static final String OPTION_EXIT = "3";
public static void main(String... args) {
Scanner sc = new Scanner(System.in);
String userChoice = null;
do {
System.out.println("Choose an option: \n 1. Game 1\n2. Game 2\n3. Exit");
userChoice = sc.nextLine();
switch(userChoice) {
case OPTION_1:
/*
Calls a static method of a class, so there is no need of instantiate the class first.
*/
GameOne.start();
break;
case OPTION_2:
/*
In this case, create a new instance of the class GameTwo, and then call the method start().
*/
GameTwo game = new GameTwo();
game.start();
break;
default:
System.out.println("Wrong option, try again.");
}
while(!OPTION_EXIT.equals(userChoice));
}
}
class GameOne {
public static void start() { ... }
}
class GameTwo {
public void start() { ... }
}

Related

Issue is Java Main class..its not running properly

I have 7 classes(shown in pick below) with main method class for testing is Animalstuff class. When I'm running the code its getting hung and not moving any where. Need your help to solve this.At the end I want to run using Junit.
classes all
running Animalstuff class, see below it hang and not moving forward.
hung
here is the code for complete Animalstuff class.
/**
*
*/
import java.util.ArrayList;
import java.util.Scanner;
public class AnimalStuff {
// main function
public static void main(String[] args) {
// for taking inputs
Scanner in = new Scanner(System.in);
// arrayList to store all the animals
ArrayList<Animal> myList = new ArrayList<Animal>();
int ch;
// Loop until user chooses to quit
do {
// print menu
System.out.println("Menu");
System.out.println("1. Add animal");
System.out.println("2. Print");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
ch = in.nextInt();
// if user chooses to add animal to list
if(ch==1) {
// input the kind/name of animal
in.nextLine();
String word;
System.out.print("Enter name of animal: ");
word = in.nextLine();
// create object of that kind
Animal obj = Animal.newInstance(word);
// if user entered invalid animal, print message
if(obj==null) {
System.out.println("Animal doesn't exist.");
}
// else add to the list
else {
myList.add(obj);
}
}
// if user chooses to see information of all the
// animals in the list
else if(ch == 2) {
for(int i=0;i<myList.size();i++) {
myList.get(i).print(true);
}
}
// if user chooses to quit
else {
System.out.println("See you soon!");
}
}while(ch != 3);
}
}
Below is the code for Animal class
import java.util.ArrayList;
import java.util.Scanner;
public class Animal {
// variables
public String kind;
public String integument;
public boolean fast;
// private constructor to avoid plain animals
private Animal() {
}
// public argument constructor for Mammal and Bird class to
// call
public Animal(String kind, boolean fast) {
this.kind = kind;
this.fast = fast;
}
// movement method
public String movement() {
if(fast) {
return "I run on four legs.";
}
else {
return "I walk on four legs.";
}
}
// sound method
public String sound() {
return "";
}
// method to print all the information about the animal
public void print(boolean fast) {
String move = "";
if(fast)
move = "fast";
else
move = "slowly";
System.out.println("I am a "+kind);
System.out.println(" I have "+integument);
System.out.println(" When I go "+move+", "+movement());
System.out.println(" The sound I make is "+sound());
}
// method to return the animal object of type kind
public static Animal newInstance(String kind) {
Animal obj;
boolean correct = false;
if(kind.toLowerCase().equals("cow")) {
obj = new Cow();
Cow cow = new Cow();
if(obj.equals(cow)) {
correct = true;
}
}
else if(kind.toLowerCase().equals("duck")) {
obj = new Duck();
Duck duck = new Duck();
if(obj.equals(duck)) {
correct = true;
}
}
else if(kind.toLowerCase().equals("parrot")) {
obj = new Parrot();
Parrot parrot = new Parrot();
if(obj.equals(parrot)) {
correct = true;
}
}
else if(kind.toLowerCase().equals("whale")) {
obj = new Whale();
Whale whale = new Whale();
if(obj.equals(whale)) {
correct = true;
}
}
else {
return null;
}
if(correct) {
System.out.println("Correct object is formed.");
}
else {
System.out.println("Wrong object is formed.");
}
return obj;
}
// Function to check if two methods are same, i.e., this function
// checks whether the object formed is correct or not
public boolean equals(Animal obj) {
if(this.kind.equals(obj.kind)) {
if(this.integument.equals(obj.integument)) {
if(this.movement().equals(obj.movement())) {
if(this.sound().equals(obj.sound())) {
return true;
}
}
}
}
return false;
}
}
Please let me know whats worng in this and how I can fix. The other classes are very small if need I can give code for those as well.
Thanks
Enter your choice:
If you are getting this line in the console then it's asking for the input ch. Enter your input and you'll proceed further.

How to fix null error when I've already declared the variable

I am making a PVP RPG game and the display box comes out with "null" instead of the variable I have already declared.
I have declared the variable as the user's next input and stored that information in the variable. Then when I try to display the variable, it only shows "null",
System.out.println("Welcome, Player One and Player Two!");
delay(1500);
System.out.println("What is your name, Player One?");
playerOne.name = userInput.nextLine();
I already declared playerOne as a new character(different class)
System.out.println("Your turn, " + playerOne.name+".");
if (p1Swordgo == 1) {
This is the problem I'm coming up with. It is in the same main method and the variables are declared in the main method, and yes I imported scanner and declared the variable userInput
I expected it to be what the user typed in, but it came up with null. As I've said previous, it's in the same main method and nothing should go wrong, but it comes up with "null"
import java.util.Random;
import java.util.Scanner;
public class Arena {
Random generator = new Random();
public static void main(String[] args) {
Character playerOne = new Character(10,10,0);
Character playerTwo = new Character(10,10,0);
boolean P1hasClass = false;
boolean P2hasClass = false;
int p1Swordgo = 0;
int p2Alchgo = 0;
int p2Archgo = 0;
Scanner userInput = new Scanner(System.in);
System.out.println("Welcome, Player One and Player Two!");
delay(1500);
System.out.println("What is your name, Player One?");
playerOne.name = userInput.nextLine();
delay(1000);
System.out.println("Hello, " +playerOne.name +".");
delay(1000);
System.out.println("What is your name, Player Two?");
playerTwo.name = userInput.nextLine();
delay(1000);
System.out.println("Hello, " +playerTwo.name +".");
delay(1500);
countdown();
System.out.println("Your turn, " + playerOne.name+".");
if (p1Swordgo == 1) {
if (p2Archgo == 1 || p2Alchgo == 1) {
if (playerOne.move == 1){
System.out.println("What do you want to do?" +'\n' +"1 = Move into range of " +playerTwo.name +'\n' +"2 = Heal" +'\n' +"3 = Forfeit");
int P1Choice = userInput.nextInt();
if (P1Choice == 1) {
playerOne.move --;
System.out.println(playerOne.move);
}
}
}
}
}
public static void delay ( int time){
try {
Thread.sleep(time);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
public static void countdown() {
delay(500);
System.out.println("Get ready to fight in 5,");
delay(1000);
System.out.println("4");
delay(1000);
System.out.println("3");
delay(1000);
System.out.println("2");
delay(1000);
System.out.println("1");
delay(1000);
System.out.println("Fight!");
delay(750);
}
}
And then in a class called Character
public class Character {
public int strength;
public double health;
public int move;
public String name;
public Character(double health, int strength, int move) {
this.health = health;
this.strength = strength;
this.name = name;
this.move = move;
}
}
And in a class called SwordFighter
public class SwordFighter extends Character {
public SwordFighter() {
super(60,15, 1);
}
}
And in a class called Archer
public class Archer extends Character{
public Archer() {
super(45,20, 0);
}
}
And finally, in a class called Alchemist
public class Alchemist extends Character {
public Alchemist() {
super(50,15, 0);
}
}
Thank you for your patience, by the way
Once the two players have chosen their name and you have set it using playerOne.name = userInput.nextLine();, you assign a different object, with a null name, to playerOne:
playerOne = new SwordFighter();
So, after this line has been executed, playerOne.name is null.

Chatbot won't respond

I am trying to create a chatbot program but my issue is that, when I run the program, it exits right after the sentence is typed.
import java.util.*;
public class Mina{
public static void main(String[]args){
ai();
}
public static void ai(){
greeting();
conversation();
}
public static void greeting(){
System.out.println("Hello. I am Mina.");
}
public static void conversation(){
Scanner console = new Scanner(System.in);
String chat = console.nextLine();
if(!chat.equalsIgnoreCase("\bBye\b") || !chat.equalsIgnoreCase("\bBye.\b")){
keywords(chat);
}
}
public static void keywords(String word){
if(word.equalsIgnoreCase("\bHello\b") || word.equalsIgnoreCase("\bHello.\b")){
System.out.println("What do you want to talk about?");
keywords(word);
}else if(word.equalsIgnoreCase("\bMr. Smith\b") || word.equalsIgnoreCase("\bMr. Smith.\b")){
System.out.println("I bet he is a nice teacher.");
keywords(word);
}else if(word.equalsIgnoreCase("\bBye\b") || word.equalsIgnoreCase("\bBye.\b")){
System.exit(0);
}
return;
This is what I get:
Mina's Run
I previously had my code loop by placing keyword(); at the end of the method.
}else if(word.equalsIgnoreCase("\bBye\b") || word.equalsIgnoreCase("\bBye.\b")){
System.exit(0);
}
keyword(word);
return;
If anyone has any ideas on what I can possibly do to fix this problem, please help.
I have modified your code to make it work in a fashion where it will ask the user to input a new line until they say "Bye". This is achieved by using the while loop as shown:
import java.util.*;
public class Mina{
public static void main(String[]args){
ai();
}
public static void ai(){
greeting();
conversation();
}
public static void greeting(){
System.out.println("Hello. I am Mina.");
}
public static void conversation(){
Scanner console = new Scanner(System.in);
String chat = console.nextLine();
while(!(chat.equalsIgnoreCase("Bye") || chat.equalsIgnoreCase("Bye."))){
keywords(chat);
chat = console.nextLine();
}
System.exit(0);
}
public static void keywords(String word){
if(word.equalsIgnoreCase("Hello") || word.equalsIgnoreCase("Hello.")){
System.out.println("What do you want to talk about?");
}else if(word.equalsIgnoreCase("Mr. Smith") || word.equalsIgnoreCase("Mr. Smith.")){
System.out.println("I bet he is a nice teacher.");
}
}
}

Calling Random Value from an Enum Java

I have a Enum Class, a Player Class, and a class called Lisa that extends Player class. Im trying to randomly generate a value (PAPER, ROCK, or SCISSORS) from the Enum. Error: "The primitive type int of Roshambo does not have a field ROCK." Any advice or pointers would be greatly appreciated. It may be apparent, but this is my fists Java class and Google and Stackoverflow searches have not helped. Here is what I have coded so far:
UPDATE: Thanks for all the assistance. I've updated my whole program below. I was wondering if anyone could suggest the best way/place possible to implement logic to determine the winner/loser of the game? Here is the full code:
MAIN
package gameOfRoshambo;
import java.util.Scanner;
public class RoshamboApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Roshambo!");
System.out.println("Enter your name:");
//Create a new payer
Player1 player1 = new Player1();
String name = sc.nextLine();
player1.setName(name);
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
System.out.println("Hello " + name + ". " + "Would you like to play against Bart or Lisa? (B/L)");
String opponent = sc.next();
if(opponent.equalsIgnoreCase("B")){
//Create a new Bart opponent
Bart bart = new Bart();
System.out.println(player1.getName() + ": " + player1.getChoice());
System.out.println("Bart: " + bart.getRoshambo());
}
else if (opponent.equalsIgnoreCase("L")){
//Create a new Lisa opponent
Lisa lisa = new Lisa();
System.out.println(player1.getName() + ": " + player1.getChoice());
System.out.println("Lisa: " + lisa.getRoshambo());
}
// Ask user if they want to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
//Close Scanner
System.out.println("Thanks for playing! Goodbye!");
sc.close();
}
}
ENUM
package gameOfRoshambo;
public enum Roshambo
{ROCK, PAPER, SCISSORS;
public String toString() {
switch(this) {
case ROCK: return "Rock";
case PAPER: return "Paper";
case SCISSORS: return "Scissors";
default: throw new IllegalArgumentException();
}
}
}
PLAYER
package gameOfRoshambo;
abstract class Player {
String name;
Roshambo roshambo;
abstract int generateRoshambo();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Roshambo getRoshambo() {
return roshambo;
}
public void setRoshambo(Roshambo newRoshambo) {
roshambo = newRoshambo;
}
}
PLAYER1
package gameOfRoshambo;
import java.util.Scanner;
public class Player1 extends Player{
String player1 = "";
public Player1(){
super();
}
Scanner scan = new Scanner(System.in);
public Roshambo getChoice(){
System.out.println("Enter Choice: Paper, Rock, Scissors (r/p/s): ");
char playerChoice = scan.nextLine().toUpperCase().charAt(0);
switch (playerChoice){
case 'R':
return Roshambo.ROCK;
case 'P':
return Roshambo.PAPER;
case 'S':
return Roshambo.SCISSORS;
}
System.out.println("Invalid input!");
return getChoice();
}
public String getPlayer1() {
return player1;
}
public void setPlayer1(String player1) {
this.player1 = player1;
}
#Override
int generateRoshambo() {
// TODO Auto-generated method stub
return 0;
}
}
BART
package gameOfRoshambo;
public class Bart extends Player {
public Bart(){
super();
}
public Roshambo getRoshambo(){
return Roshambo.ROCK;
}
#Override
int generateRoshambo() {
// TODO Auto-generated method stub
return 0;
}
}
LISA
package gameOfRoshambo;
import java.util.Random;
public class Lisa extends Player {
private Random rand;
public Lisa(){
super();
rand = new Random();
}
public Roshambo getRoshambo(){
int shoot = rand.nextInt(3);
return Roshambo.values()[shoot];
}
#Override
int generateRoshambo() {
return 0;
}
}
You should store your roshambo field as a Roshambo not an int and update your setter and getter accordingly. This is because in Java Enums cannot be casted to int. See the below stack overflow link for explanation:
Cast Int to enum in Java
Field names should start with a lower case
Use Roshambo.values()[choice]
Get rid of the 1 + in 1 + rand.nextInt(3); because the nextInt() method has the first enum value in position 0. So
Roshambo.values()[0] = ROCK
Roshambo.values()[1] = PAPER
Roshambo.values()[2] = SCISSORS
In the Lisa constructor, change to rand = new Random() instead of Random rand = new Random() to avoid assigning to a new local variable which you lose once the constructor finishes
See the code snippets I've attached below for you
Player Class
package gameOfRoshambo;
abstract class Player {
String name;
Roshambo roshambo;
abstract int generateRoshambo();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Roshambo getRoshambo() {
return roshambo;
}
public void setRoshambo(Roshambo newRoshambo) {
roshambo = newRoshambo;
}
}
Lisa Class
package gameOfRoshambo;
import java.util.Random;
public class Lisa extends Player {
private Random rand;
public Lisa(){
super();
rand = new Random();
}
public Roshambo getRoshambo(){
int choice = rand.nextInt(3);
return Roshambo.values()[choice];
}
#Override
int generateRoshambo() {
return 0;
}
}
Also with the new above implementation you don't use the abstract int generateRoshambo() method so consider removing it and its implementation in Lisa...
Your field Roshambo is of type int. I think you want to declare it as something more like this:
Roshambo roshambo;
It is bad practice to capitalize field names. In this case, it confused you because you mixed up the field name with the type. You will have to replace int with Roshambo in several other places in your code.

Dealing with object's scope

I'm trying to write a game in Java with a Player class that has 2 subclasses: HumanPlayer and ComputerPlayer. I want to allow the user to choose which player to play against, and once chosen - to create the relevant object and play.
Since the object is created within an if statement, the compiler doesn't let me perform any operations outside the if scope. In other cases I would create the object within the class' scope but in this case I cant know in advance which object to create (human/computer)
Here is some code for illustration:
public class Player {
private String name;
public String getName(){
return name;
}
}
public class HumanPlayer extends Player {
public void play(){
System.out.println("Human playing");
}
}
public class ComputerPlayer extends Player {
public void play(){
System.out.println("Computer playing");
}
}
import java.util.Scanner;
public class PlayerDriver {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please type 1 for human, 2 for computer");
int selection = in.nextInt();
if (selection==1){
HumanPlayer player = new HumanPlayer();
} else if (selection==2){
ComputerPlayer player = new ComputerPlayer();
} else {
throw new IllegalArgumentException("invalid answer");
}
Player.play(); //can't do that
}
}
Harness the power of polymorphism
Player player = null; // player should never be null as you would have thrown an exception, but for the sake of completeness
if (selection == 1){
player = new HumanPlayer();
} else if (selection == 2){
player = new ComputerPlayer();
} else {
throw new IllegalArgumentException("invalid answer");
}
player.play();
assuming the Player class has a play() method. I see it doesn't. Change your class Player to have an override-able play() method which you override in the sub types.

Categories

Resources