I'm really new to java, and just programming in general. I am trying to make a simple "story game".
I want the program to start again where I commented "starting again point if walk.equals("b") (second time)"
Here is my code:
P.S. sorry if it is poorly written
import java.util.*;
public class leikur1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("|---------Welcome to the adventure------------|");
System.out.println("Please enter Name"); // inputs name
String nafn = scan.nextLine();
nafn = nafn.toLowerCase();
System.out.println("Gender, male or female");
String kyn = scan.nextLine();
kyn = kyn.toLowerCase();
while((!kyn.equals("male")) && (!kyn.equals("female")) ) //bara haegt ad velja male eda female
{
System.out.println("That is not valid input" );
kyn = scan.nextLine();
kyn = kyn.toLowerCase();
}
System.out.println("Are you ready for the adventure");
String leikur = scan.nextLine();
leikur = leikur.toLowerCase();
while((!leikur.equals("yes")) && (!leikur.equals("no")) ) //impossible to input something else than male or female
{
System.out.println("That is not valid input" );
leikur = scan.nextLine();
leikur = leikur.toLowerCase();
}
if(leikur.equals("no"))
{
System.out.println("Thank you anyway"); //if input = no program ends
}
// if input = yes the game begins
else
{
System.out.println("Write Start to begin or Quit to exit");
String start = scan.nextLine();
start = start.toLowerCase();
String gender;
if(kyn.equals("male"))
{
gender = "he";
}
else
{
gender = "she";
}
while((!start.equals("start")) && (!start.equals("quit")) )
{
System.out.println("That is not valid input" );
start = scan.nextLine();
start = start.toLowerCase();
}
if(start.equals("start"))
{
System.out.println("Walking instructions: left - l right - r forward - f back - b down - d up - u\n");
System.out.println(nafn + " is in a abandoned house late at night, stuck in the basement with no light.\n");
System.out.println("In wich way should " + gender + " go to find his way to the stairs?" ); **// starting again point if walk.equals("b") (second time)**
String walk = scan.nextLine();
walk = walk.toLowerCase();
//////////
while((!walk.equals("f")) && (!walk.equals("b")) ) // not possible bcus of walls or no stairs
{
System.out.println("That is not possible" );
walk = scan.nextLine();
}
if(walk.equals("f"))
{
System.out.println("Great choice, " + gender + " found the stairs right away. Should"+gender+" go upstairs or go back?" );
}
else if (walk.equals("b"))
{
System.out.println("Oh boy! " + nafn +" got stuck in a beartrap and died... GAME OVER" );
}
/////////
walk = scan.nextLine();
while(!walk.equals("u") && !walk.equals("b") )
{
System.out.println("That is not possible" );
walk = scan.nextLine();
}
if(walk.equals("u"))
{
System.out.println("Excelent!" + nafn + " is now upstairs" );
}
**else if(walk.equals("b") )
{
System.out.println("Now " + nafn + " is at stage 1 again" );
}**
//////////////
// code 4 the game should be here above
}
else if(start.equals("quit"))
{
System.out.println("Thank you anyway");
}
}
}
}
If you just want to repeat your content, a while loop is sufficient
boolean continue = true;
while(continue)
{
else if(walk.equals("b") )
{
System.out.println("Now " + nafn + " is at stage 1 again" );
continue = true;
}
else if(start.equals("quit"))
{
System.out.println("Thank you anyway");
continue = false;
}
}
the reason I'm using the variable continue is to better illustrate the while loop. you can also use while(true), which will normally loop forever. to skip to the beginning of the next iteration you use continue; and to break out, you can use break
while(true)
{
else if(walk.equals("b") )
{
System.out.println("Now " + nafn + " is at stage 1 again" );
continue;
}
else if(start.equals("quit"))
{
System.out.println("Thank you anyway");
break;
}
}
If you really wanted to take your coding to the next level, you could take a more data-driven approach, and have a data model to define your game. The following is a sample data model in xml
<Places>
<Place name="YourRoom" text="You are in your room. Where would you like to go?">
<Option text="Enter the hallway." result="Hallway"></Option>
</Place>
<Place name="Hallway" text="You are in the hallway. Where would you like to go?">
<Option text="Go to your room" result="YourRoom"></Option>
</Place>
</Places>
And then you'd write your program something like this
pseudocode:
xmlElement currentRoom = // get starting element
while(true)
{
print(currentRoom.Attributes[text])
for(int i=0; i<currentRoom.Elements.length; i++)
{
print(currentRoom.Elements[i] + "type " + i+1;
}
int choice = getInt();
int result = currentRoom.Elements[choice].result;
currentRoom GetElementWithName(result);
}
You should rather learn Java, OOP and other base constructs. If you really insist, you can use labels (to be honest since the advent of structured programming, in the sixties people try not to use GOTO anymore... but if you want to fail a job interview go ahead ;-) )
// ...
// label is your label, you can use any text
label:{
// ...
// here is your GOTO
break label;
}
Side note : it works like a charm, but please don't do it (or at least don't say I'm the one who told you about labels) !
Related
I don't receive any errors when compiling, however the output isn't correct?
The program stops when the user should able to input.
import java.util.Scanner;
class person
{
private String name, choice1, choice2, choice3;
//Getters
public String getName()
{
return this.name;
}
public String getChoice1()
{
return this.choice1;
}
public String getChoice2()
{
return this.choice2;
}
public String getChoice3()
{
return this.choice3;
}
//Setters
public void setName( String n )
{
this.name = n;
}
public void setChoice1( String c1 )
{
this.choice1 = c1;
}
public void setChoice2( String c2 )
{
this.choice2 = c2;
}
public void setChoice3( String c3 )
{
this.choice3 = c3;
}
}
public class AdventureGame
{
public static void main(String[] Args) throws Exception
{
String end = "Game Over";
Scanner keyboard = new Scanner(System.in);
person p = new person();
//intro
System.out.println( "Welcome travellar, your adventure awaits you..." );
Thread.sleep(1000);
System.out.print( "Player Name: " );
String inputName = keyboard.next();
p.setName(inputName);
Thread.sleep(1000);
//Question 1
System.out.println( "You are in a creepy house! Would you like to go \"upstairs\" or into the \"kitchen\"?" );
String inputChoice1 = keyboard.nextLine();
p.setChoice1(inputChoice1);
if ( p.getChoice1().equals("kitchen") )
{ //Q2
System.out.println("There is a long countertop with dirty dishes everywhere. Off to one side there is, as you'd expect, a refrigerator. You may open the \"refridgerator\" or look in a \"cabinet\" ");
String inputChoice2 = keyboard.nextLine();
p.setChoice2(inputChoice2);
if ( p.getChoice2().equals("refridgerator") )
{
System.out.println("Inside the refridgerator you see some food. Would you like to eat that food? (\"yes\" or \"no\")");
String inputChoice3 = keyboard.nextLine();
p.setChoice3(inputChoice3);
if ( p.getChoice3().equals("yes") )
{
System.out.println(p.getName() + " died of food poisoning.");
Thread.sleep(1000);
System.out.print(end);
}
else if ( p.getChoice3().equals("no") )
{
System.out.print("You will never know what that food tasted like. The regret haunts you till suicide.");
Thread.sleep(1000);
System.out.print(end);
}
}
else if ( p.getChoice2().equals("cabinet") )
{
System.out.println( "The cabinet was a trap! You took a barbed contraption to the face; you are blinded and bleeding out." );
Thread.sleep(1000);
System.out.println("As you lie on the floor blind and bleeding out, you hear footsteps. Do you \"move\" or try to \"hide\"?");
String inputChoice3 = keyboard.nextLine();
p.setChoice3(inputChoice3);
if ( p.getChoice3().equals("move") )
{
System.out.print("As you moved faster so did the footsteps. you took a final blow.");
Thread.sleep(1000);
System.out.print(end);
}
else if ( p.getChoice3().equals("hide") )
{
System.out.println("blinded, you failed to realise that you were in plain sight. You became an easy meal.");
Thread.sleep(1000);
System.out.print(end);
}
}
}
else if ( p.getChoice1().equals("upstairs") )
{
System.out.println("As you reach the top of the stairs, your encounter 3 doors; which door do you enter? (\"1\" or \"2\")");
String inputChoice2 = keyboard.nextLine();
p.setChoice2(inputChoice2);
if ( p.getChoice2().equals("1") )
{
System.out.println("As you grab the handle of the first of the door you hear a scream!");
Thread.sleep(1000);
System.out.println("do you \"run\" or \"open\" the door?!");
String inputChoice3 = keyboard.nextLine();
p.setChoice3(inputChoice3);
if( p.getChoice3().equals("run") )
{
System.out.println("Running down the stairs, you misplaced a foot and fell to your demise.");
Thread.sleep(1000);
System.out.print(end);
}
else if (p.getChoice3().equals("open"))
{
System.out.println("As your head poked through, an unrelenting force slammed the door, decapitating your head.");
Thread.sleep(1000);
System.out.print(end);
}
}
else if ( p.getChoice2().equals("2") )
{
System.out.println("You enter what seems to be a vacant bedroom. Do you take a nap? (\"yes\" or \"no\")");
String inputChoice3 = keyboard.nextLine();
p.setChoice3(inputChoice3);
if ( p.getChoice3().equals("yes") )
{
System.out.println("You never wake up...");
System.out.print(end);
}
else if ( p.getChoice3().equals("no") )
{
System.out.println("You turn around turn around to leave bu the door is gone?!");
Thread.sleep(1000);
System.out.println( "The grim reaper appears... Your time has come." );
Thread.sleep(1000);
System.out.print(end);
}
}
}
}
}
There might be some confusion about the use of next() and nextLine().
For next(), you are scanning the input until the next space and you place the cursor at the position in which the scanning stopped
For nextLine(), you are scanning the input until the end of the line and you place the cursor on a new line.
Disclaimer: Before you continue reading on and look at the proposed the solution, you can try and figure out what's wrong with your code by using the above information and see if you can solve it yourself! :)
So the slight bug happens at this line: String inputName = keyboard.next();
For instance, if I were to type apogee in your application and then press enter, then inputName would be set to apogee. It seems great until now, but, the enter key was also considered as an input.
Now, when we arrive at String inputChoice1 = keyboard.nextLine();, the enter key would be considered as an input and your inputChoice1 is now an empty string. Since you have no conditions which matches an empty string, you will exit the application.
There are two ways to solve this issue:
Add keyboard.nextLine() right after String inputName = keyboard.next(); to handle the input triggered by the enter key ("\n")
Use keyboard.nextLine() instead of next()
Happy Coding!
I am new to java so forgive me if I am making a very simple mistake. I am attempting to make shop within a text based adventure game. I have created an array shopItems which stores a list of items as strings that the shop can sell. Here is a part of the method I use for the user to make purchases within the game.
String request = s.nextLine().toLowerCase();
for (int i = 0 ; i < shopItems.length ; i++)
{
if(request.equalsIgnoreCase(shopItems[i]))
{
System.out.println("We have this item in stock! That will be " + itemPrice[i] + " gold, "
+ "would you like to purchase this item?");
String command2 = s.nextLine().toLowerCase();
if(command2.equals("yes") || command2.equals("y"))
{
if (savings >= itemPrice[i])
{
System.out.println("Congratulations! You have purchased " + shopItems[i] + ". Thank you "
+ "for your business.");
savings = savings - itemPrice[i];
inv.add(shopItems[i]);
magicShopPurchase();
}
else if (savings < itemPrice[i])
{
System.out.println("I'm sorry, you don't have enough gold to purchase this item! Try "
+ "again when you have enough!");
}
}
}
else if(request.equals("leave"))
{
System.out.println("Thank you! Please come again soon!");
inMagicShop();
}
else
{
System.out.println("I'm sorry, we don't have any of those in stock at the moment. Would you "
+ "like to purchase a different item?");
String command2 = s.nextLine().toLowerCase();
if(command2.equals("yes") || command2.equals("y"))
{
magicShopPurchase();
}
else if(command2.equals("no") || command2.equals("n"))
{
System.out.println("Thank you! Please come again soon!");
inMagicShop();
}
else
{
System.out.println("Haha, you kiss your mother with that mouth? Come back some other time!");
inMagicShop();
}
}
}
I am trying to compare the scanner input with shopItems to check if the item that the user wants to purchase is available in the shop, however it does not recognize any of the elements in shopItems. Am I doing something wrong with this method/is there a mistake somewhere? This is my first post here so please forgive me if I have left out anything important.
EDIT
First is where I call the method to store elements into shopItems.
try {
itemList = new String(Files.readAllBytes(Paths.get("C:\\Users\\gravy_000\\Desktop\\Software Development 1\\GameProject\\src\\hallSim\\magicitems.txt")));
read(itemList);
} catch (IOException e) {
e.printStackTrace();
}
Second is the method I used to read the text file and store it into shopItems.
public static void read(String shopList) {
shopItems = shopList.split("\\r?\\n");
}
Here is a link to the text file in Dropbox
https://www.dropbox.com/s/rbfsr1fj2yzus1q/magicitems.txt?dl=0
The problem is that you are telling the user that the item is not found, the first time request.equalsIgnoreCase(shopItems[i]) returns false, NOT when request is not present.
So you should replace the code by something like this or equivalent:
String request = s.nextLine().toLowerCase();
if(request.equals("leave")) {
//leave
} else {
boolean isItemInStock = false;
for (int i = 0 ; i < shopItems.length ; i++) {
if(request.equalsIgnoreCase(shopItems[i])) {
isItemInStock = true;
break;
}
}
if(isItemInStock) {
System.out.println("We have this item in stock! That will be " + itemPrice[i] + " gold, "
+ "would you like to purchase this item?");
//...
} else {
System.out.println("I'm sorry, we don't have any of those in stock at the moment. Would you "
+ "like to purchase a different item?");
//...
}
}
Note how the if/else statement that handles what to with request is outside the main loop.
I heard that one can turn the if/else statements into loops, they are somewhat equivalent. Could someone give me an example, because I am having a hard time understanding the conversion process.
Ok from the comments I guess I didn't ask the question correctly. I am basically working on an assignment and have to use someone's code which was written in all if/else statements and convert it into a code that includes loops.
I am not asking for the answer to this problem but I am asking for an example on how one would do this. I've pretty much though of a way of doing it, with the code below. It's basically a Haunted House maze type of "game" that ends whenever you touch and explore an object after going through rooms, but there is no backtracking. With loops I have to allow backtracking, and allow the user to explore as many items as possible, and only end the game when the user decides to end it.
EDIT:
Okay, I've started to convert the Living Room section path of the code above into a while loop. Please tell me if it looks good, if I could improve it somehow, or if I made any mistakes, it seems to run fine. The only problem I have is that when I click decide to go use the chest, it asks twice and then ends, it should only ask once, the same with the Candelabra. Maybe I am missing something about the "break" statement? But I don't know because when I am in the pantry, and then go back, and I have the if else contain just break; it does what it is supposed to do... but not with the chest and the candelabra.
But here is my code so far:
public class LoopyHauntedHouse {
private String name; //Player name.
private String location0; //First location selected from door.
private String toFrontDoor = "";
private String atFrontDoor;
//Method asking for user's name, and welcoming the user as well as asking where they'd like to go for the first time.
public void intro()throws MalformedURLException
{
//URL to image initialized from the original code as needed.
URL frontDoor = new URL("http://i.imgur.com/2m3giQk.png");
//Scanner for user input.
Scanner scnr = new Scanner(System.in);
//Asking for user's name and welcoming the user.
name = JOptionPane.showInputDialog(null, "What is your name?");
JOptionPane.showMessageDialog(null, "Welcome " + name + " to the Haunted House!");
//Shows starting location.
JOptionPane.showMessageDialog(null, name + " you're at the front door of the haunted house.", "Title",
JOptionPane.PLAIN_MESSAGE, new ImageIcon(frontDoor));
//Asks for first choice of room to start at.
location0 = JOptionPane.showInputDialog(null, name + " where to next? 'Living Room', 'Dining Room' or 'Stairs'?");
}
//Method for the rest of the program allowing users to walk through the house, backtrack, and interact with objects.
public void startWalking()throws MalformedURLException
{
//URLs to images are initialized from the original code as needed.
URL stairs = new URL("http://i.imgur.com/WuddJUc.png");
URL bedroom1 = new URL("http://i.imgur.com/HZ6OSyZ.png");
URL bedroom2 = new URL("http://i.imgur.com/JZORNpd.png");
URL bathroom = new URL("http://i.imgur.com/onSEc1J.png");
URL masterBedroom = new URL("http://i.imgur.com/bf4L0sH.png");
URL masterBathroom = new URL("http://i.imgur.com/yp87dTX.png");
URL livingRoom = new URL("http://i.imgur.com/7XQD5Pt.png");
URL bathRoom = new URL("http://i.imgur.com/G0CxjSy.png");
URL diningRoom = new URL("http://i.imgur.com/gyU9mep.png");
URL kitchen = new URL("http://i.imgur.com/tTMRCID.png");
URL pantry = new URL("http://i.imgur.com/zBxPJCs.png");
while(location0.equalsIgnoreCase("Living Room")||(toFrontDoor.equalsIgnoreCase("Living Room")))
{
JOptionPane.showMessageDialog(null, name + " you are now in the Living Room");
String move1 = JOptionPane.showInputDialog(null, name + " would you like to explore the 'Chest' walk to the 'Bathroom' or 'Go back' and go to another room?");
if(move1.equalsIgnoreCase("Chest"))
{
JOptionPane.showMessageDialog(null, name + " a ghost escapes and scares you to death!");
JOptionPane.showMessageDialog(null, "Game Over! You've died.", "Try Again.",
JOptionPane.WARNING_MESSAGE, new ImageIcon(livingRoom));
break;
}
else if(move1.equalsIgnoreCase("Bathroom"))
{
while(move1.equalsIgnoreCase("Bathroom"))
{
JOptionPane.showMessageDialog(null, name + " you are now in the bathroom.");
String move2 = JOptionPane.showInputDialog(null, name + " would you like to explore the 'Mirror', 'Shower', or 'Go back'?");
if(move2.equalsIgnoreCase("Shower"))
{
JOptionPane.showMessageDialog(null, name + " the room suddenly steams up and you feel fingers touching the back of your neck...");
}
else if(move2.equalsIgnoreCase("Mirror"))
{
JOptionPane.showMessageDialog(null, name + "you see a bloody face looking back at you!");
}
else if(move2.equalsIgnoreCase("Go back"))
{
JOptionPane.showMessageDialog(null, name + " you are now in the Living Room");
break;
}
else
{
JOptionPane.showMessageDialog(null, "Please enter a valid option.");
}
}
}
else if(move1.equalsIgnoreCase("Go back"))
{
toFrontDoor = move1;
break;
}
else
{
JOptionPane.showMessageDialog(null, "Please enter a valid option.");
}
}
while(location0.equalsIgnoreCase("Dining Room"))
{
JOptionPane.showMessageDialog(null, name + " you are now in the Dining Room");
String move1 = JOptionPane.showInputDialog(null, name + " would you like to explore the 'Candelabra' or walk to the 'Kitchen'");
if(move1.equalsIgnoreCase("Candelabra"))
{
JOptionPane.showMessageDialog(null, "The candelabra light up by themselves and " + name + " sees a death shadow!");
JOptionPane.showMessageDialog(null, "Game Over! You've died.", "Try Again.",
JOptionPane.WARNING_MESSAGE, new ImageIcon(diningRoom));
break;
}
else if(move1.equalsIgnoreCase("Kitchen"))
{
while(move1.equalsIgnoreCase("Kitchen"))
{
JOptionPane.showMessageDialog(null, name + " you are now in the 'Kitchen'.");
String move2 = JOptionPane.showInputDialog(null, name + " would you like to explore either the 'Refrigerator' or 'Cabinet' walk to the 'Pantry', or 'Go back'");
if(move2.equalsIgnoreCase("Refrigerator"))
{
JOptionPane.showMessageDialog(null, name + " opens the refrigerator and finds some delicious soul food.");
}
else if(move2.equalsIgnoreCase("Cabiner"))
{
JOptionPane.showMessageDialog(null, "The dished and glasses start flying at you as soon as you open the door. " + name + " gets hit in the head and feels themselves moving towards a light.");
JOptionPane.showMessageDialog(null, "Game Over! You've died.", "Try Again.",
JOptionPane.WARNING_MESSAGE, new ImageIcon(kitchen));
break;
}
else if(move2.equalsIgnoreCase("Pantry"))
{
while(move2.equalsIgnoreCase("Pantry"))
{
JOptionPane.showMessageDialog(null, name + " you are now in the Pantry.");
String move3 = JOptionPane.showInputDialog(null, name + " would like to explore the 'Dusty Recipe Box', the 'Broom', or 'Go back'?");
if(move3.equalsIgnoreCase("Dusty Recipe Box"))
{
JOptionPane.showMessageDialog(null, name + "opens it up and a recipe for chocolate devils food cake appears out of no where.");
}
else if(move3.equalsIgnoreCase("Broom"))
{
JOptionPane.showMessageDialog(null, "As soon as " + name + " touches the broom, it flies up in the air!");
}
else if(move3.equalsIgnoreCase("Go back"))
{
break;
}
else
{
JOptionPane.showMessageDialog(null, "Please enter a valid option.");
}
}
}
else if(move2.equalsIgnoreCase("Go back"))
{
toFrontDoor = move2;
break;
}
else
{
JOptionPane.showMessageDialog(null, "Please enter a valid option.");
}
}
}
}
}
public void toFrontDoor() throws MalformedURLException
{
if(toFrontDoor.equalsIgnoreCase("Go back"))
{
atFrontDoor = JOptionPane.showInputDialog(null, name + " where to next? 'Living Room', 'Dining Room', 'Stairs', or 'Leave the house'?");
if(atFrontDoor.equalsIgnoreCase("Leave the house"))
{
JOptionPane.showMessageDialog(null, "Game Over! Thanks for playing.");
}
}
else
{
startWalking();
}
}
}
Test CLass:
public class LoopyTest {
public static void main(String[] args) throws MalformedURLException {
LoopyHauntedHouse player = new LoopyHauntedHouse();
player.intro();
player.startWalking();
player.toFrontDoor();
}
}
Yes, in assembly language, loops are implemented with condition statement and a goto statement:
L1: if ( <cond> )
{
<loop-body>
goto L1 ;
}
You can use this approach in C, but not in Java because goto is not permitted.
When program gets to L1, it checks the condition. If the condition is met, program will proceed with loop-body, after that it will jump (goto) to L1 which labels a line number in your program. There, a loop. It will break if the condition is not met and program will continue at next line after curly brace { .
You can make a loop that does the functional equivalent of an if statement if you're careful about how you design it.
If:
if(myVal == 1) {
//do something
}
Functionally equivalent for:
for(int i = myVal; i == 1; ++i) {
//Do something
}
Functionally equivalent while:
int i = myVal;
while(i == 1) {
//Do something
++i;
}
Notice, that in the loops I don't directly compare myVal against the loop terminator. This is because you have to change the comparison value in order to get out of the loop, and you may not want to change your actually variable.
However, if your entire desired code was running inside a while(isPlaying) {}, you don't need a bunch of other loops. You just add else if(move#.equalsIgnoreCase("quit") {isPlaying = false; } for all the places you check each move#.
I would also add, that your current code could benefit from using classes. There's really no reason to have a new move# variable for each command the user enters.
Since the different rooms are kind of the "state". you could probably solve it when using the state pattern. Each state is represented by one obect. Using those objects, each can decide what to do next based on it's state. For example:
class Room {
private String roomName;
private URL icon;
private List<String> nextRooms;
public Room(String _roomName, URL _icon, String... _nextRooms) {
roomName = _roomName;
icon = _icon;
nextRooms = new ArrayList<>();
for (String string : _nextRooms) {
nextRooms.add(string.toLowerCase());
}
}
public void showInfo(String player) {
JOptionPane.showMessageDialog(null, player + " you're in " + roomName, "Title",
JOptionPane.PLAIN_MESSAGE, new ImageIcon(icon));
}
public String nextRoomName(String player) {
StringBuilder sb = new StringBuilder();
for (String string : nextRooms) {
sb.append(string).append(", ");
}
String roomOptions = sb.toString();
while(true) {
String input = JOptionPane.showInputDialog(null, player + " where to next? Your options are: " + roomOptions);
if(nextRooms.contains(input)) {
return input;
}
}
}
}
public void start() throws MalformedURLException {
Map<String, Room> rooms = new HashMap<>();
rooms.put("room a", new Room("Room A", new URL("http://i.imgur.com/7XQD5Pt.png"), "Room B", "Room C"));
rooms.put("room b", new Room("Room B", new URL("http://i.imgur.com/7XQD5Pt.png"), "Room A"));
rooms.put("room c", new Room("Room C", new URL("http://i.imgur.com/7XQD5Pt.png"), "Room A", "Win"));
String player = JOptionPane.showInputDialog(null, "What is your name?");
JOptionPane.showMessageDialog(null, "Welcome " + player + " to the Haunted House!");
Room room = rooms.get("room a");
while (true) {
room.showInfo(player);
String nextRoom = room.nextRoomName(player).toLowerCase();
if ("win".equalsIgnoreCase(nextRoom)) {
return;
}
if (rooms.containsKey(nextRoom)) {
room = rooms.get(nextRoom);
}
}
}
That's kind of complicated, especially if you're new to Java or Object Oriented , so alternatively make each room a method. And depending on what the user decides, call the appropriate method and so on.
void start() {
roomA();
}
void roomA() {
String input = JOptionPane....
if (input.equals("Room B")) {
roomB();
}
}
void roomB() {
String input = JOptionPane....
if (input.equals("Room A")) {
roomA();
} else if (input.equals("win")) {
win();
}
}
void win() {
JOptionPane.showMessageDialog...
}
I am creating a coin flip game for an assignment that saves your last high score and name. the program works fine if there is not a high score file already there, but if there is a file there the program stops working.
import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
public class BradySkuza43
{
public static void main( String[] args ) throws Exception
{
Scanner keyboard = new Scanner(System.in);
String coin, again, bestName, saveFile = "coin-flip-score.txt";
int flip, streak = 0, best;
File in = new File(saveFile);
if ( in.createNewFile() )
{
System.out.println("Save game file doesn't exist. Created.");
best = 1;
bestName = " ";
}
else
{
Scanner input = new Scanner(in);
bestName = input.next();
best = input.nextInt();
input.close();
System.out.println("High score is " + best + " flips in a row by " + bestName );
}
do
{
flip = 1 + (int)(Math.random()*2);
if ( flip == 1 )
{
coin = "HEADS";
}
else
{
coin = "TAILS";
}
System.out.println( "You flip a coin and it is... " + coin );
if ( flip == 1 )
{
streak++;
System.out.println( "\tThat's " + streak + " in a row...." );
System.out.print( "\tWould you like to flip again (y/n)? " );
again = keyboard.next();
}
else
{
streak = 0;
again = "n";
}
} while ( again.equals("y") );
System.out.println( "Final score: " + streak );
if ( streak > best )
{
System.out.println("That's a new high score!");
System.out.print("Your name: ");
bestName = keyboard.next();
best = streak;
}
else if ( streak == best )
{
System.out.println("That ties the high score. Cool.");
}
else
{
System.out.println("You'll have to do better than " + streak + "if you want a high score.");
}
PrintWriter out = new PrintWriter( new FileWriter(saveFile) );
out.println(bestName);
out.println(best);
out.close();
}
}
when there is a file already there I get a NoSuchElement error. I am assuming it has to do with the import functions but I am unaware of how to fix it.
The way you read 'best' when there is already a file (with the 'best' value) seems to be incorrect. You may be looking for something like this (modify based on your data) to read the 'saved best value'.
BufferedReader reader = new BufferedReader(new FileReader(in));
String readNumber = "";
while (reader.readLine() != null) {
readNumber += reader.readLine();
}
best = Integer.valueOf(readNumber);
Ended up having to just run the code to see how the savefile is being produced. Seeing that NoSuchElement exception is coming from the second read from the file (input.nextInt()) pointed to the problem.
If you don't beat the existing the streak (including getting TAILS as your first flip), you aren't prompted for a name. This makes the savefile read
\n
1
\n
Scanner by default ignore whitespace. You don't check if there is available input (hasNext methods). When you call the next() or nextInt() when there is no input you get NoSuchElement. Why is this happening from the save?
Line by line:
bestName = input.next(); <-- This is getting the "1" since there is a name saved
best = input.nextInt(); <-- since the 1 was already read, so there's nothing to get
That second input with the savefile after getting an initial TAILS, is causing your crash.
Two solutions, make sure you are getting and saving the bestName in the else at the end of your main, or be more careful in reading the savefile.
(edit)
In general when using Scanner (or just about anything API that has a the hasNext()/next() style), it's best to call and check hasNext() before each next(). This will ensure you have something to get from the next().
Even if you don't think there is a possible reason for there not to be something there, having something like
if(!foo.hasNext) {
System.out.println("foo should really have something here, but hasNext says it doesn't);
System.exit();
}
will stop your code in its tracks if there is a problem, and give you a stop to add some debug statements to see what's going on.
Here are some suggestions:
Your high score file's name doesn't change, right? It shouldn't be a variable, it should be a static final variable.
Play the game and then decide whether or not this is a high score. So you should have a getHighScore() method (which can be static).
If the new score is a high score, then write it to the high score file. There should be a method static writeHighScore(final String name, final int score).
So I would change your program to something more like this:
public class BradySkuza43
{
public static final String HIGH_SCORE_FILE = "coin-flip-score.txt";
public static void main( String[] args ) throws Exception
{
final Scanner keyboard = new Scanner(System.in);
final int highScore = getHighScore();
final int newScore = getScore(keyboard);
if(newScore != 0 && newScore > highScore){
final String name = getName(keyboard);
writeHighScore(name, newScore);
}
private static int highScore(){
// read high score from high score file or return Integer.MIN_VALUE if
// no high score file exists
}
private static int getScore(final Scanner keyboard){
// play game, prompt user, get input, etc. and then
// return the player's score.
}
private static String getName(final Scanner keyboard){
// prompt the user for their name and return their input
}
private static void writeHighScore(final String name, final int score){
// write this high score (with the name) to the high score file
}
}
I'm using an ArrayList to save the name, day and time of a show. My program requires me to output the number of shows that play on each day of the week. I've inputted 4 different shows, two of which are on the same day. So far, the only thing the output's given me is "On Thursday there are/is 2 show(s)." The other two didn't show. How can I make is so that it displays the number of shows for each day I've inputted? Here's my code for that:
String showDay = ((showInfo)show.get(0)).day.toString();
int totalShows = 0;
//print occurences for how many shows play each day
for (int i = 0; i < show.size(); i++) {
if (showDay.equals(((showInfo)show.get(i)).day.toString())) {
totalShows++;
}
}
System.out.println("On " + showDay + " there are/is " + totalShows + " show(s).");
}
Here's my code for the shows I input:
//input information
do{
showInfo temp = new showInfo();
System.out.print("Enter the name of show: ");
String showName = br.readLine();
temp.name = showName;
System.out.print("Enter which day of the week a new episode premieres: ");
String showDay = br.readLine();
temp.day = showDay;
System.out.print("Enter time in 24-hour format (e.g. 2100, 1900): ");
int showTime = Integer.valueOf(br.readLine()).intValue();
temp.time = showTime;
show.add(temp);
System.out.print("Would you like to add another show? (y/n) ");
}
while((br.readLine().compareTo("n")) != 0);
Keep in mind that I'm using Java 1.4. No other choice. By teacher's demand.
This is probably obvious, but I'm being oblivious right now. Any help would be great! Thanks in advance!
EDIT:
String showDay = ((showInfo)show.get(0)).day.toString();
if("sunday".equalsIgnoreCase(showDay)){
showdayCount[0]++;
System.out.println("There are/is " + showdayCount[0]++ + " show on Sunday.");
}else if("monday".equalsIgnoreCase(showDay)){
showdayCount[1]++;
System.out.println("There are/is " + showdayCount[1]++ + " show on Monday.");
}else if("tuesday".equalsIgnoreCase(showDay)){
showdayCount[2]++;
System.out.println("There are/is " + showdayCount[2]++ + " show on Tuesday.");
}else if("wednesday".equalsIgnoreCase(showDay)){
showdayCount[3]++;
System.out.println("There are/is " + showdayCount[3]++ + " show on Wednesday.");
}else if("thursday".equalsIgnoreCase(showDay)){
showdayCount[4]++;
System.out.println("There are/is " + showdayCount[4]++ + " show on Thursday.");
}else if("friday".equalsIgnoreCase(showDay)){
showdayCount[5]++;
System.out.println("There are/is " + showdayCount[5]++ + " show on Friday.");
}else if("saturday".equalsIgnoreCase(showDay)){
showdayCount[6]++;
System.out.println("There are/is " + showdayCount[6]++ + " show on Saturday.");
}
This is also only giving me one line. What am I doing wrong?! :(
EDIT:
What I want is to input name/day/time of a TV show, then later be able to display the amount of shows that are on that specific day!
For example, Big Bang Theory and Community are both on Thursday. So the code would output something like
There are 2 shows on Thursday.
Nothing's worked, so far.
You only get one day from this line:
String showDay = ((showInfo)show.get(0)).day.toString();
Here's my hack solution (may have some errors, like a misnamed variable but you should be able to fix it):
//Create a map that maps days to the shows that are on that day
LinkedHashMap showDays=new LinkedHashMap(); //String to Set map
String[] days={"Sunday","Monday", ....};//put the rest of the days in here
for(int dayIndex=0;dayIndex<days.length;dayIndex++){
String day=days[dayIndex];
showDays.put(day,new HashSet());
}
//iterate through the shows and put them in their respective days in the map
for (int i = 0; i < show.size(); i++) {
String dayForShow=((showInfo)show.get(i)).day.toString();
showDays.get(dayForShow).put(show.get(i));
}
//now print out how many shows are on each day
for(int dayIndex=0;dayIndex<days.length;dayIndex++){
String day=days[dayIndex];
int showsToday=showDays.get(day).size();
///do your print out now
}
You can make 'LinkedHashMap showDays' a class variable and add to it each time you add to show (and remove from it each time you remove from show).
PS. Tell your teacher it is no longer 2002, technology moves on and they make my job harder.
Create a Show class
public class Show {
String showName;
String showDay;
int showTime;
static int[] showdayCount = new int[7];
public Show(String showName, String, showDay, iny showTime){
this.showName = showName;
this.showDay = showDay;
this.showTime = showTime;
// increment showDayCOunt[] according to showDay from
switch(showDay){
case "Sunday": showDayCount[0]++; break;
case "Monday": showDayCount[1]++; break;
case "Tuesday": showDayCount[2]++; break;
case "Wednesday": showDayCount[3]++; break;
case "Thursday": showDayCount[4]++; break;
case "Friday": showDayCount[5]++; break;
case "Saturday": showDayCount[6]++; break;
}
}
}
Here's your main method from YourClass
public static void main(String[] args){
// Create Array of Shows
Show[] shosList = new Show[4]; // or how many ever shows you have
// Get your inputs for showName, showDay, showTime
Sting showName =
String showDay =
int showTime =
// Create show Object
Show show = new Show(showName, showDate, showTime);
// add show to ArrayList
showList[someIndex] = show;
// Do all other stuff then print
// when you print, you can get the showDayCount directly from the Show class
}
Now I don't want to do everything for you. I just want to get you headed in the right direction. Note that if you want the above to happen more than once, consider putting inside of a loop.
Edit: With getShowdayCount
Add this to my above Show class
public int getShowdayCount(String showday){
switch(showDay){
case "Sunday": return showDayCount[0]; break;
case "Monday": return showDayCount[1]; break;
case "Tuesday": return showDayCount[2]++; break;
case "Wednesday": return showDayCount[3]++; break;
case "Thursday": return showDayCount[4]++; break;
case "Friday": return showDayCount[5]++; break;
case "Saturday": return showDayCount[6]++; break;
}
}
Edit: With example if/else if from switch statement
// for main method inputs
if ("sunday"equalsIgnoreCase(showDay){
showdayCount[0]++
} else ("monday".equalsIgnoreCase(showDay){
showdayCount[1]++
} // finish if/else if statement
// for getShowdayCount method
if ("sunday"equalsIgnoreCase(showDay){
return showdayCount[0];
} else ("monday".equalsIgnoreCase(showDay){
return showdayCount[1];
} // finish if/else if statement
You can call it from your main class like this
show.getShowdayCount(show.showday);
Edit: Actually, Just put the above edit in you class with the main method
YourClassWithMainMethod{
static int[] showdayCount = new int[7];
public static void mina(String[] args){
// call getShowdayCount here
getShowdayCount(String showday);
}
public static int getShowdayCount(String showday){
}
}
Edit: What you do want and what you don't want
You dont need this in you if statement
System.out.println("There are/is " + showdayCount[5]++ + " show on Friday.");
When you want to print all the shows:
for (int i = 0; i < showdayCount.length; i++){
int showday;
if (i == 0){
showday = "Sunday
finish the if/else if statements
}
System.out.println("There is " + showDayCount[i] + " shows on " + showday);
}