Using output of another class as a variable in other class - java

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.

Related

A way to reset program on cmd?

I wrote a simlpe dice game and would like to know a way to reset the program after typing something like "Reset". I use cmd to run my programs. There is no graphics included in any of my programs whatsoever.
import java.util.Scanner;
import java.util.Random;
public class Dice
{
public static void main(String[] args)
{
String personPlay; //User's play
String computerPlay = ""; //Computer's play
int computerInt; //Randomly generated number used to determine computer's play
String response;
Scanner scan = new Scanner(System.in);
Random generator = new Random();
System.out.println("Let's play some dice!");
//Generate computer's play
computerInt = generator.nextInt(6)+1;
//Translate computer's randomly generated play to
//string using if statements
if (computerInt == 1)
computerPlay = "1";
else if (computerInt == 2)
computerPlay = "2";
else if (computerInt == 3)
computerPlay = "3";
else if (computerInt == 4)
computerPlay = "4";
else if (computerInt == 5)
computerPlay = "5";
else if (computerInt == 6)
computerPlay = "6";
//Get player's play from input
System.out.println("Choose a number between 1 and 6.");
personPlay = scan.next();
//Print computer's play
System.out.println("The dice rolled " + computerPlay);
//See if you won.
if (personPlay.equals(computerPlay))
System.out.println("You won!");
else System.out.println("You lost!");
}
}
You should use an infinite loop and get input from user, check if user entered "RESET", if so roll the dice again or do whatever you're doing now.
If he entered a phrase like "EXIT" infinite loop ends or your program ends.
Usually I don't like giving full answers, but there are some improvements I wanted to show and just listing them would be a lot of work as well.
import java.util.Scanner;
import java.util.Random;
public class Dice
{
private static void play(Scanner scan, Random generator)
{
int computersPlay, usersPlay;
System.out.println("Let's play some dice!");
computersPlay = generator.nextInt(6) + 1;
System.out.print("Give a number:");
usersPlay = scan.nextInt();
System.out.printf("The dice rolled %d\n", computerPlay);
if (computersPlay == usersPlay) {
System.out.println("You win !");
}
else {
System.out.println("You lose!");
}
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Random generator = new Random();
do {
play(scan, generator);
System.out.println("If you want to continue type:'Reset'");
} while(scan.next().equals("Reset");
}
}
Changes moving the play to a different method to keep oversight, using the Scanners nextInt method to obtain a number directly and compare that instead, and the do {} while(); statement to let it repeat an arbitrary amount of times (given that you type reset)
By "reset" I assume you meant "repeat"? Use a while loop.
Also, no real need to store String values other than capture what the user entered.
public class DiceGuess {
// Global variables for this class
static Random generator = new Random();
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Let's play some dice!");
// Initialize some variables
int computerInt;
String response;
while (true) { // Play forever
computerInt = generator.nextInt(6) + 1;
System.out.println("Choose a number between 1 and 6. ('quit' to stop playing)");
response = scan.nextLine();
if (response.equalsIgnoreCase("quit")) break; // Stop the game
try {
System.out.println("The dice rolled " + computerInt);
if (Integer.parseInt(response) == computerInt) {
System.out.println("You won!");
} else {
System.out.println("You lost!");
}
} catch (NumberFormatException e) {
System.err.println("That wasn't a number!");
}
}
}
}

Having problems with my random number guess game

