String option = (String) JOptionPane.showInputDialog(frame,
"A wooden crate appears! It looks ready to kick your butt!",
"Battle!",
JOptionPane.QUESTION_MESSAGE,
null,
attacks,
attacks[0]);
if (option.equals("slash"))
{
damage = (int)(Math.random()*(stick.getMax()-stick.getMin()) + stick.getMin());
}
else if (option.equals("magic"))
{
if (playerMana >= 25)
{
damage = (int) intellect*((stick.getMax()-stick.getMin())/2) + (int)Math.round(Math.pow(playerLevel, 1.20));
playerMana -= 25;
}
else
{
damage = 0;
}
}
else if (option.equals("run"))
{
out.println("fail! you run from the fight!");
}
else if (option.equals("healing") && healPots >= 1)
{
playerHp+= (playerHp*0.15);
}
else
{
out.println("you have no potions! Get some in town to heal your hp!");
}
Stick is just a weapon object I made with min max damage values. Player hp and mana are both 100. healPots is 0.
I am trying to make a rpg style fighting system where the player picks options and takes turns. However, the loop automatically skips to the final else regardless of what is chosen.
When you ask a question on SO, it is always a good idea to provide a minimal, running example.
I removed the actual game logic from your code and replaced frame with null:
public class ShubhankarsQuestion
{
public static void main(String[] args)
{
String[] attacks = {"slash", "magic", "run", "healing"};
String option = (String) JOptionPane.showInputDialog(null,
"A wooden crate appears! It looks ready to kick your butt!",
"Battle!", JOptionPane.QUESTION_MESSAGE,
null, attacks, attacks[0]);
if (option.equals("slash"))
{
System.out.println("You chose slash...");
}
else if (option.equals("magic"))
{
System.out.println("You chose magic...");
}
else if (option.equals("run"))
{
System.out.println("You chose run...");
}
else if (option.equals("healing"))
{
System.out.println("You chose healing...");
}
else
{
System.out.println("you have no potions! Get some in town to heal your hp!");
}
}
}
This works perfectly. Either you haven't shown us the actual code, or your problem lies elsewhere.
Can you show us the definition of the variable attacks?
String[] attacks = {"slash!", "magic!", "healing!", "run!"};
Well, there you have it. You compare "slash!" with "slash", which certainly isn't equal :)
Either remove the exclamation marks from the array, or add them to the compared strings.
Related
I have a program where i'm required to seperate as much out as possible as different methods and classes.
I have a rng, thats a class. I want to use the output from the rng in another class to compare it against a user selection to decide if they win or lose.
This is my rng.
package stockGame;
import javax.swing.JOptionPane; // Import this just in case I need a popup window
import java.util.Random; // Import this so i can use the random number
//The purpose of this class is to generate a random number between 1 and 12
public class Dice {
public static void Dice(){
Random random = new Random ();
JOptionPane.showMessageDialog(null,"The Computer picked " + (random.nextInt(12)+1));
}
}
Here is my if loop in the second class. I want to be able to say. If (option ==1 AND RNG is GREATER/LESS/EQUAL to 6){
That way it can compare and decide if the user has won or lost.
if (option ==1){
output = "You chose to trade less than £6 and the computer rolled RNG, so you win/lose,";
JOptionPane.showMessageDialog(null, output, "The Message", JOptionPane.INFORMATION_MESSAGE);
}
if (option ==2){
output = "You chose to trade more than £6";
JOptionPane.showMessageDialog(null, output, "The Message", JOptionPane.INFORMATION_MESSAGE);
}
if (option==3){
output = "You chose to trade exactly £6";
JOptionPane.showMessageDialog(null, output, "The Message", JOptionPane.INFORMATION_MESSAGE);
}
Hoping to get the ouput generated from RNG class to be used in another class
You have to return the value from the Dice Method:
public class Dice {
public static int Dice(){
Random random = new Random ();
int randomNum = random.nextInt(12)+1;
JOptionPane.showMessageDialog(null,"The Computer picked " + randomNum);
return randomNum;
}
}
The if-statement should be something like this:
if(option == 1 && Dice.Dice() == 6)
{
//do something
}
First of all, in order to return something from a method, that method signature must be set to return something different from void, in your case int:
public class Dice {
public static int dice() {
Random random = new Random ();
int picked = random.nextInt(12)+1;
return picked;
}
}
and then use it:
int picked = Dice.dice();
JOptionPane.showMessageDialog(null,"The Computer picked " + picked);
if (option == 1 && picked < 6) {
output = "You chose to trade less than £6 and the computer rolled RNG, so you win/lose,";
}
if (option == 2 && picked > 6) {
output = "You chose to trade more than £6";
}
if (option == 3 && picked == 6) {
output = "You chose to trade exactly £6";
}
JOptionPane.showMessageDialog(null, output, "The Message", JOptionPane.INFORMATION_MESSAGE);
As you can see, I moved the message outside of the dice method because it's better to let do only a single task for each method, and by doing so you'll can reuse the dice method for other purposes without the need to show the message.
A little confused on where to put another if-else statement after one. like do I put it under the if statement ("have you registered to vote yet?" ) or do i put it under the else statement?
I wanted it to answer if yes then it would print out "you can vote" and if no then it would print out "You must register before you can vote"
here's the code
import java.util.Scanner;
public class voting {
public static void main(String[] args) {
int yourage, votersage;
votersage = 18;
Scanner input = new Scanner(System.in);
System.out.println("How old are you? ");
yourage = input.nextInt();
if (yourage >= votersage) {
System.out.println("Have you registered to vote?");
}
else {
System.out.println("You are too young to vote");
}
}
}
I think this works to how you want it. You may need to change around the input'Registered as I am a bit rusty with inputs but I think this should work?
if (yourage >= votersage) {
Scanner input = new Scanner(System.in)
System.out.println("Have you registered to vote?");
Registered = input.next();
if Registered = ("Yes") {
System.out.println("You can vote");
}
else if Registered = ("No"){
System.out.println("You need to register to vote");
}
else:
System.out.println("INVALID INPUT")
}
else {
System.out.println("You are too young to vote");
}
For elif statements you put the elif before the else, but make sure to add a clause for the elif statement to run just like you did with the original if statement.
if (yourage >= votersage) {
System.out.println("Have you registered to vote?");
}
else if (yourage <= votersage){
System.out.println("You must register before you can vote.");
}
else {
System.out.println("You are too young to vote");
}
Nested if statement work in these scenarios...
if (yourage >= votersage)
{
System.out.println("Have you registered to vote?");
bool registered = input.next();
if(registered)
{
System.out.println("You can vote");
}
else
{
System.out.println("Please get yourself register on voting portal!");
}
}
else {
System.out.println("You are too young to vote");
}
Hi I'm making a game where the player is met with a robot and the robot asks it to guess a number between 1-10. The player has three tries or they die. I've written all my code and the guessing works fine but whenever the play gets it right he still dies. I added a couple of print statements to see what value my code was returning and it seems to be returning the wrong value. Can someone help me out? Thanks.
Goes from this class
if (choice != -1) {
if (john[choice] != null) {
if (john[choice].compPlayerAttack()) {
System.out.print("IT'S GAME OVER MAN!\n");
System.exit(0);
}
else {
System.out.println("Robot appears. Guess a number between 1-10. Get it right and you can pass, or you die. You have three chances.\"");
int answer = 0;
john[choice].toPass(answer);
if (answer== 1) {
System.out.println(answer);
map[x][y].removeJohnPlayer();
}
else { System.out.println(answer);
System.out.print("IT'S GAME OVER MAN!\n");
System.exit(0);
}
To this class
public int toPass(int right){
int hiddenNum = numram.nextInt(MAX_NUMBER);
Scanner input = new Scanner(System.in);
int numOfGuesses = 0;
int a = right;
do {
System.out.println("Enter a number by guessing: ");
int guessedNum = input.nextInt();
numOfGuesses++;
if (guessedNum == hiddenNum) {
System.out.println("Darn! Your number is matched. You may live.");
System.out.println("You have made " + numOfGuesses + " attempts to find the number!");
a = 1;
break;
} else if (guessedNum < hiddenNum) {
System.out.println("Try a bigger number");
} else if (guessedNum > hiddenNum) {
System.out.println("Try a smaller number");
}
} while (numOfGuesses < 3);
System.out.println(a);
return a;
}
Here
john[choice].toPass(answer);
you are ignoring the value returned by your toPass method.
Change it to:
answer = john[choice].toPass(answer);
BTW, there's no reason to pass an argument to your toPass method, since it makes no use of it, and it can't change it (since Java is a pass by value language). A return value is enough.
i.e. change your method to public int toPass().
Another change you should make is to change the return type to boolean. Returning true or false is more readable than returning 1 or 0.
So I wrote a java code for a numbers guessing game. The entire thing is pretty much done. It works by choosing a random number then asking the user for console inputs and then saying whether that is higher or lower than the random number. Once you guess it, it then asks if you want to play again. When you finally say no to this (be it one game or several) it prints out your Overall results including total games, total guesses, avg guesses/game and your best game. I have everything worked out except I cant figure out how to make it print your overall best game.
import java.util.*; //so I can use scanner
public class GuessingGame {
public static void main(String[] args) {
Random rand = new Random ();
int max = 100;
Scanner input = new Scanner(System.in);
int guess;
boolean play = true;
int totalGames = 0;
int totalGuesses = 0;
System.out.println("Can you guess the word?");
System.out.println("I am sure you cannot guess!");
System.out.println("Go ahead and try!");
System.out.println();
while (play) {
System.out.println("I'm thinking of a number between 1 and " + max + "...");
int numberToGuess = rand.nextInt(max) + 1;
int numberOfTries = 0;
boolean win = false;
while (!win) {
System.out.print("Your guess? ");
guess = input.nextInt();
numberOfTries++;
if (guess == numberToGuess) {
win = true;
} else if (guess > numberToGuess) {
System.out.println("It's lower.");
} else if (guess < numberToGuess) {
System.out.println("It's higher.");
}
input.nextLine();
}
if (numberOfTries == 1) {
System.out.println("You got it right in " + numberOfTries + " guess!");
} else {
System.out.println("You got it right in " + numberOfTries + " guesses!");
}
totalGames++;
totalGuesses+= numberOfTries;
System.out.print("Do you want to play again? ");
String answer = input.nextLine();
char firstLetter = answer.charAt(0);
if (firstLetter == 'y' || firstLetter == 'Y') {
play = true;
} else {
play = false;
}
System.out.println();
}
System.out.println("Overall results:");
System.out.println("Total games = " + totalGames);
System.out.println("Total guesses = " + totalGuesses);
System.out.println("Guesses/game = " + totalGuesses/totalGames);
System.out.println("Best game = ");
}
}
In order to get the best game you need a keep track of the best best after each game, such as a variable that checks it there is a new best game after each game.
Keep track of the best score, which is the lowest number of guesses.
int bestGame = Integer.MAX_VALUE; // at the top
bestGame = Math.min(bestGame, numberOfTries); // at the end of your inner while loop
The worst possible score is the highest number of guesses, which is limited by Integer.MAX_VALUE, so you start there.
By the best game u mean minimum number of tries needed to answer is the best game.
/* int mintries,bestgame,gamenumber=0;
bestgamenumber=0;mintreies=Integer.MAX_VALUE:*/
Add the above lines above your while(play)
gamenumber++;
/*if(mintries>numberOfTries)
{
mintries=numberOfTries;//update mintries
betgame=gamenumber;
}*/
Add the if condition just before closing while(play).
So it will be like
int mintries;
mintreies=Integer.MAX_VALUE:
int gamenumber=0;
int bestgamenumber=0//if you want to print the which game is the best game(!st,2nd,3rd..) ;
while(play)
{
// do all your stuff
gamenumber++;
if(mintries>numberOfTries)
{
mintries=numberOfTries;//update mintries
bestgamenumber=gamenumber;
}
}
}
System.out.println("Game number +bestgamenumber+"was the best game with"+ mintries+"tries);
I am considering that you want to print which game (1st,2nd,3rd)is best and minimum tries made to guess the best game.Correct me if i am wrong.
To fit into the code you have already written, You could
Create a new 'global' variable, for example int bestGame = Integer.MAX_VALUE;.
Whenever the user is done with a game do a check if the current numberOfGuesses is smaller than the current bestGame, and if it is, then overwrite bestGame with the current numberOfGuesses.
At the end, you simply need to output bestGame.
I have been unable to find something related to this so far. I've heard that surrounding the majority of your program in a while loop like this makes the program inefficient, is there any better way to get the same effect?
while (1 == 1) {
//User Input
System.out.println("Do you wish to roll? (Y/N)");
if (kb.hasNext()) {
userContinue = kb.next();
}
if (userContinue.equalsIgnoreCase("n")) {
System.exit(0);
}
//Calculations
score = 0;
while (userContinue.equalsIgnoreCase("Y")) {
rollResult = user.rollTwoDie();
score = rollResult + score;
if (score > 21) {
System.out.println("You loose for going over 21.");
System.out.println("Your final score was: " + score);
score = 0;
System.out.println("Play again? (Y/N)");
if (kb.hasNext()) {
userContinue = kb.next();
}
if (userContinue.equalsIgnoreCase("n")) {
System.exit(0);
}
}
else if (score <= 21) {
System.out.println("Your score is: " + score);
System.out.println("Roll again? (Y/N)");
if (kb.hasNext()) {
userContinue = kb.next();
}
}
}
if (userContinue.equalsIgnoreCase("N")) {
while (computerScore <= score && computerScore < max) {
computerResult = computer.rollTwoDie();
computerScore = computerResult + computerScore;
}
userContinue = computer.checkComputerScore(computerScore, score);
}
}
I'm not Java guy, but in many languages 1==1 is usually optimized to true anyway.
So you can use while(true) or while(1==1) or even while (2==2).
It doesn't matter.
In your case it doesn't matter even more, because your while loop is not forcing CPU to work a lot. Your loop is waiting for user input for most of the time. Don't worry about this in this case.
While loops can be extremely inefficient in some cases. In these cases - it's better to use Events instead of loops.
Theoretical example of very incorrect inefficient while loop:
while(true)
{
if(textBox1.Text == "yes") x = 1;
if(textBox1.Text == "no") x = 2;
if (x == 1) doSomething();
if (x == 2) doSomethingElse();
}
It is very inefficient, because you "ask" interface about data in textbox again and again, and there is no reason to do this. There is no pause, CPU and memory are forced to do same thing again and again without pause. In this case - Event should be used.
Events exist in many programming languages. There are many sites, videos and tutorials explaining Events.
Take a look at this video about Events in Java:
Java Programming Tutorial - 52 - Event Handling on Youtube (by Bucky Roberts)
After watching this (and maybe few more Bucky or other tutorial videos) you should understand better why while loops are bad idea sometimes.
It's not necessarily inefficient. It will just run endlessly. If you want that then this isn't necessarily evil.
One thing you may consider is adding a stop boolean. That way you can ask the user if they want to quit, and set the variable to true/false.
boolean stop = false;
while(stop == false) {
//...
}
Also, stylistically I like doing infinite while loops like this:
while(true) {
//...
}
Instead of using "1==1"