Simple adventure game producing wrong output, no errors when compiling - java

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!

Related

How to check for and use input from a different methood

I am making a game and a the end of the game I want it to call the user by the name that they put in,, this is the code I have.
private static final Scanner console = new Scanner(System.in);
public static void main(String[] args) {// follow the prompts.//
System.out.println("Hello user! what is your name? ");
String Name = console.nextLine();
System.out.println("Really? " + Name + " is too weird to be a real name.");
confirmation();
Mascot();
System.out.println("Thank you for playing the demo");
console.close();
}
public static void confirmation() {
System.out.print("is that REALLY your name? (type Y/N) ");
String yN = console.nextLine();
String a = yN;
if (a.toLowerCase().contains("y")) {
System.out.println("I still dont belive you, so you will have to answer 3 riddles before you can continue to the game");
} else {
calledIt();
}
}
public static void calledIt() {
System.out.println("I knew it!");
System.out.print("whats your real name? ");
String realName = console.nextLine();
System.out.println(
"" + realName + " sounds like a real name, but you lied the first time so you will need to answer riddles 3 to continue to the game");
}
public static boolean Mascot() {
System.out.println("what Is our school mascot?");
String b = console.nextLine();
if (b.toLowerCase().contains("tiger")) {
System.out.println("Good, next riddle.");
System.out.println("What runs around the whole yard without moving?");
String c = console.nextLine();
if (c.toLowerCase().contains("fence")) {
System.out.println("Good, next riddle.");
System.out.println("What goes on four feet in the morning, two feet at noon, and three feet in the evening? ");
String d = console.nextLine();
if (d.toLowerCase().contains("man")) {
System.out.println("You, have sucsefully passed the third riddle");
return true;
} else {
System.out.println("You have failed");
return false;
}
} else {
System.out.println("You have failed");
return false;
}
} else {
System.out.println("You have failed");
return false;
}
}
I want for it to at the end print * user's name*, you have successfully passed the third riddle.
but it needs to be able to weather the first name was kept, or if this sequence was used.
public static void calledIt() {
System.out.println("I knew it!");
System.out.print("whats your real name? ");
String realName = console.nextLine();
System.out.println(
"" + realName + " sounds like a real name, but you lied the first time so you will need to answer riddles 3 to continue to the game");
}
and if it has been activated it needs to use the new name.
Change return type of calledIt() to String and return realName from this method
Change return type of confirmation() to String. Initialize a String (String name = null). In the else part, assign the value returned from calledIt() to this string (String name = calledIt()). Return name.
In main, if the value returned from confirmation() is not null, update Name with this new value.
Pass the Name as input to Mascot method. For this, you have to update the Mascot method to accept a String as input.
You can pass the variable into confirmation() and calledIt() like this
public static void main(String[] args) {// follow the prompts.//
System.out.println("Hello user! what is your name? ");
String Name = console.nextLine();
System.out.println("Really? " + Name + " is too weird to be a real name.");
confirmation(Name);
Mascot();
System.out.println("Thank you for playing the demo");
console.close();
}
public static void confirmation(String name) {
System.out.print("is that REALLY your name? (type Y/N) ");
String yN = console.nextLine();
String a = yN;
if (a.toLowerCase().contains("y")) {
System.out.println("I still dont belive you, so you will have to answer 3 riddles before you can continue to the game");
} else {
calledIt(name);
}
}
public static void calledIt(String realName){
System.out.println("I knew it!");
System.out.print("whats your real name? ");
System.out.println(
"" + realName + " sounds like a real name, but you lied the first time so you will need to answer riddles 3 to continue to the game");
}
You could do the following change:
public static void main(String[] args) { // follow the prompts.//
System.out.println("Hello user! What is your name? ");
String name = console.nextLine();
System.out.println("Really? " + name + " is too weird to be a real name.");
System.out.print("Is that REALLY your name? (type Y/N) ");
String yN = console.nextLine();
String a = yN;
if (a.toLowerCase().contains("y")) {
System.out.println("I still don't believe you, so you will have to answer 3 riddles before you can continue to the game");
} else {
System.out.println("I knew it!");
System.out.print("Whats your real name? ");
name = console.nextLine();
System.out.println(
"" + name + " sounds like a real one, but you lied the first time so you will need to answer riddles 3 to continue to the game");
}
mascot(name);
System.out.println("Thank you for playing the demo");
console.close();
}
public static boolean mascot(String name) {
System.out.println("what Is our school mascot?");
String b = console.nextLine();
if (b.toLowerCase().contains("tiger")) {
System.out.println("Good, next riddle.");
System.out.println("What runs around the whole yard without moving?");
String c = console.nextLine();
if (c.toLowerCase().contains("fence")) {
System.out.println("Good, next riddle.");
System.out.println("What goes on four feet in the morning, two feet at noon, and three feet in the evening? ");
String d = console.nextLine();
if (d.toLowerCase().contains("man")) {
System.out.println(name + ", you have successfully passed the third riddle");
return true;
} else {
System.out.println("You have failed");
return false;
}
} else {
System.out.println("You have failed");
return false;
}
} else {
System.out.println("You have failed");
return false;
}
}