I need help with my java code!
Want it to loop threw everything till the user put in the right number. When the user put in wrong number it should say "type in a different number". When the user put in the right number it should say "congrats you won".
But till then it will loop and say "type in a different number" and after 5 tries I want it to say "you failed this mission! do you want to try again?"
import javax.swing.*;
import java.util.Random;
public class Projekt_1 {
public static void main(String[] args) {
String number;
JOptionPane.showMessageDialog(null, "Welcome to the guessing game!" + "\nYou gonna guess a number between 1 and 20." + "\nHOPE YOU LIKE IT!:)");
Random amount = new Random();
int guessnumber = anount.nextInt(20);
int random;
number = JOptionPane.showInputDialog("Guess a number between 1 and 20");
random = Integer.parseInt(number);
while (random == guessnumber){
JOptionPane.showMessageDialog(null, "You won!" + "\nYour number was" + "" + guessnumber);
}
if (random < guessnumber){
number = JOptionPane.showInputDialog("Your number is to high :(" + "\nType in a new lower number!");
random = Integer.parseInt(number);
}else if (random > guessnumber){
number = JOptionPane.showInputDialog("Your number is to low :(" + "\nType in a higher number!");
random = Integer.parseInt(number);
}
}
}
That is because your only iterative statement is only displaying "You won!..etc":
while (random == guessnumber){
JOptionPane.showMessageDialog(null, "You won!" + "\nYour number was" + "" + guessnumber);
}
Enclose the other codes below your while-loop to include them within the while loop. If you indent your codes properly, you should be able to spot your own problem. This is what you are looking for:
while (random != guessnumber){
//prompt for user input
if (random < guessnumber){
//Show Message "Your number is too low...
}
else if (random > guessnumber){
//Show Message "Your number is too high..."
}
else{ //got the number
//Show Message "you won!.."
}
}

Fixing if else if statements for java game

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.

How to reduce code in main method by making new methods for my code?

Hi I am using Eclipse to program a game.
Basically, the user chooses 1. Even or 2. Odd
A randomly generated dice rolls. If the user lands on the choice he made (even number or odd number) he stays otherwise, he moves 5 steps back.
The user is vsing the computer. So if user is Even, computer is Odd, and vice versa
My problem is I don't know how to call this kind of method. Please look at my code and give me advice. If it can be better let me know also.
package Testing;
import java.util.Scanner;
import java.util.Random;
public class hundredsteps {
public static int playerChoice(){
System.out.println("Please choose an option below");
System.out.println("1. Even");
System.out.println("2. Odd");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
return choice;
// player set EVEN by default
}
public static int playerRoll(){
System.out.println("Press enter to roll");
Scanner input = new Scanner(System.in);
String roll = input.nextLine();
Random generator = new Random();
int dice1 = generator.nextInt(6)+1;
int dice2 = generator.nextInt(6)+1;
int sumOfDice = dice1 + dice2;
return sumOfDice;
}
public static int cpuRoll(){
Random generator = new Random();
int dice1 = generator.nextInt(6)+1;
int dice2 = generator.nextInt(6)+1;
int sumOfDice = dice1 + dice2;
return sumOfDice;
}
public static String gameWinner(int player, int cpu){
String winner = " ";
if (player == 100 && cpu == 100){
winner = " TIE ";
System.out.println("TIE GAME!!");
}else if (player == 100){
System.out.println();
winner = " player ";
System.out.println("Congratulations! You've won!");
}else if (cpu == 100){
winner = " cpu ";
System.out.println("Sorry, you lost. The computer won this round");
}
return winner;
}
public static void main(String[] args) {
int playerPosition = 0, cpuPosition = 0;
int playerRoll = 0, cpuRoll = 0;
do{
System.out.println();
playerRoll = playerRoll();
System.out.println();
System.out.println("You rolled " +playerRoll);
playerPosition = playerPosition + playerRoll;
if (playerPosition % 2 == 0){
System.out.println("You are now on step number " +playerPosition);
} else if (playerPosition % 2 != 0){
System.out.println("You landed on an odd number! You must move 5 steps back");
playerPosition = playerPosition - 5;
System.out.println("You are now on step number " +playerPosition);
}
cpuRoll = cpuRoll();
System.out.println("The computer rolled "+cpuRoll);
cpuPosition = cpuPosition + cpuRoll;
if (cpuPosition % 2 != 0){
System.out.println("The computer is now on step number " +cpuPosition);
} else if(cpuPosition % 2 == 0){
System.out.println("The computer landed on an even number! The computer moved 5 steps back");
cpuPosition = cpuPosition - 5;
System.out.println("The computer is now on step number " +cpuPosition);
System.out.println();
}
if (playerPosition > 100){
System.out.println("You rolled too high!");
System.out.println("You moved 20 steps back");
playerPosition = playerPosition - 20;
} if (cpuPosition > 100){
System.out.println("The computer rolled too high");
System.out.println("The computer moves 20 steps back");
cpuPosition = cpuPosition - 20;
}
} while (playerPosition <= 99 && cpuPosition <= 99);
gameWinner(playerPosition, cpuPosition);
}
}
Do you mean all the methods you call in main() keep throwing compile errors if they aren't static, so you "can't" call them?
If thats what you mean, you need to make some code to run/test your code. You need some objects. Java is object oriented (OO), so always think about "things" rather than "procedures/sequences of commands."
For example, make a test class, that will "contain" your "game object"
public class GameTest {
public static void main(String[] args) {
DiceGame game = new DiceGame();
}
}
Put your game in a separate class ( a whole new file):
public class DiceGame {
//all your primitive/object references
//add a constructor
public DiceGame() {
//initialize primitives/objects
play();
}
public void play() {
//game logic goes here
//the stuff you have in main() right now
//this isn't a static method, so call any other methods you want
}
//put your other methods here
}
Then run the file GameTest, not DiceGame. This is just one of several patterns you can use to get your code running.
If this is not what you mean, can you clarify your question?
You must be making this too hard for yourself. If you want all of the code from you main() in another method then make it so.
public static void main(String[] args) {
newMethod();
}
public static void newMethod() {
// All the stuff from your old main goes in here
}
I can only imagine that you don't understand static methods and why the methods you call from your main() must be static.
Alternatively, do exactly what #nexus_2006 said and put your game in it's own class and then in your main() create an instance of that class and start the game from there.
public static void main(String[] args) {
DiceGame game = new DiceGame();
game.play();
}
The main() above can even go inside DiceGame.java. Either way works fine.

