I am trying to modify my friend's simple Text Adventure in Java. I am trying to add a ‘quit’ option to the menu, and modify the loop in the main() method so that it exits if the user enters this command.
But this code stops the game from the very beginning no matter what the input is:
while (playerLocation==10);
System.out.println("You won the game");
break;
And this produces an error:
while(scanner.equals("9")) {
System.out.println("You have quit the game.");
break;
}
Full code below:
package practice;
import java.util.Scanner;
public class practice
{
private final int NO_EXIT = 99999; // indicates that there is no exit in that direction
private int map[][] = {{NO_EXIT,1,NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT}, // 1
{2,NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT}, // 2
{NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,3,NO_EXIT,NO_EXIT}, // 3
{NO_EXIT,NO_EXIT,4,NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT}, // 4
{NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,5}, // 5
{NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,6,NO_EXIT,NO_EXIT}, // 6
{NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,7}, // 7
{NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,8,NO_EXIT}, // 8
{9,NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT}, // 9
{NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT,NO_EXIT}}; // 10
private String description[] = {"(Stage 1) stranded in dead-looking forest. You are trying to find your way out of here. You then see a pathway heading east.",
"(Stage 2) now in a large abandoned military base. There is no other way around and you see another pathway heading north.",
"(Stage 3) now brought by the path you took here in an abandoned farmhouse. You now see a cave up ahead on the northwest",
"(Stage 4) now inside a cave. It has an entrance to the west.",
"(Stage 5) currently in the left wing of the cave. On the southwest there is an entrance leading somwhere.",
"(Stage 6) halfway through to your escape. You are in the bottom of the cave. \nThere is a small hole ahead on your northeast, but you can fit right through",
"(Stage 7) inside a section where there is a body of water. On your southwest direction, you see a ladder leading somewhere.",
"(Stage 8) inside a slightly dark hallway. You see a light ahead in the southeast direction.",
"(Stage 9) now outside the cave. You see a path heading north connecting towards an establishment.",
"(Stage 10) finally on your destination!"};
private String objectName[] = {"An adult magazine", "A fully loaded .45 calibre gun", "A motherboard from the 90s", "A syringe",
"A skull", "A worn out pair of shoes", "A Matchbox", "A Wooden Plank", "Illegal Drugs", "A bottle of whiskey" };
private int objectLocation[] = {0, 1, 3, 1, 2, 0, 7, 6, 2, 1};
private int playerLocation = 0;
// Prints out a description of the location the player is currently in, including a list of any objects at that location
private void describeLocation()
{
System.out.println();
System.out.println("You are " + description[playerLocation]);
System.out.println("\n\t\tIn this area, you found: ");
int numObjects = 0;
for (int i=0; i<objectLocation.length; i++)
{
if (objectLocation[i]==playerLocation)
{
System.out.println("\n\t\t" + objectName[i]);
numObjects++;
}
}
if (numObjects==0)
{
System.out.println("\n\t\tNo Item(s)");
}
System.out.println();
}
// implements a simple text-driven menu
private int getMenuSelection(Scanner s)
{
// display menu
System.out.println("What do you want to do?");
System.out.println("1. Go North");
System.out.println("2. Go East");
System.out.println("3. Go West");
System.out.println("4. Go South");
System.out.println("5. Go North East");
System.out.println("6. Go North West");
System.out.println("7. Go South East");
System.out.println("8. Go South West");
System.out.println("9. Quit Game");
System.out.print("Enter command (1-9): ");
// get and return the user's selection
return s.nextInt();
}
// try to move in the specified direction
private void move(int direction)
{
int nextLocation = map[playerLocation][direction];
if (nextLocation==NO_EXIT)
{
System.out.println("\nThere is no way there. Try again!");
}
else
{
playerLocation = nextLocation;
}
}
public void startGame()
{
Scanner scanner = new Scanner(System.in);
do
{
describeLocation();
int selection = getMenuSelection(scanner);
move(selection-1);
while (playerLocation==10);
System.out.println("You won the game");
break;
} while (true);
}
public static void main(String[] args)
{
practice adv = new practice();
adv.startGame();
}
}
So basically what I need to know is how to put an inventory after those things are corrected.
Thank you.
One of your many problems is this code snippet:
while (playerLocation==10); // < Semi colon here means loop forever if playerLocation==10
System.out.println("You won the game");
break; // This will always happen.
You probably wanted this instead:
playerLocation = scanner.nextInt();
if (playerLocation==10){
System.out.println("You won the game");
break; // this will break the outer loop
}
First of all, the playerLocation can never be 10, your array size is only 9. You have to start counting from 0 not from 1. The first value in an array is 0.
while (playerLocation == 9) {
System.out.println("You won the game");
break;
}
The next one is, that your moving to the direction, not to the new position. If the player want to go east, you change the position to the location 2 in the array.
So think about it and work with a switch case. It could be like this.
// try to move in the specified direction
private void move(int direction) {
int x = 0;//this should be the actual position of the player
int y = 0;//this should be the actual position of the player
switch (direction) {
case 0:
System.out.println("up");
y++;
break;
case 1:
System.out.println("down");
y--;
break;
case 2:
System.out.println("left");
x--;
break;
case 3:
System.out.println("right");
x++;
break;
default:
break;
}
}
Related
I had a prompt to write a program in java that asks users for the base and height of a triangle. Then the program is supposed to find the area. I started the program asking the user if they are willing to help me. If they say "Yes" then the program continues. If they say anything other than "Yes" I want the program to stop. I don't know how to get it to reply to the user, then stop running. My code is below. If you have time to review the full thing that would be awesome! I'm brand new at this.
public static void main(String[] args) {
System.out.println("Hey can you help me practice finding the area of a triangle?");
String answerFirstQuestion = "Yes";
//if (answerFirstQuestion = Yes){
//}else{
// System.exit(0);
//}
//^^This part isn't apart of the prompt. I wanted to ask the user a question, then have them answer "Yes". If they entered anything other than that, I wanted the program to print "Oh ok, that's fine. Thanks anyways." then stop. Could I get some feedback on how to accomplish this.
switch (answerFirstQuestion) {
case "Yes":
System.out.println("Thanks kid!\nJust give me a random base and height for our imaginary triangle.\nI'll then use the equation b*h/2 to see if my program can find the area.");
break;
default:
System.out.println("Oh ok, that's fine.\nThanks anyways.");
}
int base;
base = 6;
int height;
height = 12;
int area = base*height/2;
area = base*height/2;
System.out.println("The base of the triangle is? " + base);
System.out.println("The height of the triangle is? " + height);
System.out.println("Area of Triangle is: " + area);
System.out.println("Cool I guess it works, thanks again!");
}
}
The java.lang.System.exit() method exits the current program by terminating running Java virtual machine.
The following example shows the usage of java.lang.System.exit() method.
// A Java program to demonstrate working of exit()
import java.util.*;
import java.lang.*;
class GfG
{
public static void main(String[] args)
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
for (int i = 0; i < arr.length; i++)
{
if (arr[i] >= 5)
{
System.out.println("exit...");
// Terminate JVM
System.exit(0);
}
else
System.out.println("arr["+i+"] = " +
arr[i]);
}
System.out.println("End of Program");
}
}
I hope that this helps you :).
Just return.
System.out.println("Hey can you help me practice finding the area of a triangle?");
String answerFirstQuestion = "Yes";
switch (answerFirstQuestion) {
case "Yes":
System.out.println("Thanks kid!\nJust give me a random base and height for our imaginary triangle.\nI'll then use the equation b*h/2 to see if my program can find the area.");
break;
default:
System.out.println("Oh ok, that's fine.\nThanks anyways.");
return;
// Return from the main function. The code below this will NOT be executed
}
https://cse.sc.edu/~shephejj/csce146/Homework/Homework01.html
import java.util.*;
public class MineSweep {
enum Spaces{Empty,Player,Cone,Mine}
public static final int Board_Size=10;
public final static double Percent_Mine = 0.1;
public static void main(String[]arg){
Spaces[][] Board= new Spaces[Board_Size][Board_Size];//Creates new multidimensional array.
int numOfMoves=0;
int positionX=0;
int positionY=0;
boolean isOver=false;
boolean isDead = false;
Random r= new Random();
//Random Places the cone on the GameBoard.
int coneX=r.nextInt(Board_Size);
int coneY=r.nextInt(Board_Size);
Scanner Scan = new Scanner(System.in);
Scanner scan2 = new Scanner(System.in);
for(int i=0;i<Board.length;i++){
for(int j =0; j<Board[1].length;j++){
Board[i][j]=Spaces.Empty;
}
}
Board[positionX][positionY]= Spaces.Player;
Board[coneX][coneY]=Spaces.Cone;
System.out.println("Welcoem to Mine Walker. Get the ice cream cone and avoid the Mines.");
int mines = (int)(Board_Size*Board_Size*Percent_Mine);
do
{
int x = r.nextInt(Board_Size-1)+1;
int y =r.nextInt(Board_Size-1)+1;
//Places mines in random spots
if (Board[x][y]== Spaces.Empty)
{
Board[x][y]=Spaces.Mine;
mines--;
}
}
while(mines>0);
if(isDead==true){
Board=generateBoard();
}else{
while(isOver==false)
{
for(int y=0;y<Board.length;y++)
{
for(int x=0;x<Board[y].length;x++)
{
switch(Board[x][y])
{
case Empty:
System.out.print("_");
break;
case Player:
System.out.print("X");
break;
case Mine:
System.out.print("!");
break;
case Cone:
System.out.print("^");
break;
default:
System.out.print("?");
break;
}
}
System.out.println(" ");
}
System.out.println("Enter either -1,0,1 to move in the X or 9 to quit");
int directionX = Scan.nextInt();
if(directionX==9)
{
System.out.println("Game Over");
System.exit(0);
}
System.out.println("Enter either -1,0,1 to move in th Y");
int directionY= Scan.nextInt();
if(directionX<-1 || directionX>1){
System.out.println("Invalid Input X");
directionX=0;
}
if(directionY <-1 || directionY>1)
{
System.out.println("Invalid input Y");
directionY = 0;
}
Board[positionX][positionY] = Spaces.Empty;
positionX+=directionX;
positionY+=directionY;
if(positionX < 0)
{
positionX = 0;
}
else if(positionX>Board_Size-1)
{
positionX = Board_Size-1;
}
if(positionY < 0)
{
positionY = 0;
}
else if(positionY> Board_Size-1)
{
positionY = Board_Size-1;
}
String retry;
if(Board[positionX][positionY]==Spaces.Mine)
{
isDead=true;
System.out.println("Boom! Dead!");
System.out.println("Would you like to play again? \"Yes\" or \"No\"");
retry = scan2.nextLine();
if (retry.equalsIgnoreCase("Yes"))
{
isOver = false;
generateBoard();
}
else if (retry.equalsIgnoreCase("No"))
{
System.out.println("Goodbye!");
System.exit(0);
}
}
if(Board[positionX][positionY]==Spaces.Cone)
{
System.out.println("You win!");
System.out.println("Would you like to play again? \"Yes\" or \"No\"");
}
Board[positionX][positionY] = Spaces.Player;
}
}
}
public static Spaces[][] generateBoard(){
int positionX=0;
int positionY=0;
Random r= new Random();
//Random Places the cone on the GameBoard.
int coneX=r.nextInt(Board_Size);
int coneY=r.nextInt(Board_Size);
Spaces[][] Board= new Spaces[Board_Size][Board_Size];
for(int i=0;i<Board.length;i++){
for(int j =0; j<Board[1].length;j++){
Board[i][j]=Spaces.Empty;
}
}
Board[positionX][positionY]= Spaces.Player;
Board[coneX][coneY]=Spaces.Cone;
System.out.println("Welcoem to Mine Walker. Get the ice cream cone and avoid the Mines.");
int mines = (int)(Board_Size*Board_Size*Percent_Mine);
do
{
int x = r.nextInt(Board_Size-1)+1;
int y =r.nextInt(Board_Size-1)+1;
//Places mines in random spots
if (Board[x][y]== Spaces.Empty)
{
Board[x][y]=Spaces.Mine;
mines--;
}
}
while(mines>0);
return Board;
}
}
In the code is above.Everything works, i'm just unable to create a new game board.I create a method called "generateboard()" and I call that method if "isDead= true" and user responds yes to if they want to retry.Please Help !
First of, you should really try to clean up your code a bit. It has some duplication and it is kinda hard to read. That said, I think your problem lies with this piece of code:
if (retry.equalsIgnoreCase("Yes"))
{
isOver = false;
generateBoard();
}
You are generating a new board, but you are not telling your program to use it. Change generateBoard() to Board = generateBoard();. Also you forget to reset your players position to 0,0.
Now I would like to give you some pointers on how you could clean up your program. The first part of your main method is basically a copy paste of your generate board method, this means that you could instead reuse that method to initialize the board.
After generating your board, the first if statement if (isDead == true) will never be true, because you just set isDead = false. Just do away with this if statement. This actually makes your isDead variable unused, because you don't use it otherwise.
You probably want to either return the starting position of the player from the generateBoard method, or take the starting position as arguments to the method in order to know where the position of the player is. In your example your player always starts at 0,0, but one could imagine that you would want to change that some time.
A couple of things to note:
In Java, variables usually start with a lower case letter (use "board" instead of "Board").
Enums in Java are usually all UPPER CASE (EMPTY instead of Empty etc.).
You don't need to use == false or ==true on boolean values, you could simply write: if (isDead).
You could also do with dividing your code into methods, but I'll leave that as an exercise for you. Also, you don't actually do anything when a player wins in the game.
I have created a single-class Java game in which we need to buy and sell stocks, I have just started Java and am a newbie so need help + this code is not very good.
import java.io.*;
import java.util.Random;
public class stock_holding_game
{
static Random randomn = new Random();
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args)throws IOException
{
double cash = 30.0;
double stocks[] = {0,10,20,40,80,160,320,640};//cost of stocks (there are 7 stocks each with different price)
int mystocks[] = {0,0,0,0,0,0,0,0};
pass("Enter your name");
String name = br.readLine();
pass("Hi "+name);
commandlist();
boolean booleancheck = true;
while(booleancheck)
{
pass("Please enter your command");
String command = br.readLine();
command =" "+command+" ";
char c = command.charAt(2);
switch(c)
{
case'h':
pass("enter the stock ID number");
int s1 = Integer.parseInt(br.readLine());
if(s1>0&&s1<=8)
{
pass("Starting price: "+stocks[s1]);
double t = randomn.nextDouble() *(stocks[s1]/10.0);
int add = randomn.nextInt(2);
if(add==0)stocks[s1]=stocks[s1]+t;
else
stocks[s1]=stocks[s1]-t;
pass("Current price: "+stocks[s1]);
}
else
{
pass("Wrong Number");
pass("Enter a number from 1 to 8");
pass("Do whole task again xD");
}
break;
case 'n':
pass("Enter the stock ID number");
int s2 = Integer.parseInt(br.readLine());
if(s2>0&&s2<=8)
{
double t = randomn.nextDouble() *(stocks[s2]/10.0);
int add = randomn.nextInt(2);
if(add==0)stocks[s2]=stocks[s2]+t;
else
stocks[s2]=stocks[s2]-t;
pass("Current price: "+stocks[s2]);
pass("You currently have: "+mystocks[s2]+ " of these stocks");
pass("You have " +cash+" cash");
pass("Enter the number of stocks you wish to buy");
int nsbuy = Integer.parseInt(br.readLine());
if(nsbuy<0)pass("Idiot ! , add atleast 1 if you wish to buy");
else if(nsbuy==0);
else
{
double checkprice = nsbuy*stocks[s2];
if(checkprice > cash)
{
pass("You don't have enough cash in hand !");
}
else
{
cash = cash - checkprice;
mystocks[s2] = mystocks[s2] + nsbuy;
pass("Now you have "+mystocks[s2]+ " of stock ID " +s2);
pass("You are left with "+cash);
}
}
}
else
{
pass("Invalid Input!");
pass("Enter a number from 1 to 8");
}
break;
case 'a':
pass("You have currentln " +cash+" cash");
break;
case 'x':
booleancheck = false ;
pass("You leave with "+cash+" cash");
pass("Bye, Hope to see you again .");
break;
case 'o':
commandlist();
break;
case 'y':
for(int xyz = 1; xyz<mystocks.length - 1;xyz++)
{
pass("You have "+mystocks[xyz]+ " of stock ID "+xyz);
}
break;
case 'e':
pass("Enter the stock ID number");
int s3 = Integer.parseInt(br.readLine());
if(s3>0&&s3<=8)
{
double t = randomn.nextDouble() *(stocks[s3]/10.0);
int add = randomn.nextInt(2);
if(add==0)stocks[s3]=stocks[s3]+t;
else
stocks[s3]=stocks[s3]-t;
pass("Current price: "+stocks[s3]);
pass("You currently have: "+mystocks[s3]+ " of these stocks");
pass("You have " +cash+" cash");
pass("Enter the number of stocks you wish to sell");
int nssell = Integer.parseInt(br.readLine());
if(nssell<0)pass("Enter atleast 1 if you wish to sell(in case you have)");
else if(nssell==0);
else
{
double nscheckprice = stocks[s3]*nssell;
if(nssell>mystocks[s3])pass("You don't jave that many stocks !");
else
mystocks[s3] = mystocks[s3] - nssell;
cash = cash + nscheckprice;
pass("You have successfully sold your " +nssell+" stocks for "+nscheckprice);
pass("Now , you have , "+ mystocks[s3]+ " of stock ID "+s3);
pass("You are left with " +cash + " cash");
}
}
else
{
pass("Invalid Input!");
pass("Enter a number from 1 to 8");
}
break;
default:
pass("Invalid Input!");
break;
}
}
}
private static void commandlist()
{
pas("Your command list : ");
pas("checkstock - check the current and earlier value of a stock");
pas("invest - buy shares ");
pas("sell - sell ur share ");
pas("exit - leave the game");
pas("my - show ur all current stock");
pas("cash - show ur current cash in hand");
pas("There are 7 stock with id 1 , 2 , 3 , and so on till 7")
pas("Remember ! It is case sensitive");
}
private static void pass(String source)
{
System.out.println(source);
}
private static void pas(String source)
{
System.err.println(source);
}
}
I wish to have an applet for this code but I don't know much about applets. I wish to use some buttons instead of typing. I know codes to add buttons but don't know how to use them. Need help on it, all replies would be appreciated.
And yes , also tell how is this game (rate this game), but rate as if a newbie as made it.
Now, instead of going on full ask on how to convert it into an applet I wish to ask it in small blocks. First of all how shall I use a button and tell my PC how to proceed?
This is my code:
import java.awt.*;
public class Buttonsuse extends java.applet.Applet
{
Button invest , sell , check ;
public void init()
{
setBackground (Color.white);
setLayout(new FlowLayout (FlowLayout.CENTER,10,10));
invest = new Button("Invest");
sell = new Button("Sell");
check = new Button("Check");
add(invest);
add(sell);
add(check);
}
}
Now, how shall I know and tell the computer that a button is pressed, like if user presses invest button, it prints "you wish to invest".
How shall I do that?
Your current program is little more than a large static main method with a few small supporting static methods. Since this code is very linear, as most console programs are, and since it has no OOP-compliant classes, there is no way to directly convert or re-use any of this code to use in an event-driven GUI. I suggest:
Extract out the logic or brains behind your program into true OOP classes with instance fields, constructors and non-static methods.
Only after doing this should you consider creating a GUI to display the logic.
Read a decent book on OOP and Java such as "Thinking in Java" as this will help you think and code in an OOP way.
Non-GUI Classes to consider:
Stock classes with String name, double (or BigDecimal) value, String abbreviated name
Player that holds a String for name, a HashMap<Stock, Integer> for Stocks held and number of shares.
Market where a player can buy and sell Stocks.
The bottom line is that there is no one single simple way to "convert" this code to a GUI, and instead you should focus on learning Java fundamentals, and experiment with your code while learning (for that's how you learn).
My assignment is to try and create a card game and I'm stuck at the point where I am trying to display the cards in a jframe. I have a Displayable instance and a Displayble hand deck and card which implements this. I'm stuck at what to put inside the display method that they have to override and also what I should put in the jframe class/jpanel. Any help is much appreciated thanks a lot.
public interface Displayable {
public void display(Graphics g, int x, int y);
}
Example of one of the displayable classes.
public class DisplayableCard extends Card implements Displayable {
Graphics g;
String filename = "\\images\\classic-cards\\7.png";
Image image = new ImageIcon(getClass().getResource(filename)).getImage();
#Override
public void display(Graphics G, int x,int y)
{
}
}
We got given this code to use and told to- "Test your new classes by creating a simple subclass of JFrame, which contains an instance of CardGamePanel. Simply construct and add an appropriate Displayable object to the CardGamePanel instance to test each Displayable"
public class CardGamePanel extends JPanel{
private Displayable theItem;
private int x, y;
#Override
public void paint(Graphics g) {
if (theItem != null)
{
theItem.display(g, x, y);
}
}
public void setItem(Displayable item, int x, int y) {
theItem = item;
this.x = x;
this.y = x;
}
}
So I tried this:
public class simple extends JFrame
{
CardGamePanel c = new CardGamePanel();
Displayable d;
DisplayableDeck d1 = new DisplayableDeck();
}
public class mainclass {
public static void main(String args[])
{
DisplayableDeck d1 = new DisplayableDeck();
simple s1 = new simple();
s1.c.setItem(d1, 50, 50); // like this?
}
}
Any help much appreciated :)
You can try this program
public class HighLow {
public static void main(String[] args) {
System.out.println("This program lets you play the simple card game,");
System.out.println("HighLow. A card is dealt from a deck of cards.");
System.out.println("You have to predict whether the next card will be");
System.out.println("higher or lower. Your score in the game is the");
System.out.println("number of correct predictions you make before");
System.out.println("you guess wrong.");
System.out.println();
int gamesPlayed = 0; // Number of games user has played.
int sumOfScores = 0; // The sum of all the scores from
// all the games played.
double averageScore; // Average score, computed by dividing
// sumOfScores by gamesPlayed.
boolean playAgain; // Record user's response when user is
// asked whether he wants to play
// another game.
do {
int scoreThisGame; // Score for one game.
scoreThisGame = play(); // Play the game and get the score.
sumOfScores += scoreThisGame;
gamesPlayed++;
TextIO.put("Play again? ");
playAgain = TextIO.getlnBoolean();
} while (playAgain);
averageScore = ((double)sumOfScores) / gamesPlayed;
System.out.println();
System.out.println("You played " + gamesPlayed + " games.");
System.out.printf("Your average score was %1.3f.\n", averageScore);
} // end main()
/**
* Lets the user play one game of HighLow, and returns the
* user's score on that game. The score is the number of
* correct guesses that the user makes.
*/
private static int play() {
Deck deck = new Deck(); // Get a new deck of cards, and
// store a reference to it in
// the variable, deck.
Card currentCard; // The current card, which the user sees.
Card nextCard; // The next card in the deck. The user tries
// to predict whether this is higher or lower
// than the current card.
int correctGuesses ; // The number of correct predictions the
// user has made. At the end of the game,
// this will be the user's score.
char guess; // The user's guess. 'H' if the user predicts that
// the next card will be higher, 'L' if the user
// predicts that it will be lower.
deck.shuffle(); // Shuffle the deck into a random order before
// starting the game.
correctGuesses = 0;
currentCard = deck.dealCard();
TextIO.putln("The first card is the " + currentCard);
while (true) { // Loop ends when user's prediction is wrong.
/* Get the user's prediction, 'H' or 'L' (or 'h' or 'l'). */
TextIO.put("Will the next card be higher (H) or lower (L)? ");
do {
guess = TextIO.getlnChar();
guess = Character.toUpperCase(guess);
if (guess != 'H' && guess != 'L')
TextIO.put("Please respond with H or L: ");
} while (guess != 'H' && guess != 'L');
/* Get the next card and show it to the user. */
nextCard = deck.dealCard();
TextIO.putln("The next card is " + nextCard);
/* Check the user's prediction. */
if (nextCard.getValue() == currentCard.getValue()) {
TextIO.putln("The value is the same as the previous card.");
TextIO.putln("You lose on ties. Sorry!");
break; // End the game.
}
else if (nextCard.getValue() > currentCard.getValue()) {
if (guess == 'H') {
TextIO.putln("Your prediction was correct.");
correctGuesses++;
}
else {
TextIO.putln("Your prediction was incorrect.");
break; // End the game.
}
}
else { // nextCard is lower
if (guess == 'L') {
TextIO.putln("Your prediction was correct.");
correctGuesses++;
}
else {
TextIO.putln("Your prediction was incorrect.");
break; // End the game.
}
}
/* To set up for the next iteration of the loop, the nextCard
becomes the currentCard, since the currentCard has to be
the card that the user sees, and the nextCard will be
set to the next card in the deck after the user makes
his prediction. */
currentCard = nextCard;
TextIO.putln();
TextIO.putln("The card is " + currentCard);
} // end of while loop
TextIO.putln();
TextIO.putln("The game is over.");
TextIO.putln("You made " + correctGuesses
+ " correct predictions.");
TextIO.putln();
return correctGuesses;
} // end play()
} // end class
You can try out the game in this applet, which simulates the program:
I'm writing a program that is supposed to return the value of rolling two dice. I want the user to be able to select a specified type of die or chose a custom number of sides. So, for example, I chose the triangle die, I would have a 3 sided die.
The variable:
private int die = 1;
private int preselectedSides;
The case in a switch I've made to handle the menu looks like this:
switch(selection)
case 1:
premadeDice(3, 4, 6);
x=1;
break;
The receiving method looks like this:
//premade Dice Selection//
public int premadeDice(int triangle, int rectangle, int cube)
{
String choice;
boolean flag = false;
while (flag == false)
{
System.out.println("Enter in the shape you want your die to be");
System.out.println("A triangle die has 3 sides. If this is what you want, type \"triangle\"");
System.out.println("A rectangle die has 4 sides. If this is what you want, type \"rectangle\"");
System.out.println("A cube die has 6 sides. If this is what you want, type \"cube\"");
choice = sc.next();
if (choice.equalsIgnoreCase("triangle"))
{
System.out.println("You have chosen the triangle die.");
preselectedSides = triangle;
flag = true;
}
else if (choice.equalsIgnoreCase("rectangle"))
{
System.out.println("You have chosen the rectangle die.");
preselectedSides = rectangle;
flag = true;
}
else if (choice.equalsIgnoreCase("cube"))
{
System.out.println("You have chosen the traditonal cube die.");
preselectedSides = cube;
flag = true;
}
else
{
System.out.println("You have not entered in a valid die shape. Try again");
}
}//end while loop
return preselectedSides;
}//end pre-made dice method
I created a getter to get access to that returned value:
//getter for Die
public void getDie()
{
System.out.println(preselectedSides);
}
Call it like this:
test.getDie();
And I get the following output for a cube (or for the other shapes, I keep getting 1 along with the value)
1
6
I've tried finding this logic error but I don't see it. Why does it keep outputting the number one? Ask for clarification if needed.
This seems like an awful lot of code. You can simplify it like so:
public class Die
{
int sides;
//get/set/constructor
...
}
public class DieRoller
{
Die die;
public int roll()
{
Random generator = new Random();
return generator.nextInt(this.die.getSides());
}
}
You can run it like so:
public static void main(String[] args)
{
System.out.println("Number of sides?");
Scanner sc = new Scanner(System.in);
Die currentDie = new Die(sc.nextInt());
System.out.println("Rolling");
DieRoller roller = new DieRoller(currentDie);
int sideRolled = roller.roll();
System.out.println(String.format("You rolled %d on your %d sided die",sideRolled,currentDie.getSides()));
}