If/else statements written as loops

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...
}

Need to start again at a certain point in java

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) !

Coin flip game save issue

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
}
}

Getting a String from one part of the class to the other

ORIGINAL QUESTION
so I am new to coding. Ive probably hit my 3 month mark. But I like to go past the class I am taking because this stuff really interests me. So I wanted to mess around with some code to try and understand it some more. After a lot of googling this is as far as I have gotten. The program is suppose to ask for a password. If the right password is entered then it will show two options. Option 1 will have you put information in (name, last name, age, cell phone number). Option 2 will show the information stored. Everything so far has been going great besides the fact I want to display the information gained from A into B. I have a two separate classes.
The first is called main (This is the main method witch works fine)
import javax.swing.*;
//Created by: Robert Duval
//3/26/13
public class Main
{
public static void main(String[] args)
{
String tempString, passWord = "mrGiggles", input = "null";
while(!input.equals(passWord)) //This loop looks for the password
{
input = JOptionPane.showInputDialog("Hello, please enter password.");
if(input.equals(passWord)) //If the password is correct
{
while(!input.equals("Enter information")||!input.equals("View profile")) //This loop looks to see what to do next
{
input = JOptionPane.showInputDialog("Welcome\nEnter information\nView profile");
if(input.equals("Enter information"))
{
display.input();
}
else if(input.equals("View profile"))
{
display.stored();
}
else
{
tempString = "ERROR\nCannot find what you are looking for.";
JOptionPane.showMessageDialog(null, tempString);
}
}
}
else //If the password is incorrect.
{
tempString = "In-correct";
JOptionPane.showMessageDialog(null, tempString);
}
}
}
}
My second class (display) is where I have been running into problems. Should I make them Public Strings? Or what? The input() method fills the Strings that I want to use in the stored() method. And I have been looking this up for awhile but I don't understand the return and what not. If you could help me out and point out my flaws that would be fantastic.
import javax.swing.*;
//Created by: Robert Duval
//3/26/13
public class display
{
public static void input() //This is the method that will ask for the information
{
String age="null", cellNumber="null", name="null", lastName="mull", allInfo = name+ "\n" +lastName+ "\n" +age+ "\n" +cellNumber+ "\n";
name = JOptionPane.showInputDialog("Enter the first name");
lastName = JOptionPane.showInputDialog("Enter the last name");
age = JOptionPane.showInputDialog("Enter the age");
cellNumber = JOptionPane.showInputDialog("Enter the cell phone number");
display.stored();
}
public static void stored() //This method is asking the user what to show for the input() method.
{
String loop = "loop", tempString;
while(!loop.equals("break"))
{
tempString = JOptionPane.showInputDialog("What information would you like to see? \nname\nage\ncell number\nall info\nquit");
if(tempString.equals("name")||tempString.equals("Name")||tempString.equals("NAME"))
{
JOptionPane.showMessageDialog(null, name); //This is where I want to display the name String from input() method
}
else if(tempString.equals("age")||tempString.equals("Age")||tempString.equals("AGE"))
{
JOptionPane.showMessageDialog(null, age); //This is where I want to display the age String from input() method
}
else if(tempString.equals("cell number")||tempString.equals("Cell number")||tempString.equals("cell Number")||tempString.equals("Cell Number")||tempString.equals("cellNumber")||tempString.equals("cellnumber")||tempString.equals("Cellnumber"))
{
JOptionPane.showMessageDialog(null, cellNumber); //This is where I want to display the cellNumber String from input() method
}
else if(tempString.equals("all info")||tempString.equals("All info")||tempString.equals("all Info")||tempString.equals("All Info")||tempString.equals("allinfo")||tempString.equals("allInfo")||tempString.equals("Allinfo")||tempString.equals("AllInfo"))
{
JOptionPane.showMessageDialog(null, allInfo); //This is where I want to display the allInfo String from input() method
}
else if(tempString.equals("quit")||tempString.equals("Quit")||tempString.equals("QUIT"))
{
loop = "break"; //Breaks the while loop
}
else
{
tempString = "Not a valid answer. \nPlease try again.";
JOptionPane.showMessageDialog(null, tempString);
}
}
}
}
UPDATED QUESTION
Okay so after looking at the answers I got it really close! But for some reason when I go to look at the data it produces "null" for everything. I'm thinking its because I I close the method and then re open it so everything refreshes. How do I save the information put in input. Leave the method. Come back but open display instead and show that information?
Here is the updated code:
main class
import javax.swing.*;
//Created by Robert Duval
//3/26/13
public class Main
{
public static void main(String[] args)
{
String tempString, passWord = "mrGiggles", input = "null";
display display = new display();
while(!input.equals(passWord)) //This loop looks for the password
{
input = JOptionPane.showInputDialog("Hello, please enter password.");
if(input.equals(passWord)) //If the password is correct
{
while(!input.equalsIgnoreCase("Enter information")||!input.equalsIgnoreCase("View profile")) //This loop looks to see what to do next
{
input = JOptionPane.showInputDialog("Welcome\nEnter information\nView profile");
if(input.equalsIgnoreCase("Enter information"))
{
display.input();
}
else if(input.equalsIgnoreCase("View profile"))
{
display.stored();
}
else
{
tempString = "ERROR\nCannot find what you are looking for.";
JOptionPane.showMessageDialog(null, tempString);
}
}
}
else //If the password is incorrect.
{
tempString = "In-correct";
JOptionPane.showMessageDialog(null, tempString);
}
}
}
}
display class
import javax.swing.*;
//Created by: Robert Duval
//3/26/13
public class display
{
String age="null", cellNumber="null", name="null", lastName="mull", allInfo = name+ "\n" +lastName+ "\n" +age+ "\n" +cellNumber+ "\n";
public void input()
{
name = JOptionPane.showInputDialog("Enter the first name");
lastName = JOptionPane.showInputDialog("Enter the last name");
age = JOptionPane.showInputDialog("Enter the age");
cellNumber = JOptionPane.showInputDialog("Enter the cell phone number");
}
public void stored()
{
String tempString;
while(true)
{
tempString = JOptionPane.showInputDialog("What information would you like to see? \nname\nage\ncell number\nall info\nquit");
if (tempString.equalsIgnoreCase("name"))
{
JOptionPane.showMessageDialog(null, name); //This is where I want to display the name String from input() method
}
else if(tempString.equalsIgnoreCase("age"))
{
JOptionPane.showMessageDialog(null, age); //This is where I want to display the age String from input() method
}
else if(tempString.equalsIgnoreCase("cell number"))
{
JOptionPane.showMessageDialog(null, cellNumber); //This is where I want to display the cellNumber String from input() method
}
else if(tempString.equalsIgnoreCase("all info")||tempString.equalsIgnoreCase("allinfo"))
{
JOptionPane.showMessageDialog(null, allInfo); //This is where I want to display the allInfo String from input() method
}
else if(tempString.equalsIgnoreCase("quit"))
{
break; //Breaks the while loop
}
else
{
tempString = "Not a valid answer. \nPlease try again.";
JOptionPane.showMessageDialog(null, tempString);
}
}
}
}
BTW thanks everyone for all the help. I appreciate it.
SOLUTION
Alright guys. I played with it some more and found out how to get it to work. Thanks for all of the help it was needed.
main class
import javax.swing.*;
//Created by Robert Duval
//3/26/13
public class Main
{
public static void main(String[] args)
{
String tempString, passWord = "mrGiggles", input = "null";
display display = new display();
while(!input.equals(passWord)) //This loop looks for the password
{
input = JOptionPane.showInputDialog("Hello, please enter password.\nQuit");
if(input.equals(passWord)) //If the password is correct
{
while(!input.equalsIgnoreCase("Enter information")||!input.equalsIgnoreCase("View profile")) //This loop looks to see what to do next
{
input = JOptionPane.showInputDialog("Welcome\nEnter information\nView profile\nLog out");
if(input.equalsIgnoreCase("Enter information"))
{
display.input();
}
else if(input.equalsIgnoreCase("View profile"))
{
display.stored();
}
else if(input.equalsIgnoreCase("log out"))
{
break;
}
else
{
tempString = "ERROR\nCannot find what you are looking for.";
JOptionPane.showMessageDialog(null, tempString);
}
}
}
else if(input.equalsIgnoreCase("quit"))
{
break;
}
else //If the password is incorrect.
{
tempString = "In-correct";
JOptionPane.showMessageDialog(null, tempString);
}
}
}
}
display class
import javax.swing.*;
//Created by: Robert Duval
//3/26/13
public class display
{
String age="null", cellNumber="null", name="null", lastName="null";
public void input()
{
name = JOptionPane.showInputDialog("Enter the first name");
lastName = JOptionPane.showInputDialog("Enter the last name");
age = JOptionPane.showInputDialog("Enter the age");
cellNumber = JOptionPane.showInputDialog("Enter the cell phone number");
}
public void stored()
{
String tempString, allInfo = name+ "\n" +lastName+ "\n" +age+ "\n" +cellNumber+ "\n";
while(true)
{
tempString = JOptionPane.showInputDialog("What information would you like to see? \nName\nAge\nCell number\nAll info\nBack");
if (tempString.equalsIgnoreCase("name"))
{
JOptionPane.showMessageDialog(null, name);
}
else if(tempString.equalsIgnoreCase("age"))
{
JOptionPane.showMessageDialog(null, age);
}
else if(tempString.equalsIgnoreCase("cell number"))
{
JOptionPane.showMessageDialog(null, cellNumber);
}
else if(tempString.equalsIgnoreCase("all info")||tempString.equalsIgnoreCase("allinfo"))
{
JOptionPane.showMessageDialog(null, allInfo);
}
else if(tempString.equalsIgnoreCase("back"))
{
break;
}
else
{
tempString = "Not a valid answer. \nPlease try again.";
JOptionPane.showMessageDialog(null, tempString);
}
}
}
}
It runs perfectly!
P.S
It wouldn't let me answer my own question
You need to make your display class methods non-static and use an object with fields:
public class Display
{
private String age="null", cellNumber="null", name="null", lastName="mull", allInfo = name+ "\n" +lastName+ "\n" +age+ "\n" +cellNumber+ "\n";
public void input()
{
name = JOptionPane.showInputDialog("Enter the first name");
lastName = JOptionPane.showInputDialog("Enter the last name");
age = JOptionPane.showInputDialog("Enter the age");
cellNumber = JOptionPane.showInputDialog("Enter the cell phone number");
stored();
}
public void stored()
{
String tempString;
while(true)
{
tempString = JOptionPane.showInputDialog("What information would you like to see? \nname\nage\ncell number\nall info\nquit");
if(tempString.equalsIgnoreCase("name"))
{
JOptionPane.showMessageDialog(null, name); //This is where I want to display the name String from input() method
}
else if(tempString.equalsIgnoreCase("age"))
{
JOptionPane.showMessageDialog(null, age); //This is where I want to display the age String from input() method
}
else if(tempString.equalsIgnoreCase("cell number")||tempString.equals("Cell number")||tempString.equalsIgnoreCase("cellNumber"))
{
JOptionPane.showMessageDialog(null, cellNumber); //This is where I want to display the cellNumber String from input() method
}
else if(tempString.equalsIgnoreCase("all info")||tempString.equalsIgnoreCase("allinfo"))
{
JOptionPane.showMessageDialog(null, allInfo); //This is where I want to display the allInfo String from input() method
}
else if(tempString.equalsIgnoreCase("quit"))
{
break; //Breaks the while loop
}
else
{
tempString = "Not a valid answer. \nPlease try again.";
JOptionPane.showMessageDialog(null, tempString);
}
}
}
}
As you cann see I changed the class name from display to Display. This is a Java convention to distuingish class names from variable names. The methods are not static anymore, meaning you can't call them on the class, but only on an object of that class. Such an object can have fields describing it's condtion. To have access to those fields you need non-static members. The call display.stored() is now just stored() to call the method on the same object you just called input() on. To clearify it, you could also write this.stored(). this always point to the present object.
I also introduced the break command to the loop in the Display class.
Let's take a look what changes have to be made in your main class now:
public class Main
{
public static void main(String[] args)
{
String tempString, passWord = "mrGiggles", input = "null";
Display display = new Display();
while(!input.equals(passWord)) //This loop looks for the password
{
input = JOptionPane.showInputDialog("Hello, please enter password.");
if(input.equals(passWord)) //If the password is correct
{
while(!input.equals("Enter information")||!input.equals("View profile")) //This loop looks to see what to do next
{
input = JOptionPane.showInputDialog("Welcome\nEnter information\nView profile");
if(input.equals("Enter information"))
{
display.input();
}
else if(input.equals("View profile"))
{
display.stored();
}
else
{
tempString = "ERROR\nCannot find what you are looking for.";
JOptionPane.showMessageDialog(null, tempString);
}
}
}
else //If the password is incorrect.
{
tempString = "In-correct";
JOptionPane.showMessageDialog(null, tempString);
}
}
}
}
The line Display display = new Display() creates a new object of the Display class and assigns it to a variable with type Display and name display. If you call methods on display (which is now the variable) they are invoked on the object the variable points to instead of the class.

Categories

Resources