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;
}
}
Related
I am new to Java and have recently started coding within the last week. I have tried to build some basic things and did the following:
import java.util.Scanner;
public class App {
public static void main(String[] args){
// creating scanner object
Scanner userSex = new Scanner(System.in);
System.out.println("Enter your sex (male or female): ");
String sex = userSex.nextLine();
System.out.println("Thank you, you entered " + sex );
// new scanner
Scanner userAge = new Scanner (System.in);
System.out.println("Are you a child or adult: ");
String age = userAge.nextLine();
System.out.println("You are a " + sex + " " + age);
if (userAge.equals("child")) {
System.out.println("children");
} else if (userAge.equals("adult")) {
System.out.println("adults");
}
}
}
Unfortunately however, only the top of the code runs. The below code doesn't run and doesn't print anything out even when I enter "child" or "adult".
if (userAge.equals("child")) {
System.out.println("children");
} else if (userAge.equals("adult")) {
System.out.println("adults");
}
instead of
if(userAge.equals("child")) {
System.out.println("children");
}
else if(userAge.equals("adult")) {
System.out.println("adults");
}
do this
if(age.equals("child")) {
System.out.println("children");
}
else if(age.equals("adult")) {
System.out.println("adults");
}
The one thing that was already mentioned is that you only need one scanner object. It's unnecessary to create one for each string entered. The main problem is that you are testing if userAge equals "child" or "adult", but userAge is the scanner object. I think you meant to write age.equals("child"), as age is the actual String entered.
The following works:
import java.util.Scanner;
public class App {
public static void main(String[] args){
//creating scanner object
Scanner in = new Scanner(System.in);
System.out.println("Enter your sex (male or female): ");
String sex = in.next();
System.out.println("Thank you, you entered " + sex );
//new scanner
System.out.println("Are you a child or adult: ");
String age = in.next();
System.out.println("You are a " + sex + " " + age);
if(age.equals("child")) {
System.out.println("children");
}
else if(age.equals("adult")) {
System.out.println("adults");
}
}
}
Rather than creating two separate scanners you just use one and call the next()method. I also change the condition from if(userAge... to if(age...
There is no need to create two scanner object .Just create one scanner object.
You can also use BufferedReader instead of Scanner.In your code you use userAge.equals("child") .but this is not right since you store the value returned by scanner in age , use age to compare in if-else codition like age.equals("child")
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your sex (male or female): ");
String sex = scanner.nextLine();
System.out.println("Thank you, you entered " + sex );
System.out.println("Are you a child or adult: ");
String age = scanner.nextLine();
System.out.println("You are a " + sex + " " + age);
if (age.equals("child")) {
System.out.println("children");
} else if (age.equals("adult")) {
System.out.println("adults");
}
Reference Link:https://docs.oracle.com/javase/tutorial/essential/io/scanning.html
This is my code. The program won't give me the last print line "Thank you for using the Basic user Interface program."
public class nameClass {
public static void main(String[] args) {
String input;
String name;
int age;
double mileage;
displayApplicationInformation();
displayDivider("Start Program");
TerminateApplication();
// process name
displayDivider("Get Name");
name = getInput("name");
System.out.println("Your name is: " + name);
// Process age
displayDivider("Get Age");
input = getInput("Your age");
age = Integer.parseInt(input);
System.out.println("Your age is: " + age);
// Process Mileage
displayDivider("Get Mileage");
input = getInput("Your MPG");
mileage = Double.parseDouble(input);
System.out.println("Your car MPG is: " + mileage);
}// end of main
public static void displayApplicationInformation()
{
System.out.println("Welcome to the Basic User Interface Program");
}// end of displayApplicaionInformation
public static void displayDivider(String outputTitle) {
System.out.println("*********" + outputTitle + "********");
}// end of displayDvider
public static String getInput(String inputType)
{
String input = "";
input = JOptionPane.showInputDialog("Enter the " + inputType);
return input;
}
public static void TerminateApplication()
{
System.out.println("Thank you for using the Basic User Interface program");
return;
}
}// end of MainClass
You have to actually call the method TerminateApplication;
System.out.println("Your car MPG is: " + mileage);
TerminateApplication();
Simple, call TerminateApplication.
You are doing it on the 9th line of main().
Here, check this out:
displayDivider("Get Mileage");
input = getInput("Your MPG");
mileage = Double.parseDouble(input);
System.out.println("Your car MPG is: " + mileage);
//add this...
TerminateApplication();
Hope this helps!
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!");
}
}
}
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.
So I'm doing a TUI and this was my first iteration.
package bulb.classes;
import java.util.Scanner;
import java.util.ArrayList;
public class RoomTUI {
private ArrayList<Room> rooms;
Scanner scan = new Scanner (System.in);
private int userNumber;
private String userAnswer;
public void run() {
rooms = new ArrayList<Room>();
introduction();
userNumber = 0;
options();
while(userNumber < 5) {
if(userNumber == 1) {
newRoom();
}
if(userNumber == 2) {
addBulbToRoom();
}
if(userNumber == 3) {
clickAllBulbsInRoom();
}
if(userNumber == 4) {
printDescriptionOfBulbs();
}
}
System.out.println("Goodbye");
}
public int getUserInt(String aString) {
System.out.println(aString);
userAnswer = scan.nextLine();
userNumber = Integer.parseInt(userAnswer);
return userNumber;
}
public void displayRooms() {
System.out.println("Possible rooms to choose from.");
String tempString = "";
int roomIndex = 0;
for (int i = 0; i < rooms.size(); i++) {
tempString = tempString + "Room " + roomIndex++ + ": " + rooms.get(i).getDescription() + "\n";
}
System.out.println(tempString);
}
public void introduction() {
System.out.println("Welcome! With this program you can make rooms and design and place the light bulbs for each room you create.");
}
public void options() {
System.out.println("1 : Create a new Room");
System.out.println("2 : Add a bulb to an existing room");
System.out.println("3 : Click all of the bulbs in a particular room");
System.out.println("4 : Display a description of all bulbs in a particular room");
System.out.println("5 : Quit");
getUserInt("What would you like to do?");
}
public void newRoom() {
System.out.println("Please enter a name for your room");
String name = scan.nextLine();
Room aRoom = new Room(name);
rooms.add(aRoom);
System.out.println("You have added the " + name + ".");
options();
}
public void addBulbToRoom() {
displayRooms();
System.out.println("Which room do you want the bulb in?");
String choice = scan.nextLine();
int choiceNumber = Integer.parseInt(choice);
System.out.println("Please enter the blub's color.");
String color = scan.nextLine();
System.out.println("Please enter the blub's increment amount.");
String incrementS = scan.nextLine();
int incrementI = Integer.parseInt(incrementS);
ThreeWayBulb aBulb = new ThreeWayBulb(color, incrementI);
rooms.get(choiceNumber).addBulb(aBulb);
System.out.println("A " + color + " bulb with and increment of " + incrementI + " was added.");
options();
}
public void clickAllBulbsInRoom() {
displayRooms();
System.out.println("Which room do you want the bulbs clicked?");
String choice = scan.nextLine();
int choiceNumber = Integer.parseInt(choice);
rooms.get(choiceNumber).clickAllBulbs();
System.out.println("The bulbs in " + rooms.get(choiceNumber).getDescription() + " have been clicked.");
options();
}
public void printDescriptionOfBulbs() {
displayRooms();
System.out.println("Please enter a room number.");
String choice = scan.nextLine();
int choiceNumber = Integer.parseInt(choice);
System.out.println(rooms.get(choiceNumber).getDescription() + " with " + rooms.get(choiceNumber).returnSize() + " bulbs: " + "\n" + rooms.get(choiceNumber).toString());
options();
}
}
My instructor wants me to do this without instance variables He said if a method needs the ArrayList that I should make it a parameter and have no instance variables in my TUI. I can't for the life of me figure out how to do that. Also, making it static work fly either. Thanks for any help you can give.
He wants you to declare the ArrayList from a central location (such as the main thread) and then pass it as an argument to the functions that use it. This way if you were to take methods and put them in different classes then it wouldn't break because they're not dependent on this class.
For example if we take your newRoom class:
public void newRoom(List<Room> roomList) {
System.out.println("Please enter a name for your room");
String name = scan.nextLine();
Room aRoom = new Room(name);
roomList.add(aRoom);
System.out.println("You have added the " + name + ".");
options();
}
EDIT: The easiest way to achieve this is to probably move the declaration of rooms to within your run method. Now for each location in the code that reports "unknown variable rooms" you can modify the function to take an ArrayList as a parameter.
Well, eliminating userNumber and userAnswer as members is trivial; their usage is very localized.
For the list, just pass it around after creating it in your main loop.
The scanner is used multiple places; it could also be passed around, I suppose.