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...
}
Related
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;
}
}
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 wrote the piece of Java code below. When running it and typing in any value (either one defined, e.g. latte, or any other, e.g. az integer), I get an InputMismatchException.
As far as I could find answers, this exception means that the input type does not match the expected type. What am I missing, why isn't the code recognizing a String input? Thanks for the supprort.
Cheers, Gabor
package Lesson1;
import java.util.Scanner;
public class Coffee {
public static void main(String[] args) {
//I define the type of coffees as Strings, plus the order as String as well
String espresso = "espresso";
String americano = "americano";
String cappuccino = "cappuccino";
String latte = "latte";
String order = new String();
//I ask the user for their input
Scanner choice = new Scanner(System.in);
System.out.println("What kind of coffee would you like? We have: espresso, americano, cappuccino and latte");
//depending on the user's choice, the corresponding name is displayed; if any other string is entered, the else clause is displayed
if (order.equals(choice.next(espresso))) {
System.out.println("Your order: " + espresso);
} else if (order.equals(choice.next(americano))) {
System.out.println("Your order: " + americano);
} else if (order.equals(choice.next(cappuccino))) {
System.out.println("Your order: " + cappuccino);
} else if (order.equals(choice.next(latte))) {
System.out.println("Your order: " + latte);
} else {
System.out.println("Unfortunately we can't serve you. Have a nice day!");
}
}
}
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Lesson1.Coffee.main(Coffee.java:22)
You write once in default input, but you're trying to read multiple times using choice.next(..).
One solution is assign your choice in a String before the if-else statement and then check it using equalsIgnoreCase.
//I ask the user for their input
Scanner choice = new Scanner(System.in);
System.out.println("What kind of coffee would you like? We have: espresso, americano, cappuccino and latte");
String picked = choice.next();
//depending on the user's choice, the corresponding name is displayed; if any other string is entered, the else clause is displayed
if (picked.equalsIgnoreCase(espresso)) {
System.out.println("Your order: " + espresso);
} else if (picked.equalsIgnoreCase(americano)) {
System.out.println("Your order: " + americano);
} else if (picked.equalsIgnoreCase(cappuccino)) {
System.out.println("Your order: " + cappuccino);
} else if (picked.equalsIgnoreCase(latte)) {
System.out.println("Your order: " + latte);
} else {
System.out.println("Unfortunately we can't serve you. Have a nice day!");
}
I think you are using the Scanner wrong. Trying using the next() method with no parameters to get the user input, and only call it once (instead of inside each if else branch). Like this:
package com.company;
import java.util.Scanner;
public class Coffee {
public static void main(String[] args) {
//I define the type of coffees as Strings, plus the order as String as well
String espresso = "espresso";
String americano = "americano";
String cappuccino = "cappuccino";
String latte = "latte";
//I ask the user for their input
Scanner choice = new Scanner(System.in);
System.out.println("What kind of coffee would you like? We have: espresso, americano, cappuccino and latte");
//depending on the user's choice, the corresponding name is displayed; if any other string is entered, the else clause is displayed
String order = choice.next();
if (order.equals(espresso)) {
System.out.println("Your order: " + espresso);
} else if (order.equals(americano)) {
System.out.println("Your order: " + americano);
} else if (order.equals(cappuccino)) {
System.out.println("Your order: " + cappuccino);
} else if (order.equals(latte)) {
System.out.println("Your order: " + latte);
} else {
System.out.println("Unfortunately we can't serve you. Have a nice day!");
}
}
}
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) !
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.