Exception in thread "main" error when randomising array variables - java

can anyone tell me why I'm getting the error
Exception in thread "main" java.lang.NullPointerException
at test_package.First_class.main(First_class.java:14)
This is my code. it is designed to choose a random Parea and print it to the screen and then the Earea array in the same way. (please ignore the Areabase and the switch unless that is contributing to the error. Areabase is only there temporary)
package test_package;
import java.util.Scanner;
public class First_class {
private static final String[] Parea = null;
private static final String[] Earea = null;
public static void main(String[] args){
int Areabase = 1;
Scanner keyin = new Scanner(System.in);
switch (Areabase) {
case 1:
Parea[1] = "You enter what looks like it was once the ship cafateria but is now in ruin.";
Parea[2] = "You find yourself in a hallway, some of the lights are broken and the doors barely work.";
Parea[3] = "You enter an old storage room and almost slip into the huge hole that has opened up in the floor.";
Parea[4] = "You walk into the ships bathroom, the toilets are overflowing and the soap has a bite out of it.";
Parea[5] = "This seems to be an outdated controll deck, you wonder why it is here then you decide to move on.";
Parea[6] = "You emerge into the libary and almost trip over a stack of books. i lybrarian woould scream at this mess";
Parea[7] = "You find yourself in a room you dont reconise. there is glass all over the ground.";
Parea[8] = "You enter the main controll room. it seems that the entire front of the ship has colapsed.";
Parea[9] = "You walk into the ship's dorm. one room is littered with cat posters. Hang in there one says.";
Parea[10] = "This seems to have once been a black marketing room. you think you now understand the bounty.";
Parea[11] = "You emerge into a rapidly changing simulation room. it changes to a beach, a castle, YOUR SHIP?";
Parea[12] = "You move into the prisoner room. all the cells are open. people must have busted out.";
Parea[13] = "You trip and fall into the life support room. this room is badly dammage, badly badly dammages.";
Parea[14] = "You float into a random empty room. you emediatly know what it is. an anti gravity room.";
Parea[15] = "This room appears to be a half caved in engenerring room. maby you should leave befor those barrels explode.";
Earea[1] = "This room is on fire";
Earea[2] = "An explotion rocks the ship";
Earea[3] = "This room smells foul";
Earea[4] = "you wish you could take this room back to your ship";
Earea[5] = "THIS ROOM IS FILLED WITH ANIME";
int random = (int) Math.floor(Math.random() * (15 - 1) + 1);
int random2 = (int) Math.floor(Math.random() * (5 - 1) + 1);
System.out.println(Parea[random]);
System.out.println(Parea[random2]);
break;
default:
break;
}
}
}
Any ideas?
Thank you for your help :)

you have to set the length for the arrays first use them in Java
change these
private static final String[] Parea = null;
private static final String[] Earea = null;
to this
private static final String[] Parea = new String[16];
private static final String[] Earea = new String[6];

Related

Cannot resolve symbol - ArrayList, Java

I'm writing a code in JAVA that is going to be a Lucky Wheel Game. The game at this stage takes a number as input to start the wheel to turn, get a random element from a collection of prizes and outputs the price. As you can see the code below, I created an array and added it's elements to the ArrayList. The player have 3 turns and at each turn he gets a random price (element) from the ArrayList. Sounds good, but I'm stuck. The problem is, for some reason I get the error of "Cannot resolve symbol 'wheel'. I use IntelliJ IDEA. I just started coding so I'm sure there's gonna be more errors after I resolve this one. But first, I want to solve this, then I can continue the game and add more to it. Thanks for all the answers!
Here's the code:
import java.util.*;
public class Game {
public static void func1(String[] prizes) {
ArrayList<String> wheel = new ArrayList<>(5);
//Adds array elements to ArrayList
Collections.addAll(wheel, prizes);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random randomGenerator = new Random();
String[] prizes = {"Television", "iPhone", "Microwave", "Ventilator", "Gift Card"};
func1(prizes);
int turn = scanner.nextInt(1);
int tries = 0;
int index = randomGenerator.nextInt(wheel.size()); // I get the error here
//int wheel = wheel.size();
while(tries < 3) {
turn = scanner.nextInt(1);
System.out.println("You won a" + wheel.get(index)); // and here too
tries++;
}
}
}

I have made a Java programme but has repetition problem