How would I create a "infinite" loops until the user decides to call it quits?

I'm having a slight problem.
I have a menu asking to:
reroll
get val
show max
show min
when the user chooses an option I want it to do one of them THEN re ask the menu in a sort of inifinite loop:
code:
import java.io.InputStream;
import java.util.Scanner;
class RecordDice {
public static void main(String[] args){
int dSides, Sides, Choice;
int max, min;
Scanner s = new Scanner(System.in);
Scanner c = new Scanner(System.in);
System.out.println("How many sides should the dice have?");
Sides = s.nextInt();
if(Sides == 4 || Sides == 6 || Sides == 12 || Sides == 20 || Sides == 100){
System.out.println("Please make a choice:\n" +
"1 - reroll the dice\n" +
"2 - get the value\n" +
"3 - show the maximum\n" +
"4 - show the minimum");
} else {
System.exit(-1);
}
Dice2 d = new Dice2(Sides);
int Choice = c.nextInt();
int Value = d.getValue();
switch(Choice){
case 1:
System.out.println();
d.reroll();
break;
case 2:
System.out.println("The current value is " + Value);
break;
case 3:
System.out.println("The maximum is " );
break;
case 4:
System.out.println("The minimun is ");
break;
}
}
}
Would putting the menu in a method and just calling the method every time a option is picked?
You can use a while loop to keep displaying it.
boolean keepGoing = true;
While(keepGoing)
{
//your code
}
Then to end it ask the user if they want to end it an set the boolean to false.
Add "5 - quit" to your menu.
Create a boolean, something like exit, initialized to false.
Add case 5: exit = true; break;
Then wrap the whole thing in while(!exit)
boolean exit = false;
while(!exit) {
//all the code you already have, starting with:
System.out.println("How many sides should the dice have?");
//and ending with the switch statement
//Plus the addition to the menu and addition to the switch statement
}
Ordinarily, I would do something like:
while(true) {
//do stuff
if(someExitCondition) {
break;
}
}
But seeing how as you're handling your user input with a switch statement, my above suggested method seems to be the cleanest way of handling it in this scenario.
Wrap it all in a do-while loop.
boolean userWantsToQuit = false;
do {
// code
// evaluate userWantsToQuit…
} while (!userWantsToQuit);
boolean keepGoing=true;
while(keepGoing)
{
//user input
if(user input to exit)
{
keepGoing=false;
}
}
or
while(true)
{
//user input
if(user input to exit)
{
break;
}
}
Assuming selection of dice sides you will allow only once, put code below that in do while loop.
You may prompt user "Do you wish to continue" after your switch block.
Get that value scanned
Condition in while loop will be something list while("YES".equals(userInput)).. assuming user will input YES or NO strings.

Categories