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.
Related
I'm struggling here. My program is about a simple sign in and log in using array. Now, whenever I want to sign in, I want all the usernames and passwords to be displayed whenever I want to check if all the accounts I created are successfully collected in an array. Now whenever I want to display all the accounts, usernames aren't displaying, just the passwords.
Here is my code:
package login;
import java.util.*;
import static java.lang.System.out;
public class login {
public static void main(String [] args) {
String user [] = new String [100];
String pass [] = new String [100];
int sign=0;
boolean again=true, logAgain=true;
Scanner scan = new Scanner (System.in);
while(again) {
out.println("[1]Sign-up\n[2]Log-in\n[3]Display Account?\n[4]Exit");
out.print("Select: ");
int a=scan.nextInt();
if (a==1) {
again=false;
sign++;
out.print("Username: ");
user[sign]=scan.nextLine();
scan.nextLine();
out.print("Password: ");
pass[sign]=scan.nextLine();
out.println("Log in now? [Y/N] : ");
String b=scan.next();
if(b.equals("Y")||b.equals("y")) {
again=true;
} else {
again=false;
System.exit(0);
}
} else if(a==2){
again=false;
logAgain=true;
while(logAgain) {
out.print("Username: ");
String userU=scan.nextLine();
scan.nextLine();
out.print("Password: ");
String userP=scan.nextLine();
if (userU.equals(user[sign])&&userP.equals(pass[sign])) {
out.println("You're logged in!");
logAgain=false;
out.println("Back to menu? [Y/N] : ");
String c=scan.next();
if (c.equals("Y")||c.equals("y")) {
again=true;
} else {
System.exit(0);
}
}else if (!userU.equals(user[sign])&&userP.equals(pass[sign])) {
out.println("Invalid username or Password!");
logAgain=true;
}else {
again=true;
logAgain=false;
out.println("Please register first!");
}
}
} else if (a==3) {
again=false;
if (sign<1) {
out.println("\nNo account to display!\nPlease sign-up first.\n");
again=true;
} else {
System.out.println("");
System.out.printf("%-15s%10s\n","Username","Passwords");
for (int i = 1; i <=sign; i++)
System.out.printf("%-15s%10s\n",user[i],pass[i]);
System.out.println("");
out.println("Back to menu? [Y/N] : ");
String c=scan.next();
if (c.equals("Y")||c.equals("y")) {
again=true;
} else {
System.exit(0);
}
}
} else if(a==4) {
again=false;
System.exit(0);
} else {
}
}
}
}
And my output goes like this:
[1]Sign-up
[2]Log-in
[3]Display Account?
[4]Exit
Select: 3
Username Passwords
Password
pass
evohohivr
Back to menu? [Y/N] :
Thank you in advance.
Your discarding the wrong Scanner input. It should read like this:
if (a==1) {
again=false;
sign++;
out.print("Username: ");
scan.nextLine(); // This was the wrong order
user[sign]=scan.nextLine();
out.print("Password: ");
pass[sign]=scan.nextLine();
out.println("Log in now? [Y/N] : ");
String b=scan.next();
if(b.equals("Y")||b.equals("y")) {
again=true;
} else {
again=false;
System.exit(0);
}
}
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 working on a text-based adventure game and need some help handling the IndexOutOfBounds exception on the getUserRoomChoice() function. I have an index of 3 on the menu so when the user enters a number > 3, it throws that exception. I tried using a try-catch on the line where it prompts the user to "Select a Number" but it is not catching it.
Here is my main class:
import java.util.Scanner;
public class Game {
private static Room library, throne, study, kitchen;
private static Room currentLocation;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
initialSetupGame();
String reply;
do {
printNextRooms();
int nextRoomIndex = getUserRoomChoice();
Room nextRoom = getNextRoom(nextRoomIndex);
updateRoom(nextRoom);
System.out.print("Would you like to continue? Yes/No: ");
reply = input.nextLine().toLowerCase();
} while ('y' == reply.charAt(0));
goodbye();
}
public static void initialSetupGame() {
// Instantiate room objects of type Room
library = new Room("Library");
throne = new Room("Throne");
study = new Room("Study");
kitchen = new Room("Kitchen");
// Connect the objects to each other
library.addConnectedRoom(throne);
library.addConnectedRoom(study);
library.addConnectedRoom(kitchen);
throne.addConnectedRoom(library);
throne.addConnectedRoom(study);
throne.addConnectedRoom(kitchen);
study.addConnectedRoom(library);
study.addConnectedRoom(throne);
study.addConnectedRoom(kitchen);
kitchen.addConnectedRoom(library);
kitchen.addConnectedRoom(study);
kitchen.addConnectedRoom(throne);
// Welcome message
System.out.println("Welcome to Aether Paradise, "
+ "a game where you can explore"
+ " the the majestic hidden rooms of Aether.");
// Prompt user for a name
Scanner input = new Scanner(System.in);
System.out.print("\nBefore we begin, what is your name? ");
String playerName = input.nextLine();
System.out.print("\n" + playerName +"? Ah yes. The Grand Warden told us"
+ " to expect you. Nice to meet you, " + playerName + "."
+ "\nMy name is King, a member of the Guardian Aethelorian 12"
+ " who protect the sacred rooms of Aether."
+ "\nAs you hold the Warden's signet ring, you have permission"
+ " to enter.\n\nAre you ready to enter? ");
String response = input.nextLine().toLowerCase();
if ('n' == response.charAt(0)) {
System.out.println("Very well then. Goodbye.");
System.exit(0);
}
if ('y' == response.charAt(0)) {
System.out.println("\nA shimmering blue portal appeared! You leap "
+ "inside it and your consciousness slowly fades...");
}
else {
System.out.println("Invalid input. Please try again.");
System.exit(1);
}
// Set the player to start in the library
currentLocation = library;
System.out.print("\nYou have spawned at the library.");
System.out.println(currentLocation.getDescription());
}
public static void printNextRooms() {
// Lists room objects as menu items
System.out.println("Where would you like to go next?");
currentLocation.printListOfNamesOfConnectedRooms();
}
// How to handle the exception when input > index?
public static int getUserRoomChoice() {
Scanner input = new Scanner(System.in);
System.out.print("(Select a number): ");
int choice = input.nextInt();
return choice - 1;
}
public static Room getNextRoom(int index) {
return currentLocation.getConnectedRoom(index);
}
public static void updateRoom(Room newRoom) {
currentLocation = newRoom;
System.out.println(currentLocation.getDescription());
}
public static void goodbye() {
System.out.println("You walk back to the spawn point and jump into"
+ "the portal... \n\nThank you for exploring the hidden rooms "
+ "of Aether Paradise. Until next time.");
}
}
Room Class
import java.util.ArrayList;
public class Room {
// Instance variables
private String name;
private String description;
private ArrayList<Room> connectedRooms;
// Overloaded Constructor
public Room(String roomName) {
this.name = roomName;
this.description = "";
connectedRooms = new ArrayList<>();
}
// Overloaded Constructor
public Room(String roomName, String roomDescription) {
this.name = roomName;
this.description = roomDescription;
connectedRooms = new ArrayList<>();
}
// Get room name
public String getName() {
return name;
}
// Get room description
public String getDescription() {
return description;
}
// Add connected room to the array list
public void addConnectedRoom(Room connectedRoom) {
connectedRooms.add(connectedRoom);
}
// Get the connected room from the linked array
public Room getConnectedRoom(int index) {
if (index > connectedRooms.size()) {
try {
return connectedRooms.get(index);
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
return connectedRooms.get(index);
}
// Get the number of rooms
public int getNumberOfConnectedRooms() {
return connectedRooms.size();
}
// Print the connected rooms to the console
public void printListOfNamesOfConnectedRooms() {
for(int index = 0; index < connectedRooms.size(); index++) {
Room r = connectedRooms.get(index);
String n = r.getName();
System.out.println((index + 1) + ". " + n);
}
}
}
You have to use try-catch in function call of getNextRoom().
Because getNextRoom(nextRoomIndex) is causing the exception. You have to put those two statements in try block.
Change this to
Room nextRoom = getNextRoom(nextRoomIndex);
updateRoom(nextRoom);
this
try{
Room nextRoom = getNextRoom(nextRoomIndex);
updateRoom(nextRoom);
} catch(Exception e){
System.out.println("print something");
}
You must have a closer look to the piece of code, where you try to access the list (or array). That is the part, where the exception is thrown, not when the user enters it. There you have to check, if the given index is larger than the size of your list.
if( index >= list.size()) {
// handle error / print message for user
} else {
// continue normaly
}
In your case, it would probably be in the method getConnectedRoom(int index) in class Room.
Where is your try/catch block for the specific part? anyway, you can use IndexOutOfBound or Custome Exception for it.
1.create a custom Exception Class
class RoomeNotFoundException extends RuntimeException
{
public RoomeNotFoundException(String msg)
{
super(msg);
}
}
add try/catch block for the specific part
public class Game
{
do {
printNextRooms();
int nextRoomIndex = getUserRoomChoice();
if(nextRoomeIndex>3)
{
throw new RoomNotFoundException("No Rooms Available");
}else{
Room nextRoom = getNextRoom(nextRoomIndex);
updateRoom(nextRoom);
System.out.print("Would you like to continue? Yes/No: ");
reply = input.nextLine().toLowerCase();
}
} while ('y' == reply.charAt(0));
}
Or you can use IndexOutOfBoundException instead of RoomNotFoundException
My code creates a set of sport results using a scanner, the user enters input in this format "Home team : Away team : Home score : Away score" - each part is split into a string in the array. I want to create an error message if one part is missing for example "Error, Home team seems to be missing" for each corresponding section however;
I am a beginner and have been trying to put an else-if condition in the for loop to help make this error message however I am doing something wrong judging by the amount of errors I am getting (delete this token).
This code will help your program to validate the user-input as per the your requirements in your question, if any of the inputs is missed by the user it is reported to him:
import java.util.Scanner;
public class Test4 {
public static void ismissing(int i)
{
switch(i)
{
case 0:
System.out.println("Home team missing");
break;
case 1:
System.out.println("Away team missing");
break;
case 2:
System.out.println("Home score missing");
break;
case 3:
System.out.println("Away score missing");
break;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input as follows; ");
System.out.println("Home team : Away team : Home score : Away score");
String str=scanner.nextLine();
String array[]=str.split(":");
for(int i=0;i<array.length;i++)
{
if(array[i].equals(" "))
{
ismissing(i);
System.exit(0); //will exit program if something is missing
}
}
System.out.println("Correct Input");
}
}
If you are going to be creating numerous games, I would recommend you make a Game class as this will make it easier to manage a Game object as opposed to 2 Strings and 2 Integer values. With a Game object you can also output your desired string output using the toString method of your Game object. When getting the user input, the criteria I used is such that team names cannot be blank and team scores cannot be less than 0. If the user enters and empty string or an invalid integer, then we simply output a message indicating the invalid input and have the user try again until they get valid input. If you want to exit when this happens you could change this to accommodate a graceful exit of the program when the user enters invalid data.
I made two methods in the main, one to get a valid String team name, and another to get a valid Integer for the score. Again if the user inputs invalid data we will loop until the input is valid.
Game Class:
public class Game
{
String homeTeam = "";
String awayTeam = "";
int homeScore = -1;
int awayScore = -1;
public Game(String inHomeTeam, int inHomeScore, String inAwayTeam, int inAwayScore)
{
super();
this.homeTeam = inHomeTeam;
this.awayTeam = inAwayTeam;
this.homeScore = inHomeScore;
this.awayScore = inAwayScore;
}
#Override
public String toString()
{
return homeTeam + "[" + homeScore + "] | " + awayTeam + "[" + awayScore + "]";
}
public String getHomeTeam() {
return homeTeam;
}
public void setHomeTeam(String homeTeam) {
this.homeTeam = homeTeam;
}
public String getAwayTeam() {
return awayTeam;
}
public void setAwayTeam(String awayTeam) {
this.awayTeam = awayTeam;
}
public int getHomeScore() {
return homeScore;
}
public void setHomeScore(int homeScore) {
this.homeScore = homeScore;
}
public int getAwayScore() {
return awayScore;
}
public void setAwayScore(int awayScore) {
this.awayScore = awayScore;
}
}
Main
public class Main
{
static Scanner scanner = new Scanner(System.in);
static Game[] allGames;
static String homeTeam = "";
static String awayTeam = "";
static int homeScore = -1;
static int awayScore = -1;
static int numberOfGames = 0;
public static void main(String[] args)
{
numberOfGames = GetUserInt("How many games do you want to enter - 100 or less: ");
if (numberOfGames > 100)
numberOfGames = 100;
allGames = new Game[numberOfGames];
for (int i = 0; i < numberOfGames; i++) {
homeTeam = GetUserString("Enter the home team name: ");
homeScore = GetUserInt("Enter the home team score: ");
awayTeam = GetUserString("Enter the away team name: ");
awayScore = GetUserInt("Enter the away team score: ");
allGames[i] = new Game(homeTeam, homeScore, awayTeam, awayScore);
}
// output the users games
for(Game curGame : allGames)
{
if (curGame != null)
System.out.println(curGame.toString());
}
}
private static String GetUserString(String prompt)
{
String input = "";
while(true) {
System.out.print(prompt);
input = scanner.nextLine();
if (input.length() > 0)
return input;
else
System.out.println("Invalid input: Can not be empty string!");
}
}
private static int GetUserInt(String prompt)
{
String input = "";
while(true) {
System.out.print(prompt);
input = scanner.nextLine();
if (input.length() > 0) {
if (isValidInt(input)) {
int value = Integer.parseInt(input);
if (value >= 0) {
return value;
}
else {
System.out.println("Invalid input: Score can not be negative");
}
}
else {
System.out.println("Invalid input: Score must be a valid integer");
}
}
else {
System.out.println("Invalid input: Score can not be empty");
}
}
}
private static boolean isValidInt(String inString)
{
try {
Integer.parseInt(inString);
return true;
}
catch (NumberFormatException e) {
return false;
}
}
}
Hope this helps!
There are some things you can do, like checking the values with an if statement. You can say something like:
if(stringIsEmpty)
{
print ("Error");
}
else
{
/*Keep executing program*/
}
You could also use a try/catch block. This could help because if a string is null (empty), you can throw a null pointer exception and define it the way you want, like this:
try
{
/*blank string code*/
}catch(NullPointerException e)
{
System.out.println("Empty strings are not allowed");
}
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...
}