I have created that Java programme but it have repetition problem, I want that if one question has done either right or wrong it must not be ask again.
It should ask 10 question only. I have tried alot to change but every time I am getting error.
I have created that Java programme but it have repetition problem, I want that if one question has done either right or wrong it must not be ask again.
It should ask 10 question only. I have tried alot to change but every time I am getting error.
package examapp;
import java.util.Random;
import javax.swing.JOptionPane;
public class Examapp {
static int nQuestions = 0; static int nCorrect = 0;
public static void main(String[] args) {
int prevNum=0;
int sum=0;
do{
Random rand = new Random();
int randomNum = rand.nextInt((11 - 1) + 1) + 1;
if(randomNum==prevNum){
prevNum=randomNum;
}
else if(randomNum==1){
String question1;
question1 = "What was the name of Google in late 90s?\n";
question1+="A. Googol\n";
question1+="B. Gigablast\n";
question1+="C. Backrub\n";
question1+="D. Google\n";
question1+="Marks=9";
check(question1,"C");
sum=sum+1;
}
else if(randomNum==2){
String question2;
question2 = "\"Do no evil\" is a tagline of?\n";
question2+="A. Yahoo\n";
question2+="B. Google\n";
question2+="C. Bing\n";
question2+="D. Duck Duck Go\n";
question2+="Marks=9";
check(question2,"B");
sum=sum+1;
}
else if(randomNum==3){
String question3;
question3 = "Which of the following is fully Object Oriented Programming Language?\n";
question3+="A. SmallTalk\n";
question3+="B. Kotlin\n";
question3+="C. Java\n";
question3+="D. F#\n";
question3+="Marks=9";
check(question3,"A");
sum=sum+1;
}
else if(randomNum==4){
String question4;
question4 = "Which among the following is not a mobile Operating System?\n";
question4+="A. Bada\n";
question4+="B. Safari\n";
question4+="C. WebOS\n";
question4+="D. MeeGo\n";
question4+="Marks=9";
check(question4,"B");
sum=sum+1;
}
else if(randomNum==5){
String question5;
question5 = "Which of the following is a correct format of Email address?\n";
question5+="A. info.website.com\n";
question5+="B. info#website.com\n";
question5+="C. info#website#com\n";
question5+="D. info.website#com\n";
question5+="Marks=9";
check(question5,"B");
sum=sum+1;
}
else if(randomNum==6){
String question6;
question6 = "What is the shortcut key of printing a document for computer having windows?\n";
question6+="A. Ctrl + Shift + P\n";
question6+="B. Alt + P\n";
question6+="C. Ctrl + Alt + P\n";
question6+="D. Ctrl + P\n";
question6+="Marks=9";
check(question6,"D");
sum=sum+1;
}
else if(randomNum==7){
String question7;
question7 = "Computer software includes\n";
question7+="A. Packaged programs\n";
question7+="B. Operating system programs\n";
question7+="C. Applications programs\n";
question7+="D. All of these\n";
question7+="Marks=9";
check(question7,"D");
}
else if(randomNum==8){
String question8;
question8 = "A function inside another function is called a _______ function\n";
question8+="A. Nested\n";
question8+="B. Round\n";
question8+="C. Sum\n";
question8+="D. Grouped\n";
question8+="Marks=9";
check(question8,"A");
sum=sum+1;
}
else if(randomNum==9){
String question9;
question9 = "What does HTTP stands for?\n";
question9+="A. Hypertext Transfer Plotter\n";
question9+="B. Hypertext Transfer Plot\n";
question9+="C. Hypertext Transfer Protocol\n";
question9+="D. Head Tail Transfer Protocol\n";
question9+="Marks=9";
check(question9,"C");
sum=sum+1;
}
else if(randomNum==10){
String question10;
question10 = "The term 'Pentium' is realted to\n";
question10+="A. DVD\n";
question10+="B. Hard Disk\n";
question10+="C. Microprocessor\n";
question10+="D. Mouse\n";
question10+="Marks=9";
check(question10,"C");
sum=sum+1;
}
else{
prevNum=randomNum;
}
}while(sum<=9);
JOptionPane.showMessageDialog(null,nCorrect + " correct out of 10" + " questions");
JOptionPane.showMessageDialog(null,"Total Obtained Marks="+(nCorrect*9));
}
public static String ask(String question) {
while(true) {
String answer = JOptionPane.showInputDialog(question);
answer = answer.toUpperCase();
if(!(answer.equals("A") || answer.equals("B") || answer.equals("C") || answer.equals("D"))){
JOptionPane.showMessageDialog(null,"Invalid Answer");
continue;
}
return answer;
}
}
static void check(String question, String correctAnswer) {
nQuestions++;
String answer = ask(question);
if(answer.equals(correctAnswer)) {
nCorrect++;
}
else {
}
}
}
Thank you!
Your main is quite cluttered. By the time you get to the bottom, you have already forgotten what was on top, such as that it is a very large do-while block. If I were you, I would put the questions and answers in an array, list or even better in your own question object. Then you could use array shuffle to put them in different order for each run and omit all the if-else blocks. It is best to also pull your initialization from random out of the loop so that you don't create a new object with every iteration.
In order to answer your question, so that you do not use an already generated random number again, you must somehow remember the already generated ones. For example, use a list.
public static void main(String[] args) {
Random rand = new Random();
List<Integer> list = new ArrayList<>();
int count = 0;
int randomNum;
do{
randomNum = rand.nextInt(10)+1;
while(list.contains(randomNum)){
randomNum = rand.nextInt(10)+1;
}
list.add(randomNum);
count++;
// rest of your code goes here
}while( count < 10);
System.out.println(list);
}

