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);
}
}
Related
I still cannot figure out what is wrong with my code.
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("[1] Register");
System.out.println("[2] LogIn as Client");
System.out.println("[3] LogIn as Admin");
System.out.println("[4] Exit");
System.out.print("Enter your choice here: ");
int choice = input.nextInt();
switch(choice){
case 1:
System.out.println("[Register Your Account]");
System.out.print("-----Enter your name: ");
String name = input.next();
System.out.print("-----Enter your desired 4-digit pin: ");
int pin = input.nextInt();
System.out.print("-----Enter your first deposit: ");
int balance = input.nextInt();
account client = new account(name,pin,balance);
client.setName(name);
client.setPin(pin);
client.setBalance(balance);
addToArrayList(client);
case 2:
System.out.println("[LogIn Your Account]");
System.out.println("----Enter Your Pin: ");
int logPin = input.nextInt();
logIn(logPin);
break;
case 3:
System.out.println("Case 3");
break;
case 4:
System.out.println("Case 4");
break;
}
}
static void addToArrayList(account client){
userList.add(client);
displayRegister(userList);
}
static void displayRegister(ArrayList<account> users){
for (account client : users){
System.out.println("(Here's what we received)");
System.out.println(client.getName());
System.out.println(client.getPin());
System.out.println(client.getBalance());
}
}
Why does my login give an output of both TRUE AND FALSE when I entered a correct pin after register, and if I entered a wrong pin the program ends?
static void logIn (int logPin){
if(!userList.isEmpty()){
int i = 0;
boolean isNotExist = false;
for(var acc: userList){
int pinCode = acc.getPin();
if(logPin==acc.getPin()){
System.out.println("(LogIn Successfully!)");
isNotExist=true;
mainMenu();
}
else{
i++;
}
}
if(isNotExist){
System.out.println("(Account does not exist...)");
}
}else{
System.out.println("(No data...)");
}
}
With this method that you have written:
static void logIn (int logPin){...}
You receive nothing when you call it. As it is of void return type. However,
static boolean logIn (int logPin){...}
Will give you a return of true or false as it is of boolean. Then call it like so:
boolean success = logIn(logPin);
EDIT for additional information
With a boolean return type on that
method, you will need to return the value isNotExist instead of just declaring and assing a value to it in the method:
{
boolean isNotExist = false;
...
// Code to assign value
...
return isNotExist;
}
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;
}
}
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");
}
so the code I currently have can return a reference to the object in the array but wont display the data inside of it. The first bit of code is the main file which the user inputs the data, but the object reference only returns the last object the user entered, what i need is for the array to be searched and if it is found with the item display the data that is stored with that object.
the first file.
import java.util.Scanner;
import java.util.*;
import java.util.ArrayList;
public class Inv
{
public static void main(String args[])
{
Scanner console = new Scanner(System.in);
String str;
char c;
int n=0;
//Product product = new Product();
System.out.println(" INVENTORY MANAGEMENT SYSTEM");
System.out.println("===============================================");
System.out.println("1. ADD PRODUCT DATA");
System.out.println("2. VIEW PRODUCT DATA");
System.out.println("3. VIEW REPRLENISHMENT STRATEGY");
System.out.println("===============================================");
System.out.println("4. EXIT PROGRAM");
while(n!=4)
{
System.out.print("\n Please enter option 1-4 to continue...: ");
n = Integer.parseInt(System.console().readLine());
if (n>4||n<1)
{
System.out.print("Invalid input, please try again...");
continue;
}
if (n==1)
{
str="y";
while(str.equals("y")||str.equals("Y"))
{
Inv.addItem();
System.out.print("Would you like to enter another product ? (Y or N) : ");
str = console.next();
}
continue;
}
if (n==2)
{
str="y";
while(str.equals("y")||str.equals("Y"))
{
Inv.prodData();
System.out.println("\n***************************************************\n");
System.out.print("Stay viewing this page? (Y or N) ");
str = console.next();
}
continue;
}
else
if (n==3)
{
System.out.print("View Replenishment Strategy.");
continue;
}
}
System.out.print("\nThank you for using this inventory management software.\n");
System.out.print("Developed by Xavier Edwards");
System.out.println("\n***************************************************\n");
}
public static Product product;
public static Store store;
public static void addItem ()
{
Scanner console = new Scanner(System.in);
product = new Product();
store = new Store();
String desc, id, str="";
double price = 0, sUpPrice = 0, unitCost = 0, inventoryCost = 0;
int stock = 0, demand = 0;
//if (product == null) //If product 1 is empty
//{
System.out.print("Please enter product description between 3 to 10 characters...: ");
desc = console.next();
desc = desc.toLowerCase();
product.setName(desc);
if ((desc.length() < 3 || desc.length() > 10))
{
System.out.println("\nThis Input is incorrect. Please make description between 3 to 10 characters.\n");
System.out.println("Try again with different input. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.print("Please enter price in $ : ");
price = console.nextDouble();
product.setPrice(price);
if (price < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.print("Please enter set up price. $ : ");
sUpPrice = console.nextDouble();
product.setsUpPrice(sUpPrice);
if (sUpPrice < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.print("Please enter unit- cost. $ : ");
unitCost = console.nextDouble();
product.setunitCost(unitCost);
if (unitCost < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.print("Please enter the inventory cost. $ : ");
inventoryCost = console.nextDouble();
product.setinvCost(inventoryCost);
if (inventoryCost < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.print("Please enter the amount in stock : ");
stock = console.nextInt();
product.setstock(stock);
if (stock < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.print("Please enter the demand of the product : ");
demand = console.nextInt();
product.setdRate(demand);
if (demand < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.println("\n*****************************************\n");
System.out.print(desc +" Product was added successfully ");
System.out.println("\n*****************************************\n");
store.add(product);
//}
}
public static void prodData()
{
Scanner console = new Scanner(System.in);
String pOption, str;
System.out.print("\nEnter product description to view the data...\n");
pOption = console.next();
if (product == null)
{
System.out.println("\nThere is no information on this product.\n");
System.out.println("\nWould you like to try again? (Y or N) \n");
str = console.next();
Inv.prodData();
}
System.out.println("The information for the product is..... ");
System.out.println("\n*****************************************\n");
System.out.println(store.ProductList.get(0));
if (product.equals(store.ProductList.get(0)))
{
System.out.println("Product description : "+product.getName());
System.out.println("Price : $ "+product.getPrice());
System.out.println("Set-up Price : $ "+product.getsUpPrice());
System.out.println("Unit Cost : $ "+product.getunitCost());
System.out.println("Inventory Cost : $ "+product.getinvCost());
System.out.println("Amount of Stock : "+product.getstock());
System.out.println("Amount of Stock : "+product.getdRate());
}*/
}
}
The second file which is where the array list is made and objects stored.
import java.util.*;
import java.util.ArrayList;
public class Store{
public ArrayList <Product> ProductList = new ArrayList<Product> ();
public Store()
{
//ArrayList = "";
}
public void add(Product product)
{
ProductList.add(product);
}
public Product getProduct(String prodName) {
for (int i = 0; i < ProductList.size(); i++) {
if (ProductList.get(i).getName().equals(prodName)) {
return ProductList.get(i);
}
}
return null;
}
}
Code for the storing of particular user entries
public class Product
{
public String name;
public double price, sUpPrice, unitCost, invCost;
public int stock, demand;
public Product()
{
name = "";
price = 0;
sUpPrice = 0;
unitCost = 0;
invCost = 0;
stock = 0;
demand = 0;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setPrice(double price) {
this.price = price;
}
public double getPrice() {
return this.price;
}
public void setsUpPrice(double sUpPrice) {
this.sUpPrice = sUpPrice;
}
public double getsUpPrice() {
return this.sUpPrice;
}
public void setunitCost(double unitCost) {
this.unitCost = unitCost;
}
public double getunitCost() {
return this.unitCost;
}
public void setinvCost(double invCost) {
this.invCost = invCost;
}
public double getinvCost() {
return this.invCost;
}
public void setstock(int stock) {
this.stock = stock;
}
public int getstock() {
return this.stock;
}
public void setdRate(int demand) {
this.demand = demand;
}
public int getdRate() {
return this.demand;
}
}
so thats the code within another file called product.java
If I understand correctly, you want the user to type in a product name, and then display all the product's data.
You should probably use your getProduct method.
product = store.getProduct(pOption);
if (product != null){
System.out.println("Product description : "+product.getName());
System.out.println("Price : $ "+product.getPrice());
System.out.println("Set-up Price : $ "+product.getsUpPrice());
System.out.println("Unit Cost : $ "+product.getunitCost());
System.out.println("Inventory Cost : $ "+product.getinvCost());
System.out.println("Amount of Stock : "+product.getstock());
System.out.println("Amount of Stock : "+product.getdRate());
}else{
System.out.println("\nThere is no information on this product.\n");
System.out.println("\nWould you like to try again? (Y or N) \n");
str = console.next();
Inv.prodData();
}
public class Inv {
//read data from any way you prefer and call the methods on store class
//since the class methods and the productlist are marked as static
//every class on your project is accessing and changing the same productlist
Store.add("your product object");
Store.getProduct("your name");
}
class Store{
public static ArrayList <product> ProductList = new ArrayList<product> ();
public static void add(product product){
ProductList.add(product);
}
public static product getProduct(String prodName) {
for (int i = 0; i < ProductList.size(); i++) {
if (ProductList.get(i).getName().equals(prodName)) {
return ProductList.get(i);
}
}
return null;
}
//implement new static methods to remove products from productlist
public static removeProduct(String name){
//code to remove product
}
public static removeAll(){
//code to clear the productlist
}
}
you need to follow this approach in your code explanation is provided inside the comments
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.