I'm super confuse because how is it possible to get ArrayList from another method, and print it to another method? So my problem here is, my code is about student registration system where it have 2 methods which are admin and student, so from admin method, we can add arrays we want and when we print that out in admin method, it works fine. But when I try to print that out in student method, seems to be not working. Here's the code:
import java.util.*;
public class myStudent {
boolean logins = false;
int myId;
String addCourse="No Record";
String NewCourse;
String removeCourse="No Record";
int modifyCourse;
String password = null;
ArrayList test = new ArrayList();
public static void main(String[] args){
myStudent obj0 = new myStudent();
obj0.login();
}
void login(){
myStudent obj1 = new myStudent();
Scanner myScanner = new Scanner(System.in);
System.out.println(" **Student Registration**");
System.out.println("\t--LOGIN--");
System.out.println("\n1)Login as student \n2)Login as admin \n3)Exit");
System.out.print(">");
int optionMenu = myScanner.nextInt();
if(optionMenu == 1){
obj1.showMenuStudent();
}
else if(optionMenu == 2){
obj1.showMenuAdmin();
}
else if(optionMenu == 3){
System.out.println("THANK YOU!");
System.exit(0);
}
}
void showMenuAdmin(){
if (!logins) {
//String myPass;
Scanner myScanner = new Scanner(System.in);
System.out.println("\n--LOGIN--");
try{
System.out.print("Admin ID : ");
myId = myScanner.nextInt();
}
catch(Exception e){
System.out.println("INVALID ID!");
System.exit(0);
}
System.out.print("Admin Password : ");
password = myScanner.next();
logins = true;
}
char option;
Scanner myScanner = new Scanner(System.in);
System.out.println("\n--WELCOME--");
System.out.println("A. Create Course");
System.out.println("B. Drop Course");
System.out.println("C. Modify Course");
System.out.println("D. Display Course");
System.out.println("E. Logout");
do
{
System.out.print("Enter An Option > ");
option = myScanner.next().charAt(0);
System.out.print("\n");
switch(option){
case 'A':
System.out.print("Create Course(Maximum is 6) :");
addCourse = myScanner.next();
test.add(addCourse);
System.out.println("\nCourse Added Successfully!");
display();
break;
case 'B':
Object[] myArray = test.toArray();
System.out.println("Current Courses List: ");
int k=1;
for(int i=0; i < myArray.length; i++){
System.out.println(k + ". " + myArray[i]);
k++;
}
System.out.println("Enter course name you want to remove :");
System.out.println("Enter 'back' to cancel");
System.out.print(">");
removeCourse = myScanner.next();
if(removeCourse!="back"){
test.remove(removeCourse);
System.out.println("\nSucceed");
display();
}else
display();
break;
case 'C':
Object[] myArray2 = test.toArray();
System.out.println("Current Courses List: ");
int m=1;
for(int i=0; i < myArray2.length; i++){
System.out.println(m + ". " + myArray2[i]);
m++;
}
System.out.println("Select course you want to modify :");
System.out.print(">");
modifyCourse = myScanner.nextInt();
try{
if(modifyCourse==1){
System.out.print("Change to :");
NewCourse=myScanner.next();
test.set(0, NewCourse);
System.out.println("Succeed!");
display();
}
else if(modifyCourse==2){
System.out.print("Change to :");
NewCourse=myScanner.next();
test.set(1, NewCourse);
System.out.println("Succeed!");
display();
}else if(modifyCourse==3){
System.out.print("Change to :");
NewCourse=myScanner.next();
test.set(2, NewCourse);
System.out.println("Succeed!");
display();
}else if(modifyCourse==4){
System.out.print("Change to :");
NewCourse=myScanner.next();
test.set(3, NewCourse);
System.out.println("Succeed!");
display();
}else if(modifyCourse==5){
System.out.print("Change to :");
NewCourse=myScanner.next();
test.set(4, NewCourse);
System.out.println("Succeed!");
display();
}else if(modifyCourse==6){
System.out.print("Change to :");
NewCourse=myScanner.next();
test.set(5, NewCourse);
System.out.println("Succeed!");
display();
}
else{
System.out.print("Invalid!");
display();
}
}
catch(Exception e){
System.out.print("Invalid, Course not available!");
display();
}
break;
case 'D':
Object[] myArray3 = test.toArray();
System.out.println("Courses List: ");
int j=1;
for(int i=0; i < myArray3.length; i++){
System.out.println(j + ". " + myArray3[i]);
j++;
}
display();
break;
}
}while(option != 'E');
System.out.println("Logged Out Successfully.Thank You!");
login();
}
void showMenuStudent(){
if (!logins) {
Scanner myScanner = new Scanner(System.in);
System.out.println("\n--LOGIN--");
try{
System.out.print("Student ID : ");
myId = myScanner.nextInt();
}
catch(Exception e){
System.out.println("INVALID ID!");
System.exit(0);
}
System.out.print("Student Password(Default is IC Number) : ");
password = myScanner.next();
logins = true;
}
Object[] myArray4 = test.toArray();
int n=1;
for (Object myArray41 : myArray4) {
System.out.println(n + ". " + myArray41);
n++;
}
}
void display(){
showMenuAdmin();
}
}
I really hope someone would understand my problem and trying to fix it.. Please :( and thank you
Here's the output from beginning to the result:
OUTPUT:
Student Registration
--LOGIN--
1)Login as student
2)Login as admin
3)Exit
2
--LOGIN--
Admin ID : 123
Admin Password : 321
--WELCOME--
A. Create Course
B. Drop Course
C. Modify Course
D. Display Course
E. Logout
Enter An Option > A
Create Course(Maximum is 6) :CS123
Course Added Successfully!
--WELCOME--
A. Create Course
B. Drop Course
C. Modify Course
D. Display Course
E. Logout
Enter An Option > E
Logged Out Successfully.Thank You!
Student Registration
--LOGIN--
1)Login as student
2)Login as admin
3)Exit
1
--LOGIN--
Student ID : 123
Student Password(Default is IC Number) : 321
[]Enter An Option >
//at this point, idk why it run like that,I just want to print out what the admin had entered in the array,but its like the student method just rerun the admin method again even i never call it, and it also shown that the array is empty. Which part is my mistake? or am i missing something here? :(
So i ran your code and found the problem. You're creating a new myStudent object at every login(), If you:
Remove the line myStudent obj1 = new myStudent();
And replace obj1.showMenuStudent(); with showMenuStudent()
And replace obj1.showMenuAdmin(); with showMenuAdmin();
You will have fixed this issue and will get the output you want. Here is the output I got, hopefully its in sync with what you want to obtain:
**Student Registration**
--LOGIN--
1)Login as student
2)Login as admin
3)Exit
>2
--LOGIN--
Admin ID : 1
Admin Password : 1
--WELCOME--
A. Create Course
B. Drop Course
C. Modify Course
D. Display Course
E. Logout
Enter An Option > A
Create Course(Maximum is 6) :CS123
Course Added Successfully!
--WELCOME--
A. Create Course
B. Drop Course
C. Modify Course
D. Display Course
E. Logout
Enter An Option > E
Logged Out Successfully.Thank You!
**Student Registration**
--LOGIN--
1)Login as student
2)Login as admin
3)Exit
>1
1. CS123
Enter An Option >
Related
I'm building a university management system where admin can log in, add student, department, 2ndly there is a faculty panel and lastly, there is a student panel where they can set course. But I've been facing some problems after adding a new student through the admin panel. The problem is if want to exit from the admin panel the whole program close. Is there any solution that if I exit from admin panel I should get back to main menu where i can enter in any panel again. there is one more problem if i tried to remove a student from registered it shows not found. Can anyone help me through this problem?
Here is my code MainActivity.java
import java.util.Scanner;
import mainpanel.*;
import interfacepart.*;
//import transactionpart.*;
public class MainActivity{
public static void main(String args[]){
boolean flag = true;
Student[] student1 = new Student[2000];
Scanner sc = new Scanner(System.in);
Admin a = new Admin("Admin", "1234");
System.out.println("**********Welcome to University Management*******");
//do {
System.out.println("**********Please Choose the task you want to perform****");
System.out.println("1.Adming Login");
System.out.println("2.Faculty Login");
System.out.println("3.Student Login");
int choose = sc.nextInt();
sc.nextLine();
if(choose == 1){
Scanner ac = new Scanner(System.in);
System.out.println("**********Welcome to Admin panel*******");
System.out.println("Please enter the userName: ");
String user = sc.nextLine();
System.out.println("Please enter the password: ");
String password = sc.nextLine();
if("Admin".equals(user) && "1234".equals(password)){
do{
System.out.println("Login successful");
System.out.println ( "**** 1. add students and department *****");
System.out.println ( "**** 2. remove students *****");
System.out.println ( "**** 3. student Information *****");
//System.out.println ( "**** n 5, print student *****");
System.out.println ( "**** 4, exit the system *****");
int sel = sc.nextInt();
switch (sel){
case 1:
System.out.println("Enter the number of student you want to add: ");
int num = sc.nextInt();
sc.nextLine();
for (int i = 0; i<num; i++) {
if (student1[i] == null) {
System.out.println("Enter the deptname: ");
String depntName = sc.nextLine();
System.out.println("Enter the deptId: ");
String depntId = sc.nextLine();
System.out.println("Enter the totalCredit: ");
int totalCredit = sc.nextInt();
sc.nextLine();
Department cs = new Department(depntName, depntId, totalCredit);
Scanner mc = new Scanner(System.in);
System.out.println("Enter the StudentName: ");
String StudentName = mc.nextLine();
System.out.println("Enter the StudentId: ");
String StudentId = mc.nextLine();
System.out.println("Enter the StudentAge: ");
String StudentAge = mc.nextLine();
System.out.println("Enter the email: ");
String email = mc.nextLine();
System.out.println("Enter the bloodGroup: ");
String bloodGroup = mc.nextLine();
System.out.println("Enter the phoneNumber: ");
String phoneNumber = mc.nextLine();
System.out.println("Enter the Address: ");
String Address = mc.nextLine();
mc.nextLine();
Student s1 = new Student(StudentName,StudentId,StudentAge,email,bloodGroup,phoneNumber,Address);
student1[i] = s1;
a.addNewRegister(student1[i]);
a.addNewDepartment(cs);
student1[i].SetAdmin(a);
student1[i].SetDeparment(cs);
cs.addNewRegister(student1[i]);
//break;
}
else{
System.out.println ( "Number of students in full");
break;
}
}
break;
case 2:
boolean isStudentRegistered = false;
System.out.println("Please Enter the Id you want to remove: ");
Scanner newCheck = new Scanner(System.in);
String stdId = newCheck.nextLine();
for(Student total : student1){
if(total != null){
if(total.getId() == stdId){
System.out.println("student found");
isStudentRegistered = true;
total = null;
System.out.println("Student removed");
}
}
}if(!isStudentRegistered){
System.out.println("No student found");
}
break;
case 3:
for(int i=0; i<1; i++){
a.showRegisteredInfo();
break;
}
break;
case 4:
System.exit(0);
//flag = false;
//break;
//continue;
break;
default:
break;
}
}while (true);
} else {
//flag = true;
System.out.println ( "Login failed please re-enter:");
}
}
else if(choose == 3){
Scanner std = new Scanner(System.in);
System.out.println ( "Welcome to Student Panel*******");
System.out.println("Please enter the StudentId: ");
String userId = std.nextLine();
System.out.println("Please enter the password: ");
String password = std.nextLine();
do{
for(Student total : student1){
if(total != null){
if(total.getId() == userId){
System.out.println("*********Welcome to university Portal***");
//isStudentRegistered = true;
total.showInfo();
}else{
System.out.println("You are not registered yet");
}
}
}
}while(true);
}
else{
System.out.println ( "Login failed please re-enter:");
}
/*} while (true);
}*/
}
}
Admin.java
package mainpanel;
public class Admin{
protected String userName;
protected String passWord;
Student[] addNewStudent;
Department[] department;
Courses[] courses;
int totalRegisterCount;
int totalDepartmentCount;
int totalCourseCount;
public Admin(){
addNewStudent = new Student[200];
department = new Department[10];
courses = new Courses[200];
totalRegisterCount = 0;
totalDepartmentCount = 0;
totalCourseCount = 0;
}
public Admin(String userName, String passWord){
this.userName = userName;
this.passWord = passWord;
addNewStudent = new Student[200];
department = new Department[10];
courses = new Courses[200];
totalRegisterCount = 0;
totalDepartmentCount = 0;
totalCourseCount = 0;
}
public void SetUserName(String userName){
this.userName = userName;
}
public String GetUserName(){
return userName;
}
public void SetpassWord(String passWord){
this.userName = userName;
}
public String GetPassword(){
return passWord;
}
public void addNewRegister(Student NewStudent){
addNewStudent[totalRegisterCount++] = NewStudent;
}
//public void removeNewStudent(Student removeNewStudent){
//}
public void addNewDepartment(Department dept){
department[totalDepartmentCount++] = dept;
}
public void addNewCourse(Courses crs){
courses[totalCourseCount++] = crs;
}
public void showDepartmentInfo(){
for(int i=0; i<totalDepartmentCount; i++){
department[i].showInfo();
}
}
public void showRegisteredInfo(){
for(int i=0; i<totalRegisterCount; i++){
addNewStudent[i].showInfo();
//addNewStudent[i].AllCourseInfo();
}
}
public void searchStudentInfo(String stdId){
//department[num].showInfo();
boolean isStudentRegistered = false;
for(Student total : addNewStudent){
if(total != null){
if(total.getId() == stdId){
System.out.println("student found");
isStudentRegistered = true;
total.showInfo();
}
}
}
if(!isStudentRegistered){
System.out.println("No student found");
}
}
/*
public void removeStudentInfo(String stdId){
//department[num].showInfo();
boolean isStudentRegistered = false;
for(Student total : addNewStudent){
if(total != null){
if(total.getId() == stdId){
System.out.println("student found");
isStudentRegistered = true;
total = null;
System.out.println("Student removed");
}
}
}
if(!isStudentRegistered){
System.out.println("No student found");
}
}
*/
}
//courses[num].showInfo();
/*public void showCourseInfo(){
for(int i=0; i<totalCourseCount; i++){
courses[i].showInfo();
}
}
*/
Approach 1 - Not recommended
You can either have a loop surrounding the core functionality of your application and break out of any internal loops to go back to the beginning of the core loop.
Approach 2 - Recommended
You could refrain from using a core loop and refactor your code such that each menu interaction is a separate function.
Each function would present the user with a specific menu and depending on the user's input another function would be called for the next menu. Generally speaking, you would not require any loops to keep the application running.
This would reduce the complexity and confusion of your code and make it much easier to expand the application with new features without needing to concern yourself with where to place code within the loop.
I recommend reading up on SOLID design principles to get an idea of how best to structure code. Here is an example article. This answer and example code is not meant to be a full representation of SOLID design and I would recommend that you strongly consider using interfaces and separate classes for each distinct part of the system and not having all the code in the MainActivity class.
An example of a function-based approach would be as follows.
I mainly focussed on the Main Menu and Admin Menu. The principle can be applied across the entire application.
Scanner sc = new Scanner(System.in);
private void displayMainMenu() {
System.out.println("**********Please Choose the task you want to perform****");
System.out.println("1.Admin Login");
System.out.println("2.Faculty Login");
System.out.println("3.Student Login");
int input = sc.nextInt();
sc.nextLine();
switch (input) {
case 1:
displayAdminLoginMenu();
break;
case 2:
displayFacultyLoginMenu();
break;
case 3:
displayStudentLoginMenu();
break;
default:
// Display the main menu again if no option was successful.
// Can also handle possible errors here with feedback to the user.
displayMainMenu();
break;
}
}
private void displayAdminLoginMenu() {
// Perform login operation here
// After successful login display admin options menu
displayAdminOptionsMenu();
}
private void displayFacultyLoginMenu() {
}
private void displayStudentLoginMenu() {
}
private void displayAdminOptionsMenu() {
System.out.println("**** 1. add students and department *****");
System.out.println("**** 2. remove students *****");
System.out.println("**** 3. student Information *****");
System.out.println("**** 4, return to main menu *****");
System.out.println("**** 5, exit the system *****");
int input = sc.nextInt();
switch (input) {
case 1:
// Call function for option 1.
break;
case 2:
// Call function for option 2.
break;
case 3:
// Call function for option 3.
break;
case 4:
displayMainMenu();
break;
case 5:
exitApplication();
break;
default:
// Display the admin menu again if no option was successful.
// Can also handle possible errors here with feedback to the user.
displayAdminOptionsMenu();
break;
}
}
private void exitApplication() {
System.exit(0);
}
These are not necessarily the only options available, but they are what I could think of at the moment.
Im Trying to put something in case 1 in the switch that when i add the new pin code it will display "*" rather than the actual number
import java.util.Scanner;
public class Main {
public Main() {
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int userChoice;
boolean quit = false;
System.out.println("Welcome to GNBanking");
System.out.println("Please Create Your Account");
String name;
String add;
int contact;
double initialdep;
int pin;
int random = (int )(Math.random() * 999999 + 1);
Scanner reg = new Scanner (System.in);
System.out.println("Please Fill out the information below");
System.out.println("Enter Your Name: ");
name = reg.nextLine();
System.out.println("Enter Your Address: ");
add = reg.nextLine();
System.out.println("Enter Your Contact Number: ");
contact = reg.nextInt();
System.out.println("Enter Your Initial Deposit");
initialdep = reg.nextInt();
System.out.println("Enter Your Pin: ");
pin = reg.nextInt();
System.out.println("Congratulations You Are Now A Member Of GNBanking Please Confirm Your Account");
System.out.println("Name of Member: " +name);
System.out.println("Address: "+ add);
System.out.println("Contact Number:" +contact);
System.out.println("Initial Deposit: "+initialdep);
System.out.println("Pin " + pin);
System.out.println("Is the Information Accurate? Y/N ");
String choice =reg.next();
if(choice.equalsIgnoreCase("Y")){
System.out.println("Excellent!!");
System.out.println("Your Account Number is: "+ random );
System.out.println("Name of Member: " +name);
System.out.println("Address: "+ add);
System.out.println("Contact Number:" +contact);
System.out.println("Initial Deposit: "+initialdep);
System.out.println("Pin: " + pin);
}else if(choice.equalsIgnoreCase("N")){
System.out.println("Do You Want to try again? Y/N");
String secchoi = reg.next();
if(secchoi.equalsIgnoreCase("Y")){
main (null);
}else if (secchoi.equalsIgnoreCase("N")){
System.out.println("Have A Nice Day!");
}
}
do {
System.out.println("[1] Change Pincode");
System.out.println("[2] View Balance");
System.out.println("[3] Deposit Money");
System.out.println("[4] Withdraw ");
System.out.println("[5] Close Account");
userChoice = in.nextInt();
switch (userChoice) {
case 1:
// Here Im trying to create a change pin that wont show the int but rather the character "*" when I type
break;
case 2:
// View Balance
break;
case 3:
// Deposit
break;
case 4:
// Withdraw
break;
case 5:
quit = true;
break;
default:
System.out.println("Wrong choice.");
break;
}
System.out.println();
} while (!quit);
System.out.println("Have A Nice Day");
}
}
*/
Use below code in the programm, If you want to display it after taking input.
int value=1234567780; //Your pincode
String data=String.valueOf(value).replaceAll("[0-9]", "*"); //replacing and storing it into new String variable
System.out.println(data);
This one you can use while taking inputs from the user in password format.
System.out.println("Please Enter your pincode: ");
char[] pinCode= cosole.readPassword();
String data = new String(pinCode);
NOTE: The cosole.readPassword() may not work in IDE , You have to run the programm through console.
Can someone help me with my code please. Im a begginer and this thing called java really confusses me :) my problem is that i have to remove user/s, but my ouput is allways just user name not found... thanks in advance
public void removeUser() {
java.util.Scanner input = new java.util.Scanner(System.in);
int checks = 1;
if (checks == 1) {
for (int i = 0; i < userList().size(); i++) {
System.out.println("Input user name for the account you want to be deleted");
userName = input.next();
if (userList.equals(userName)) {
userList.get(i);
userList.remove(userName);
System.out.println("You succesfully removed user acount");
System.out.println("If you want to exit press 0, if you want to continue press 1");
checks = input.nextInt();
} else {
System.out.println("User name not found");
}
}
}
if (checks == 0) {
administrator();
}
}
why do you think that this would work?
if (userList.equals(userName))
??
Maybe just try removing it
boolean removed = userList.remove(userName);
if (removed) {
System.out.println("You succesfully removed user acount");
}
No looping required
see
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#remove(java.lang.Object)
So your code could look like
java.util.Scanner input = new java.util.Scanner(System.in);
int checks = 1;
while (checks == 1) {
System.out.println("Input user name for the account you want to be deleted");
userName = input.next();
if (userList.remove(userName)) {
System.out.println("You succesfully removed user acount");
}
else {
System.out.println("User name not found");
}
System.out.println("If you want to exit press 0, if you want to continue press 1");
checks = input.nextInt();
}
First thing that here you do with your code is change theif (checks == 1) to while loop while(checks == 1), because if can be executed only one time.
Second thing if (userList.equals(userName)) is never true, thus the if clause won't be executed. You first get the user name from the list like this String name userList.get(i); then now you can check if it is equal like this
if(name.equals(userName)) //or userList.contains(userName){
// userList.remove(userName);
// OR
// userList.remove(i);
}
Eidt:
You can change your code as below, maybe work for you
List<String> userList = new ArrayList<>();
userList.add("AA");
userList.add("BB");
userList.add("CC");
java.util.Scanner input = new java.util.Scanner(System.in);
int checks = 1;
while (checks == 1) {
for (int i = 0; i < userList.size(); i++) {
System.out.println("Input user name for the account you want to be deleted");
String userName = input.next();
if(userList.remove(userName)) {
System.out.println("You scornfully removed user account");
} else {
System.out.println("User name not found");
}
System.out.println("If you want to exit press 0, if you want to continue press 1");
checks = input.nextInt();
}
}
if (checks == 0) {
administrator();
}
public static void main(String[] args) {
List<String> customerNames = new ArrayList<String>();
customerNames.add("john");
customerNames.add("lily");
customerNames.add("druid");
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Please enter 1 ");
if(input.nextInt() != 1){
System.out.println("break checks ... ...");
return;
}
for(int i = 0; i < customerNames.size(); i++) {
System.out.println("Input user name for the account you want to be deleted");
if (customerNames.get(i).equals(input.next())) {
customerNames.remove(i);
System.out.println("You succesfully removed user acount");
System.out.println("If you want to exit press 0 ... ...\n");
if(input.nextInt() == 0){ //break
break;
}
} else {
System.out.println("User name not found... ...\n");
}
}
}
public static void main(String[] args) {
List<String> customerNames = new ArrayList<String>();
customerNames.add("john");
customerNames.add("lily");
customerNames.add("druid");
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Please enter 1: ");
if(input.nextInt() != 1){
System.out.println("break checks ... ...");
return;
}
System.out.println("========= start =========");
System.out.println("Please enter 1: ");
while(input.nextInt() != 0){
System.out.println("Input user name for the account you want to be deleted... ...");
System.out.println("enter name:");
String _name = input.next();
for(int i = 0; i < customerNames.size(); i++) {
if(_name.equals(customerNames.get(i))){
customerNames.remove(_name);
System.out.println("You succesfully removed user acount");
break;
}
}
System.out.println("If you want to exit press 0 ... ...\n");
System.out.println("input numeric:");
}
System.out.println("========= end =========");
//break
if(customerNames.size() == 0){return;}
for(String name : customerNames){//print names
System.out.println(name);
}
}
In my code below I am not sure what order to put it in to work properly.
I first want it to print out for the user to select an option which it does, then if they select 1 it asks them their name and verifies it with the loop etc.
When I enter a name it starts to just loop the question enter your name and I don't know how to fix it.
Do I need to add more statements to my program, if I do then can I still use if statements for the user to select an option?
import java.util.Scanner;
public class username {
public static void main(String[] args) {
{
int UseLift;
int AuditReport;
int ExitLift;
int a;
UseLift = 1;
AuditReport = 2;
ExitLift = 3;
}
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");
Scanner d = new Scanner(System.in);
int a = d.nextInt();
Scanner kb = new Scanner(System.in);
// array containing usernames
String[] name = {"barry", "matty", "olly", "joey"}; // elements in array
if (a == 1) {
System.out.println(" Enter your name ");
}
String name1 = kb.nextLine();
boolean b = true;
int j = 0;// counter will start at 0
outerloop:
while (j < 3) {
System.out.println("Enter your name");
}
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
System.out.println("you are verified you may use the lift, calling lift ");
}
break;// to stop loop checking names
}
System.out.println("Username Invalid");
j++;
if (a == 2) {
System.out.println("");
}
if (a == 3) {
System.out.println(" Please Exit Lift ");
}
}
}
here you go:
public static void main(String... args) {
String[] verifiedNames = { "barry", "matty", "olly", "joey" };
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
scanner.nextLine(); // get '\n' symbol from previous input
int nameAttemptsLeft = 3;
while (nameAttemptsLeft-- > 0) {
System.out.println(" Enter your name ");
String name = scanner.nextLine();
if (Arrays.asList(verifiedNames).contains(name)) {
System.out.println("dear " + name + " you are verified " +
"you may use the lift, calling lift ");
break; // break out of loop
}
}
if (nameAttemptsLeft < 0) {
System.out.println("Username Invalid");
}
break;
case 2:
System.out.println("option 2");
break;
case 3:
System.out.println(" Please Exit Lift ");
break;
}
scanner.close();
}
Your while loop below:
while (j < 3) {
System.out.println("Enter your name");
}
will loop forever since j is not incrementing (j++). I believe you've mis-matched your curly braces at some point.
I've set up a "menu" that prints to console. Takes user input, calls according method, and then should return to the menu for further instruction. How should I structure my code so that it outputs the "menu" after it's done doing whatever it's doing?
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
EntryNode n = new EntryNode();
AddressList addressBook = new AddressList();
String menu = " ";
System.out.println("******************************************************************");
System.out.println("Welcome to the Jackie 2000 Address Book");
System.out.println("What do you want to do? ");
System.out.println("[p] View All Entries in Address Book [a] Add New Entry");
System.out.println("[d] Remove An Entry [s] Search for Entry");
System.out.println("[i] Import Address Book [x] Export Address Book");
System.out.println("[z] Exit");
System.out.println();
System.out.println("Please enter your choice: ");
menu = keyboard.next().toLowerCase();
if (menu.equals("p")) {
try {
addressBook.printList();
}
catch (Exception e){
}
}
else if (menu.equals("a")) {
System.out.println("Enter in the first name ");
String firstName = keyboard.next().toUpperCase();
System.out.println("Enter in the last name ");
String lastName = keyboard.next().toUpperCase();
System.out.println("Enter in the phone number");
String phoneNum = keyboard.next().toUpperCase();
System.out.println("Enter in the email");
String email = keyboard.next().toUpperCase();
addressBook.addEntry(firstName,lastName,phoneNum,email);
}
else if (menu.equals("d")) {
EntryNode temp = head;
for (int i = 0; i <addressBook.length(); i++) {
System.out.println(i + " Name: " + temp.getFirstName() + " " + temp.getLastName() + " "
+ temp.getPhoneNum() + " " + temp.getEmail());
temp = temp.getNext();
}
System.out.println(" ");
System.out.println("Please enter the index of the entry you wish to delete ");
int index = keyboard.nextInt();
addressBook.removeEntry(index);
}
else if (menu.equals("s")) {
System.out.println("Do you want to search by email or name? ");
String decision = keyboard.next();
if (decision.equals("email")) {
System.out.println("What email address are you looking for? ");
String email = keyboard.next();
addressBook.searchEmail(email);
}
else if (decision.equals("name")) {
System.out.println("What name are you looking for?");
String name = keyboard.next();
addressBook.searchEntry(name);
}
else System.out.println("Invalid entry. Type in 'email' or 'name'");
}
else if (menu.equals("i")) {
addressBook.importBook();
}
else if (menu.equals("x")) {
addressBook.exportBook();
}
else if (menu.equals("e")) {
System.exit(0);
}
else {
System.out.println("Invalid Entry");
}
}
}
You should definitely take a look at java's switch statement: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
You could have the entire switch-case statement inside a while loop with a boolean for when it should exit. For example:
while(!exit){
switch(input){
case "a": do something;break;
case "d":...
...
case "e": exit = true;
}
}
If you want the same menu to be displayed again after the user entered a choice and the program executed what he had to do, just put the whole process in a while or do...while loop and only exit it when the user choose the exit option.
Put a menu printlns into a separate static method. Call it after each addressBook method call, just before you close else if, except for an exit case.