I need to split this data into its own sets so that i may call on them when need

in java code
The main this I have to do is read this file into an internal data structure
I just don't know how to split each room up and keep its data together while being able to call on either the id or description etc. by its self when need but still keeping it as all in the room, so bedroom keeps all its information but when need I can call id or description separably
(this is my data they are rooms with a ID , name , summary about it and its exit ways)
Rooms:
ID=1, name = Bed Room
Description :
You are standing in the middle of a dark room. It's your room, but something feels off everything is gone just a plan dark room.
You see a red light sighing under the door it seems like a way to exit.
You can go North from here out the Door.
exits
North 2;
ID=2, name = Hallway
Description :
You enter the Hallway still noticing a red light, but it's still coming way down at the other end. You look around and notice patches of torn spots on the wall
full of black voids looking spots. Slowly sucking in more of the room. Everything else is black, and grey, just like your room was with more objects missing.
You know the red light is at the other end of the hallway with a entrance to the living room
exits
North 3, South 1;
ID=3, name = Living-room
Description :
You enter the living room its still has some color left, but you notice its slowly fading away on the table in the middle of the room surrounded by to gray couches.
you look over to your East and hear a Scream coming from the Dinning-room
but also notice Movement through the West Leading to the Basement
exits
East 4, West 5, South 2;
ID=4, name = Dinning-room
Description :
You have entered the Dinning-room and Notice shadows moving around the room you feel a cold and lifeless wind.
You are continuing to hear Screams but not from this room its coming from the East that leads to the Front-yard The screams get louder for ever step you get closer
exits
West 3, East 6;
ID=5, name = Basement
Description :
You have enter the Basement its empty and cold never felt temperatures this low. you notice smoke coming out of you mouth but also three different spots in
each corner of the basement also forming smoke just as you are.
There is not Exit other then East where you came from.
exits
East 3;
ID=6, name = Front-yard
Description :
You entered the Front-yard you notices Shadows moving along the lawn back in the fort but no ones there just you and you garden and your thoughts the driveway has no Cars
You notice you're all alone, but it can be possible you hear and see unexceptionable things. The house is floating in a endless void there is no where to go.
your only way is back into the house West
exits
West 4;
Looking at your data, in order to determine an appropriate implementation, I feel that the the exit directions should be an enum.
public enum Direction {
EAST, NORTH, SOUTH, WEST;
}
And an exit is a combination of a direction plus a number, i.e. how many room exits are there in the given direction. So I created a RoomExit class.
public class RoomExit {
private Direction direction;
private int count;
public RoomExit(Direction direction, int count) {
if (count < 0) {
throw new IllegalArgumentException("negative exits");
}
this.direction = direction;
this.count = count;
}
public Direction getDirection() {
return direction;
}
public int getCount() {
return count;
}
}
Finally, your sample data describes a series of rooms where each room has an ID, a name, a description and a number of exits. So I created a RoomData class.
import java.util.ArrayList;
import java.util.List;
public class RoomData {
private int id;
private String name;
private String description;
private List<RoomExit> exits;
public RoomData(int id, String name) {
this.id = id;
this.name = name;
exits = new ArrayList<>();
}
public boolean addExit(RoomExit exit) {
return exits.add(exit);
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public List<RoomExit> getExits() {
return exits;
}
public String toString() {
return String.format("%d %s [%s] %d exits", id, name, description, exits.size());
}
}
Then I created a "driver" class that reads the text file containing the rooms data (I named this file roomdata.txt) and creates a list of rooms.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class RoomTest {
private static final String COMMA = ",";
private static final String DESCRIPTION = "Description :";
private static final String EQUALS = "=";
private static final String EXITS = "exits";
private static final String ID = "ID";
private static final String SEMI_COLON = ";";
private static int getRoomId(String line) {
Objects.requireNonNull(line, "null line");
String[] firstSplit = line.split(COMMA);
if (firstSplit.length != 2) {
throw new IllegalArgumentException("Unexpected line: " + line);
}
String[] secondSplit = firstSplit[0].split(EQUALS);
if (secondSplit.length != 2) {
throw new IllegalArgumentException("Unexpected line: " + line);
}
int roomId = Integer.parseInt(secondSplit[1].trim());
return roomId;
}
private static String getRoomName(String line) {
Objects.requireNonNull(line, "null line");
String[] firstSplit = line.split(COMMA);
if (firstSplit.length != 2) {
throw new IllegalArgumentException("Unexpected line: " + line);
}
String[] secondSplit = firstSplit[1].split(EQUALS);
if (secondSplit.length != 2) {
throw new IllegalArgumentException("Unexpected line: " + line);
}
return secondSplit[1].trim();
}
private static void setRoomExits(RoomData room, String line) {
Objects.requireNonNull(line, "null line");
line = line.trim();
if (line.endsWith(SEMI_COLON)) {
line = line.substring(0, line.length() - 1);
}
String[] exits = line.split(COMMA);
for (String exit : exits) {
exit = exit.trim();
String[] parts = exit.split(" ");
if (parts.length != 2) {
throw new IllegalArgumentException("Unexpected exit: " + exit);
}
RoomExit roomExit = new RoomExit(Direction.valueOf(parts[0].trim().toUpperCase()),
Integer.parseInt(parts[1].trim()));
room.addExit(roomExit);
}
}
public static void main(String[] args) {
try (FileReader fr = new FileReader("roomdata.txt");
BufferedReader br = new BufferedReader(fr)) {
boolean isExits = false;
List<RoomData> rooms = new ArrayList<>();
RoomData room = null;
String line = br.readLine();
StringBuilder description = null;
while (line != null) {
if (line.startsWith(ID)) {
if (room != null) {
isExits = false;
room.setDescription(description.toString());
rooms.add(room);
description = null;
}
room = new RoomData(getRoomId(line), getRoomName(line));
}
else if (DESCRIPTION.equals(line)) {
description = new StringBuilder();
}
else if (EXITS.equals(line)) {
isExits = true;
}
else {
if (isExits) {
setRoomExits(room, line);
}
else {
description.append(line);
description.append(System.lineSeparator());
}
}
line = br.readLine();
}
if (room != null) {
room.setDescription(description.toString());
rooms.add(room);
}
System.out.printf("There are %d rooms.%n", rooms.size());
rooms.forEach(System.out::println);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
Here is the output when running the above "driver" program.
There are 6 rooms.
1 Bed Room [You are standing in the middle of a dark room. It's your room, but something feels off everything is gone just a plan dark room.
You see a red light sighing under the door it seems like a way to exit.
You can go North from here out the Door.
] 1 exits
2 Hallway [You enter the Hallway still noticing a red light, but it's still coming way down at the other end. You look around and notice patches of torn spots on the wall
full of black voids looking spots. Slowly sucking in more of the room. Everything else is black, and grey, just like your room was with more objects missing.
You know the red light is at the other end of the hallway with a entrance to the living room
] 2 exits
3 Living-room [You enter the living room its still has some color left, but you notice its slowly fading away on the table in the middle of the room surrounded by to gray couches.
you look over to your East and hear a Scream coming from the Dinning-room
but also notice Movement through the West Leading to the Basement
] 3 exits
4 Dinning-room [You have entered the Dinning-room and Notice shadows moving around the room you feel a cold and lifeless wind.
You are continuing to hear Screams but not from this room its coming from the East that leads to the Front-yard The screams get louder for ever step you get closer
] 2 exits
5 Basement [You have enter the Basement its empty and cold never felt temperatures this low. you notice smoke coming out of you mouth but also three different spots in
each corner of the basement also forming smoke just as you are.
There is not Exit other then East where you came from.
] 1 exits
6 Front-yard [You entered the Front-yard you notices Shadows moving along the lawn back in the fort but no ones there just you and you garden and your thoughts the driveway has no Cars
You notice you're all alone, but it can be possible you hear and see unexceptionable things. The house is floating in a endless void there is no where to go.
your only way is back into the house West
] 1 exits

How do I pick 4 different texts from an arraylist without repitition

The app works fine, but the answers on the buttons are sometimes repeating themselves.
How can I prevent that from happening?
This is what have tried so far.
public class RiddleGuessActivity extends AppCompatActivity {
TextView riddleQuestionTextView;
Button btn1, btn2, btn3, btn4;
ArrayList<String> riddles = new ArrayList<>();
ArrayList<String> answers = new ArrayList<>();
int locationOfCorrectAnswers = 0,incorrectAnswers;
int riddleCounter = 0;
ArrayList<String> options = new ArrayList<>();
public void generateRiddles () {
riddles.add("I kiss my mother before i die. What am i ?");
riddles.add("It is greater than God and more evil than the devil. The poor have it, the rich need it and if you eat it you'll die. What am i ?");
riddles.add("It walks on four legs in the morning, two legs at noon and three legs in the evening. What am i ?");
riddles.add("I am the beginning of the end, and the end of time and space. I am essential to creation and i surround everyplace. What am i ?");
riddles.add("What always runs but never walks, often murmurs, never talks, has a bed but never sleeps, has a mouth but never eats. What am i ?");
riddles.add("At night they come without being fetched, By day they are lost without being stolen. What am i ?");
riddles.add("The one who makes it, sells it. The one who buys it, never uses it. The one that uses it never knows that he's using it. What am i ?");
riddles.add("The more you have of it, the less you see. What am i ?");
riddles.add("I am always hungry, i must be fed, the finger i touch will soon turn red. What am i ?");
riddles.add("If you break me, i do not stop working, if you touch me, i may snared, if you lose me, nothing will matter. What am i ?");
answers.add("Matches");
answers.add("Nothing");
answers.add("Man");
answers.add("Letter E");
answers.add("River");
answers.add("The Stars");
answers.add("A Coffin");
answers.add("Darkness");
answers.add("Fire");
answers.add("Heart");
Random random = new Random();
riddleQuestionTextView.setText(riddles.get(riddleCounter));
locationOfCorrectAnswers = random.nextInt(4);
options.clear();
for (int i = 0; i < 4; i++) {
if (i == locationOfCorrectAnswers) {
options.add(answers.get(riddleCounter));
}else {
incorrectAnswers = random.nextInt(riddles.size());
while (incorrectAnswers == riddleCounter) {
incorrectAnswers = random.nextInt(riddles.size());
}
options.add(answers.get(incorrectAnswers));
}
}
btn1.setText(options.get(0));
btn2.setText(options.get(1));
btn3.setText(options.get(2));
btn4.setText(options.get(3));
}
try this
for (int i = 0; i < 4; i++) {
if (i == locationOfCorrectAnswers &&
!options.contains(answers.get(riddleCounter))) {
options.add(answers.get(riddleCounter));
}else {
incorrectAnswers = random.nextInt(riddles.size());
while (incorrectAnswers == riddleCounter) {
incorrectAnswers = random.nextInt(riddles.size());
}
if(!options.contains(answers.get(incorrectAnswers)))
options.add(answers.get(incorrectAnswers));
else --i;
}
}
that should prevent duplicates
EDIT: added full code
EDIT2: fixed indexOutOfBounds exception

Instance of a Method in a Separate Class/Method?

I am creating a small game of Final Fantasy characters, in which I input the name of who I would like to "fight" I have each character (only 5 of them) as a subclass to a superclass called Stats in which the variables (non static) and getters/setters are defined.
The code all works as I would like, but I don't like it all being in One huge class.
The Main method is here;
package com.George.revision;
import java.util.Random;
import com.George.characters.Cloud;
import com.George.characters.Squall;
import com.George.characters.Stats;
import com.George.characters.TheEnemy;
import com.George.characters.ThePlayer;
import com.George.characters.Tidus;
import com.George.characters.Yuna;
import com.George.characters.Zidane;
import com.George.input.GetInput;
import com.George.input.ListNames;
public class Main {
public static void main(String[] args) {
ListNames.listNames();
Stats clo = new Cloud();
Stats squ = new Squall();
Stats zid = new Zidane();
Stats tid = new Tidus();
Stats yun = new Yuna();
String versus = GetInput.getInput("\nWhich of these Characters would you like to go up against?");
Stats ene1 = new TheEnemy();
switch (versus) {
case "Cloud":
ene1.setName(Names.CLOUD);
ene1.setHairColor(Stats.BLONDE);
ene1.setWep(Weapons.BUSTER_SWORD);
ene1.setSkill(clo.skill);
ene1.setAp(clo.ap);
ene1.setStr(clo.str);
ene1.setMag(clo.mag);
break;
case "Squall":
ene1.setName(Names.SQUALL);
ene1.setHairColor(Stats.BLACK);
ene1.setWep(Weapons.LIONHEART);
ene1.setSkill(squ.skill);
ene1.setAp(squ.ap);
ene1.setStr(squ.str);
ene1.setMag(squ.mag);
break;
case "Zidane":
ene1.setName(Names.ZIDANE);
ene1.setHairColor(Stats.LIGHTBROWN);
ene1.setWep(Weapons.THIEF_DAGGER);
ene1.setSkill(zid.skill);
ene1.setAp(zid.ap);
ene1.setStr(zid.str);
ene1.setMag(zid.mag);
break;
case "Tidus":
ene1.setName(Names.TIDUS);
ene1.setHairColor(Stats.BLONDE);
ene1.setWep(Weapons.CALADBOLG);
ene1.setSkill(tid.skill);
ene1.setAp(tid.ap);
ene1.setStr(tid.str);
ene1.setMag(tid.mag);
break;
case "Yuna":
ene1.setName(Names.YUNA);
ene1.setHairColor(Stats.DARKBROWN);
ene1.setWep(Weapons.NIRVANA);
ene1.setSkill(yun.skill);
ene1.setAp(yun.ap);
ene1.setStr(yun.str);
ene1.setMag(yun.mag);
break;
default:
System.out.println("You did not enter a valid character name");
break;
}
System.out.println("You have chosen to face " + ene1.name);
System.out.println("Enemy Skill = " + ene1.skill + " Enemy Weapon = " + ene1.wep);
System.out.println("Enemy Skill = " + ene1.skill + " Enemy Weapon = " + ene1.wep);
int eneTotal = ene1.skill + ene1.ap + ene1.str + ene1.mag;
Stats player = new ThePlayer();
String plN = GetInput.getInput("What is your name?");
player.playerName = plN;
System.out.println("So Your name is " + player.playerName);
String plWep = GetInput.getInput("What is your Weapon's name?");
player.playerWep = plWep;
System.out.println("So your Weapon is " + player.playerWep);
Random generator = new Random();
int plSkill = generator.nextInt(10);
player.skill = plSkill;
System.out.println("Your skill level is " + player.skill);
Random gn = new Random();
int plAp = gn.nextInt(10 - 5) + 5;
System.out.println("So your Attack Power is " + plAp);
player.ap = plAp;
Random gns = new Random();
int plStr = gns.nextInt(10);
System.out.println("So your Strength is " + plStr);
plStr = player.str;
Random gnm = new Random();
int plMag = gnm.nextInt(10 - 5) + 5;
player.mag = plMag;
System.out.println("So your Magic is " + player.mag);
int plHax = 15;
double doubleResult = plHax;
double ene1Hax = 3.99;
int intResult = (int)ene1Hax;
double doubleValue = 6.99;
Double doubleObj = new Double(doubleValue);
int intR = doubleObj.intValue();
System.out.println(intR);
int plyrTotal = player.skill + player.ap + player.str + player.mag;
if (plyrTotal > eneTotal) {
System.out.println("Congratulations you beat " + ene1.name + " Please Play Again!" );
} else if (plyrTotal == eneTotal) {
System.out.println("You drew with " + ene1.name + " Play again and Win!");
}
else
{
System.out.println("You were not succesful this time " + ene1.name + " Defeated you by " + (eneTotal - plyrTotal) + " Please Try Again");
}
}
}
Now after this I have a whole lot more code generating random numbers for the players "stats", and the character, and then matching the total values of their stats to determine "a winner" which I would like to put in a separate class. My issue is,
how do I get ene1 in a separate class with the values that are input in the switch statement in the Main class.
Updated to full main method just for clarity
One of the issues you have is that you are assigning Enemy as a subclass of Stats, but with no relation to your characters. So while the enemy has the same attributes of a character, it has no relationship in which to speak to the character. Instead of copying all of these values like name and color, instead make Enemy it's own entity that holds a Stats value, that shares an interface with stats. The enemy can then use that interface to call various methods in the Stats class.
public class Static implements Actions{
// ...
}
public class Enemy implements Actions{
private Static characterType;
}
Also for future reference, could you please design your questions to be more generic? It not only helps those who don't understand the references, but also makes it easier for people who have similar problems to find this.
You can just pass it into a method (or constructor) of that class as you would any other variable or text. I.e.
clo.setOpponent(ene1);
Then have the implementation of setOpponent be like this
class Stats
{
private Stats opponent;
//ALL OF YOUR OTHER CODE AND METHODS GO HERE
public void setOpponent(Stats enemy)
{
opponent = enemy;
}
}
This doesn't take into account the poor OO design of your application, it only answers your question. Better design comes with more practice and some studying (look up IS-A and HAS-A relationships to help with basic OO design)
In your particular example I would suggest to have Enumerations for the enemies, instead of using class hierarchy, as you have got the same fields for all enemy entities and you're not using any external storage here (like DB, file or whatever).
Class hierarchies are more suitable for situations, when you have several entities which have got both similarities and distinguishes. For example, you can have one class for regular enemies, and one class for 'enforced' enemies with some superskills, so the second class will inherit the first one and will have 1 additional field. This allows you to reduce the code duplicates and provides enough flexibility. Also, class hierarchy gives you some more benefits when you want to save this entities in some storage, for example, DB.
But in you case, it is more logical to use a single Enum to have some set of enemies, which is 'hardcoded' to the application. I would suggest the next solution:
public enum Enemy {
CLOUD("Cloud", "Red", "Sword", 10),
SQUALL("Cloud", "Black", "Minigun", 999)
// and so on
;
public String name;
public String hairColor;
public String wep;
public int skill;
Enemy(String name, String hairColor, String wep, int skill /* and so on */) {
this.name = name;
this.hairColor = hairColor;
this.wep = wep;
this.skill = skill;
}
public static Enemy getByName(String name) {
for (Enemy enemy : Enemy.values()) {
if (enemy.name.equalsIgnoreCase(name)) {
return enemy;
}
}
throw new IllegalArgumentException("Enemy with the name `" + name + "` doesn't exist.");
}
}
And then it is possible to initialize an enemy in the main class by its key name:
String versus = GetInput.getInput("\nWhich of these Characters would you like to go up against?");
try {
Enemy enemy = Enemy.getByName(versus);
} catch (IllegalArgumentException e) { // processing incorrect input
System.out.println(e.getMessage());
}
Then you can pass this constant to any other class to process it and calculate whatever you want:
public class FightCalculator {
public int calculateScore(Enemy enemy) {
// Some calculations here...
}
}
It might help to create separate Hero and Enemy classes. Or if your characters aren't "good" or "bad" guys, perhaps just a Character class. For the following discussion, I will simply use Character, but you can replace this with Hero or Enemy and it should still make sense.
First of all, what is the relationship between a Character and a Stats. I think a Characater has a Stats. This means that Character should have a member variable of type Stats:
class Character {
private Stats stats = new Stats();
}
Now you can add a constructor that a new Stats object for a Character. This means that the Character needs to take several parameters for each of the values stored in a Stats. One advantage of this approach is that you write the code to set up a Stats object just once and then each case statement has just 1 line:
ene1 = new Character(/* all the stats values go here */);
The moral of the story here is that when you find yourself repeating code, you should consider writing a method which encapsulates that repetition.

Categories

Resources