Control Flow in Multiple Method Program - java

I'm writing a simple Java program, to familiarise myself with methods, that logs the people a person has met. For instance, if I meet Alison in London, I would log the following (Format: name,gender,when,where):
Alison,F,apr2013,London
The program is built up as follows:
The user is presented with different opportunities:
Log person
Search for all people named [name]
Search for all people met [place]
Get a list of available commands
Quit
Here is the skeleton of my code:
public void chooseCommand() throws FileNotFoundException {
System.out.println("Enter command: ");
text = input.next();
myCommand = Integer.parseInt(text);
while (myCommand !=5) {
if (myCommand == 1) {
writeToFile(); //Log new person
}
// Search for person type
else if (myCommand == 2) {
searchFor(); // Search for person by name
}
// Search for place
else if (myCommand == 3) {
searchFor(); // Search for person by place
}
// help
else if (myCommand == 4) {
showCommands(); // get a list of available commands
}
else if (myCommand == 5) {
exit();
}
// default
else {
System.out.println("Command not found");
}
}
}
This works just fine. However, after I choose one of the five options (log new person, search for name, search for place, help, quit), I would like to go back to the chooseCommand() method, so as to get the same options presented again, instead of having the initially chosen method loop infinitely. That is to say, after I log a new person, I want to be able to get new options, as opposed to having to log new people for all eternity, without killing the program.
// REGISTER
public void writeToFile() {
// Write to file
try {
BufferedWriter output = new BufferedWriter(new FileWriter(file, true));
System.out.println("Enter sighting: ");
for (int i = 0; i < personBlank.length; i++) {
System.out.println(personInfo[i] + ": ");
personEntry = input.next();
personBlank[i] = personEntry;
}
// change to toString() method
observed = personBlank[0] + "," + personBlank[1] + "," + personBlank[2] + "," + personBlank[3];
if (observed.equals(escape)) {
exit();
}
else {
output.write(observed); // log new person
output.newLine();
output.close();
}
back();
}
catch (IOException e){
e.printStackTrace();
}
}
Any help on this is highly appreciated!

public void someMethod() {
while(isRunning) {
chooseCommand();
}
}
Then in chooseCommand() lose the loop, make option 5 set isRunning = false instead of exit(), and use a switch statement for prettyness.
e.g.
public void chooseCommand() throws FileNotFoundException {
System.out.println("Enter command: ");
text = input.next();
myCommand = Integer.parseInt(text);
switch (myCommand) {
case 1:
writeToFile(); //Log new person
break;
case 2:
// Search for place
break;
case 3:
searchFor(); // Search for person by place
break;
// help
case 4:
showCommands(); // get a list of available commands
break;
case 5:
this.isRunning = false;
break;
default:
System.out.println("Command not found");
}
}

in the place of your code where chooseCommand() was called you could use a boolean and check that boolean is true to call chooseCommand()
java pseudocode
------------------
boolean continue=true;
while(continue)
{
System.out.println("Do you want to continue?");
Scanner scan=new Scanner(System.in);
if(scan.nextLine().equals("true"))
chooseCommand();
else
continue = false;
}

Related

Retrieve lines in txt file and append new inputs from the user java

I'm using an arraylist to append inputs and send the arraylist elements to file. However, everytime I exit the program and run it again, the contents in the written in the file becomes empty.
ArrayList<String> memory = new ArrayList<String>();
public void fileHandling() {
try {
FileWriter fWriter = new FileWriter("notes.data");
for (int x = 0; x <= memory.size() - 1; x++) {
fWriter.write(memory.get(x) + '\n');
}
fWriter.close();
} catch (IOException e) {
System.out.println(e);
}
}
public void createNote() {
Scanner insertNote = new Scanner(System.in);
LocalDate todayDate = LocalDate.now();
LocalTime nowTime = LocalTime.now();
String timeFormat = nowTime.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM));
String dateTime = todayDate.toString() + " at " + timeFormat;
while (true) {
System.out.println();
System.out.println("Enter a note");
System.out.print("> ");
String note = insertNote.nextLine();
if (note == null) {
System.out.println("Invalid input! Try again");
break;
} else {
memory.add(note + " /" + dateTime);
fileHandling();
System.out.println("Note is saved!\n");
break;
}
}
I expect the program to save the contents of every input. Then if I exit and run the program again, the contents will go back to the array
Your code currently does the following:
You enter something (X) for the first time:
It gets added to the ArrayList
The ArrayList gets written into the file
Your file now contains: X
You enter something second (Y):
It gets added to the ArrayList (Which now contains: X, Y)
The ArrayList gets written into the file
Your file now contains: X + newline + Y
Your Problem is, that everytime you create a new FileWrite it overwrites your file.
This can be avoided by using the constructor like this:
FileWriter writer = new FileWriter("notes.data", true);
This sets it into the append mode and therefore keeps previous data in the file
You don't need to create a separate Scanner, in method createNote(), in order to get a "note" from the user.
It is usually better to write your code using the interface rather than the specific implementation because then you usually need to change less code if you decide to change the implementation. Hence the type for member variable memory should probably be List rather than ArrayList.
Note that ArrayList may waste memory if the list of "note"s is large. I suggest using LinkedList instead. Alternatively, use an array (rather than a List) and handle expanding the array when adding a "note" as well as reducing the array when removing a "note".
Having an infinite loop, i.e. while (true), which contains a single if-else where both the if block and the else block contain break statements, means that the loop will perform exactly one iteration. May as well remove the while loop – which means also removing the break statements.
Rather than writing the code that generates a timestamp repeatedly, you should adopt the DRY principle and extract that code into a separate method.
The file name should be a constant so as to minimize the amount of code changes you will need to do if you decide to change the file name.
By convention, text files have a filename extension of .txt whereas binary files have the .data extension.
Although you don't need to, I personally prefer to initialize class member variables in the constructor.
The below code is a SSCCE, hence I added a main method. More notes appear after the code.
package Methods;
import java.util.*;
import java.time.format.*;
import java.time.*;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class FileSys {
private static final String FILENAME = "notes.txt";
private static final String CREATE = "C";
private static final String DELETE = "D";
private static final String FIND = "F";
private static final String QUIT = "Q";
private static final String SHOW = "S";
private static final String UPDATE = "U";
Scanner reader;
List<String> memory;
public FileSys() throws IOException {
reader = new Scanner(System.in);
memory = new LinkedList<String>();
loadFile();
}
public void fileHandling() {
Path path = Paths.get(FILENAME);
try (BufferedWriter bw = Files.newBufferedWriter(path,
StandardOpenOption.CREATE,
StandardOpenOption.WRITE);
PrintWriter pw = new PrintWriter(bw)) {
for (String write : memory) {
pw.println(write);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
public void createNote() {
String dateTime = getTimestamp();
System.out.println();
System.out.println("Enter a note");
System.out.print("> ");
String note = reader.nextLine();
memory.add(note + " / " + dateTime);
fileHandling();
System.out.println("Note is saved!");
}
public void searchNote() {
System.out.print("\nEnter note number: ");
try {
int search = reader.nextInt();
reader.nextLine();
System.out.println("\nSearch result:");
int index = memory.indexOf(memory.get(search - 1));
if (index != -1) {
System.out.println("[" + (index + 1) + "]" + " " + memory.get(search - 1));
}
else {
System.out.println("Note number-" + search + " is not found in the collection!");
}
}
catch (IndexOutOfBoundsException e) {
System.out.println("The note number you have entered is invalid!");
}
}
public void updateNote() {
String dateTime = getTimestamp(); // ZonedDateTime.now(ZoneId.systemDefault()).format(dateTimeObj);
System.out.print("\nEnter note number to change: ");
try {
int search = reader.nextInt();
int index = memory.indexOf(memory.get(search - 1));
String updateLine;
if (index != -1) {
System.out.println("\nCurrent note: ");
System.out.println("[" + (index + 1) + "]" + " " + memory.get(search - 1));
System.out.println("\nThe updated note will be: ");
System.out.print("> ");
reader.nextLine();
updateLine = reader.nextLine();
memory.set(index, updateLine + " /" + dateTime);
System.out.print("Note has been updated successfully!\n");
}
else {
System.out.println(search + " is not found in the collection!");
}
}
catch (IndexOutOfBoundsException e) {
System.out.println("The note number you have entered is invalid!");
}
fileHandling();
}
public void deleteNote() {
System.out.print("\nEnter note number to delete: ");
try {
int search = reader.nextInt();
reader.nextLine();
int index = memory.indexOf(memory.get(search - 1));
System.out.println();
if (index != -1) {
System.out.println("[" + (index + 1) + "]" + " " + memory.get(search - 1));
System.out.print("\nDo you want to delete this note? \n[y] or [n]: ");
char delDecision = reader.nextLine().charAt(0);
if (delDecision == 'y' || delDecision == 'Y') {
memory.remove(index);
System.out.println("Note has been deleted successfully!");
System.out.println();
}
else if (delDecision == 'n' || delDecision == 'N') {
System.out.println("Note was not deleted!");
}
else {
System.out.println("Invalid input!");
}
}
else {
System.out.println(search + " is not found in the collection!");
}
}
catch (IndexOutOfBoundsException e) {
System.out.println("The note number you have entered is invalid!");
}
fileHandling();
}
public void displayNote() {
if (memory.size() > 0) {
int counter = 0;
for (String note : memory) {
System.out.printf("%d. %s%n", ++counter, note);
}
}
else {
System.out.println("There are no notes.");
}
}
private String getTimestamp() {
LocalDate todayDate = LocalDate.now();
LocalTime nowTime = LocalTime.now();
String timeFormat = nowTime.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM));
String dateTime = todayDate.toString() + " at " + timeFormat;// ZonedDateTime.now(ZoneId.systemDefault()).format(dateTimeObj);
return dateTime;
}
private void loadFile() throws IOException {
Path path = Paths.get(FILENAME);
if (Files.isRegularFile(path)) {
memory.addAll(Files.readAllLines(path, Charset.defaultCharset()));
}
}
private void showMenu() {
String choice = "";
while (!QUIT.equalsIgnoreCase(choice)) {
System.out.println(CREATE + " - Create note");
System.out.println(DELETE + " - Delete note");
System.out.println(FIND + " - Search notes");
System.out.println(SHOW + " - Show notes");
System.out.println(UPDATE + " - Update note");
System.out.println(QUIT + " - Quit");
System.out.println();
System.out.print("Your choice: ");
choice = reader.nextLine();
if (!choice.isEmpty()) {
choice = choice.substring(0, 1);
choice = choice.toUpperCase();
switch (choice) {
case CREATE -> createNote();
case DELETE -> deleteNote();
case FIND -> searchNote();
case SHOW -> displayNote();
case UPDATE -> updateNote();
case QUIT -> System.out.println("Good bye.");
default -> System.out.println("Invalid: " + choice);
}
}
else {
System.out.println("No selection entered. Retry.");
}
}
}
public static void main(String[] args) {
try {
FileSys fs = new FileSys();
fs.showMenu();
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
Your code does not initially load memory with contents of file notes.txt so I added that in the constructor. Consequently you don't need to append to the file since you simply overwrite it with contents of memory.
The file handling is done using NIO.2 including try-with-resources – which was added in Java 7. There are more NIO.2 examples in the JDK documentation.
Whenever the code throws an unexpected exception, it is nearly always a good idea to print the stack trace.

addPerson (adds to an array) method isnt working, what's wrong?

I'm a student working on a project, and I have a method takes a Person, adds it to the array (Admits[]) and writes the array to file. The method currently does not do this, as the numSoFar value does not increase and the person is not saved to the array. (either that or i made a mistake in my tester class) I put coding of both classes below, and hope someone can point me in the direction of what i am doing wrong. As this is a school project please try not to be too specific actually, just tell me some suggestions as to why my coding may not work. I don't want to pass off someone else's work as my own; i just need a new set of eyes to see what I haven't.
Coding in my Database class
//adds a Person to the Database
public void addPerson(Person admit)
{
for(int i = 0; i < numSoFar; i++)//i = -1 when admit's alpabetical spot in Database has been located
{
if((i == numSoFar-1) || (i == numSoFar))//there is no Person in this index, so this is the end of the database
{
Admits[i] = admit;
numSoFar = numSoFar + 1;
}
else
{
if(Admits[i].getLN().compareTo(admit.getLN()) == -1)//last name comes before last name of Person at index i
{
Person current= Admits[i];
Admits[i] = admit;
while(i <= numSoFar)
{
Person next = Admits[i+1];
Admits[i+1] = current;
current = next;
i++;
}
numSoFar++;
}
else
{
if(Admits[i].getLN().equalsIgnoreCase(admit.getLN()))//admit and Person at index i have the same last name
{
if(Admits[i].getFN().compareTo(admit.getFN()) == -1)
{
Person current= Admits[i];
Admits[i] = admit;
while(i < numSoFar)
{
Person next = Admits[i+1];
Admits[i+1] = current;
current = next;
i++;
}
numSoFar++;
}
else
{
if(Admits[i].getFN().equalsIgnoreCase(admit.getFN())) //admit and Person at index i are the same person
{
Scanner in = new Scanner(System.in);
System.out.println("There is already a person with this name in the database.");
int c = 0;
while(c != 1 || c != 2)
{
System.out.println("If you would like to keep that person, enter '1', and if you would like to replace him/her with the person entered, enter 2.");
if(c == 2)
{
Admits[i] = admit;
}
}
}
}
}
}
}
}
this.writeToFile();
}
This is the coding to add a new person in my tester (i stopped after case 1
Person[] Admits = new Person[5000];
Database dB = new Database(Admits);
dB.fillFromFile();//fills array with info from text file
Scanner in = new Scanner(System.in);
String c = "0";
System.out.println("Hello, and thank you for using the Notre Dame admitted students friend-finder");
while(!c.equals("6")) //Menu for user to traverse, is exited when user enters a 6
{
System.out.println("Please pick the desired action from one of the options below and enter its number.");
System.out.println(" 1: Enter info for a new admitted student and check matches");
System.out.println(" 2: Change info for an admitted student already in the database");
System.out.println(" 3: Delete an admitted student from the database");
System.out.println(" 4: Log in as an admitted student to check matches");
System.out.println(" 5: View contact info for a certain person in the database");
System.out.println(" 6: Exit the program");
c = in.next();
switch(c)
{
case "1": //create new student and check matches
System.out.println("Enter your first name:");
String firstName = in.next();
System.out.println("Enter your last name:");
String lastName = in.next();
System.out.println("Enter your gender:");
String gen = in.next();
Person p = new Person(lastName, firstName, gen);
//String chracteristics
System.out.println("Are you an a. introvert or b. extrovert? (enter a or b):");
String traitIntroExtro = in.next();
while(!(traitIntroExtro.equalsIgnoreCase("a") || traitIntroExtro.equalsIgnoreCase("b")))
{
System.out.println("Invalid choice.Please re-enter your choice:");
traitIntroExtro = in.next();
}
if(traitIntroExtro.equalsIgnoreCase("a"))
{
p.setTraitIntroExtro("Introvert");
}
else
{
p.setTraitIntroExtro("Extrovert");
}
There above coding is basically repeated with different variables, but as there are many i will cut to the end of case 1
//facebook url to contact matches with
System.out.println("Please enter the url of your facebook profile page:");
String url = in.next();
p.setFacebookUrl(url);
dB.addPerson(p);
p.fillMatches(dB);
boolean first = dB.first();
if(first == true)//the database only has one person in it
{
System.out.println("You are currently the only person in the database.");
}
else//the database has atleast one person in it
{
System.out.println("Your top 2 most compatible people currently in the data base are:");
System.out.println(p.getMatches().getHead().getPerson() + ", who can be found at " + p.getMatches().getHead().getPerson().getFacebookUrl());
if(dB.getNumSoFar() == 2)
{
System.out.println("This is the only other person in the database.");
}
else
{
System.out.println(p.getMatches().getHead().getNextNode().getPerson() + ", who can be found at " + p.getMatches().getHead().getNextNode().getPerson().getFacebookUrl());
}
}
break;
Let's take a look at the case you're adding a Person to the end of the array (as you would if there were no entries yet):
for(int i = 0; i < numSoFar; i++)
{
if((i == numSoFar-1) || (i == numSoFar))
{
Admits[i] = admit;
numSoFar = numSoFar + 1;
}
else
{ /* doesn't matter */ }
}
Your for loop is never going to exit: if i = numSoFar-1, then each iteration of the for loop will increment both i and numSoFar by 1 and as such i < numSoFar will always be true.
Also, a comment mentions that i will be -1. I don't see any place where you assign i other than by deceleration and increment, so how could it ever be -1?
Finally, once you've got a working version I'd suggest posting your code over at the Code Review Stack Exchange. There are some non-functional issues out of scope for here on Stack Overflow that I'd point out there (such as the else { if (...) {...} } vs else if (...) {...} mentioned in the comments).

Restart from certain point in java

My problem regards loops and exceptions. If i run this programma it will take me to point 1, but it only let's me put in a string and then just stops. Whereas I want it to continue, just as it initially did. What am I doing wrong?
while (true) {
try {
//From here I want to start everytime. Point 1
System.out.println("Do you whish to deposit or withdraw money or end the transaction?");
Scanner readerBankTransactions = new Scanner(System.in);
String BankTransaction = readerBankTransactions.nextLine();
if (BankTransaction.equalsIgnoreCase(Transactions.ENDTRANSACTION.toString())) {
System.out.println("Thank you for using our service.");
break; //The programma should terminate here
} else {
while (true) {
if (BankTransaction.equalsIgnoreCase(Transactions.DEPOSIT.toString())) {
System.out.println("How much do you whish to deposit?");
Scanner readerDeposit = new Scanner(System.in);
double deposit = readerDeposit.nextDouble();
rekening.deposit(deposit);
double balance = rekening.getBalance();
System.out.println("Your balance is now: " + balance);
readerDeposit.close();
break; //from here I want to start again at point 1.
} else if (BankTransaction.equalsIgnoreCase(Transactions.WITHDRAW.toString())) {
System.out.println("How much do you whish to withdraw?");
Scanner readerWithdraw = new Scanner(System.in);
double withdraw = readerWithdraw.nextDouble();
rekening.withdraw(withdraw);
double balance = rekening.getBalance();
System.out.println("Your balance is now: " + balance);
readerWithdraw.close();
break; //from here I want to start again at point 1.
}
readerBankTransactions.close();
readerbankAccountNumber.close();
}
} continue;
} catch (InputMismatchException | NumberFormatException exception1) {
System.out.println("This is not what you should have put in");
} catch (InsufficientFundsException exception2) {
System.out.println("insufficientfunds!");
} catch (MaximumWithdrawException exception3) {
System.out.println("Maximum withdraw restriction!");
}
}
}
Some suggestions:
Try to avoid the pattern of while (true) followed by continue or break statements. It makes the logic very hard to follow.
You should isolate some of the logic in helper methods. Again, this will make the main logic easier to follow.
I don't understand the purpose of the inner while loop. What are you trying to accomplish here?
With that, here's my suggested rewrite:
do {
try {
String BankTransaction = getInitialSelection();
if (isDepositRequest(BankTransaction)) {
handleDeposit();
} else if (isWithdrawalRequest(BankTransaction)) {
handleWithdrawal();
}
} catch (InputMismatchException | NumberFormatException exception1) {
System.out.println("This is not what you should have put in");
} catch (InsufficientFundsException exception2) {
System.out.println("insufficientfunds!");
} catch (MaximumWithdrawException exception3) {
System.out.println("Maximum withdraw restriction!");
}
} while (!isExitRequest(BankTransaction));
System.out.println("Thank you for using our service.");
This is assuming definitions of handleDeposit(), handleWithdrawal() matching the corresponding code in your original code.
Also, I've assumed the following helper methods:
private boolean isDepositRequest(String bankTransaction) {
return Transactions.DEPOSIT.toString().equalsIgnoreCase(bankTransaction);
}
private boolean isWithdrawalRequest(String bankTransaction) {
return Transactions.WITHDRAW.toString().equalsIgnoreCase(bankTransaction);
}
private boolean isExitRequest(String bankTransaction) {
return Transactions.ENDTRANSACTION.toString().equalsIgnoreCase(bankTransaction);
}
What you are looking for is called a labelled break. Take a look information on labelled breaks at : https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Use a label for your outer while loop for eg point1 : and in the place where you want to restart from point 1 use break point1;

Circular Doubly Linked List Program in Java (Homework Help)

Basically the program is supposed to create a "round table" of executives, with a chairman who cannot be changed. I kinda sorta almost know what I'm doing and I'm about halfway through my methods for inserting and removing executives, but I just tried to test my code to see how it was going and it gets errors as soon as I input the chairpersons information. Also, I'm not really sure at all how I would go about the removeByCorporation method in the ExecutiveList. I'm almost positive that method is nearly all incorrect and I'm just not how to remove a node in a circular doubly linked list like this.
*No need to help me with the printing methods, I simply haven't gotten to them yet.
tl;dr:
1) Why is it crashing right away?
2) I'm pretty sure my removeByCorporation method is totally wrong. If it is, any suggestions or help on how to fix it?
Here are the two classes I'm having trouble with, if you'd like to see the other ones let me know and I'll post them, but they're 99% getters and setters.
FIRST CLASS
public class ExecutiveList {
private ExecutiveNode chair;
ExecutiveNode cursor;
public ExecutiveList() {
}
public ExecutiveList (Executive chairperson) {
chair.setExecutive(chairperson);
chair.left = chair;
chair.right = chair;
}
public void insertLeftOfChair(Executive exec) {
ExecutiveNode newExec = new ExecutiveNode();
newExec.setExecutive(exec);
chair.setLeft(newExec);
}
public boolean insertRightOfExec (Executive exec, String target) {
cursor = chair;
ExecutiveNode newExec = new ExecutiveNode();
do { cursor = cursor.getLeft();
if (cursor.getExecutive().equals(exec)) {
newExec.setExecutive(exec);
cursor.getRight().setLeft(newExec);
newExec.setLeft(cursor);
newExec.setRight(cursor.getRight());
cursor.setRight(newExec);
return true;
}
else {
return false;
}
} while (cursor.getExecutive().getExecutiveName() != target);
}
public boolean insertLeftOfExec (Executive exec, String target) {
cursor = chair;
ExecutiveNode newExec = new ExecutiveNode();
do { cursor = cursor.getLeft();
if (cursor.getExecutive().equals(exec)) {
newExec.setExecutive(exec);
cursor.getLeft().setRight(newExec);
newExec.setRight(cursor);
newExec.setLeft(cursor.getRight());
cursor.setLeft(newExec);
return true;
}
else {
return false;
}
} while (cursor.getExecutive().getExecutiveName() != target);
}
public boolean removeTargetExec(String name) {
if (chair.equals(name)) {
return false;
}
else {
return false;
}
}
public int removeByCorporation(String corporation) {
int removed = 0;
cursor = chair;
do {
if (cursor.getExecutive().getCompanyName().equals(corporation)) {
cursor.setExecutive(null);
cursor.getLeft();
removed = removed + 1;
}
} while (removed > 0);
return removed;
}
public void printByCorporation(String corporation) {
}
public void printAllClockwise() {
}
public void printAllCounterClockwise() {
}
}
SECOND CLASS
import java.util.Scanner;
public class MeetingManager {
public static void main(String[] args) {
// scanner to read the users input
Scanner input = new Scanner(System.in);
// strings to pass information about the chairperson
String chairpersonName;
String chairpersonCompany;
// strings to pass information about executives other
// than the chairperson
String execName;
String execCompany;
String target;
// holds information on whether on not an operation
// was successful and how many executives were removed
// for the remove by corporation command.
boolean success;
int numRemoved = 0;
// prompts the user for information about the chairperson
// and sets it to an executive object name chairperson
System.out.println("Enter the name of the chairperson: ");
chairpersonName = input.next();
if (chairpersonName.length() < 1) {
System.out.println("Please enter a full name");
}
System.out.println("Enter the company of the chairperson: ");
chairpersonCompany = input.next();
if (chairpersonCompany.length() < 1) {
System.out.println("Please enter a full name");
}
Executive chairperson = new Executive(chairpersonName, chairpersonCompany);
// creates a new ExecutiveList object and passes information
// about the chairperson
ExecutiveList list = new ExecutiveList(chairperson);
// for loop to repeatedly print the menu and take instructions
// from the user until they choose to exit.
for (int i = 1; i > 0; i++) {
ShowMenu();
String option = input.next();
// error message for improper input
if (option.length() > 3) {
System.out.println("You can only enter one option");
}
// insert left of chairperson
else if (option.toUpperCase().equals("ILC")) {
System.out.println("Enter the executives name: ");
execName = input.next();
System.out.println("Enter the executives company: ");
execCompany = input.next();
Executive newGuy = new Executive(execName, execCompany);
list.insertLeftOfChair(newGuy);
System.out.println("Insertion successful.");
}
// insert left of executive
else if (option.toUpperCase().equals("ILE")) {
System.out.println("Enter the executives name: ");
execName = input.next();
System.out.println("Enter the executives company: ");
execCompany = input.next();
Executive newGuy = new Executive(execName, execCompany);
System.out.println("Enter the name of the target executive: ");
target = input.next();
success = list.insertLeftOfExec(newGuy, target);
if (success == true) {
System.out.println("Insertion successful.");
}
else {
System.out.println("The executive could not be inserted.");
}
}
// insert right of executive
else if (option.toUpperCase().equals("IRE")) {
System.out.println("Enter the executives name: ");
execName = input.next();
System.out.println("Enter the executives company: ");
execCompany = input.next();
Executive newGuy = new Executive(execName, execCompany);
System.out.println("Enter the name of the target executive: ");
target = input.next();
success = list.insertRightOfExec(newGuy, target);
if (success) {
System.out.println("Insertion successful.");
}
else {
System.out.println("The executive could not be inserted.");
}
}
// remove target executive
else if (option.toUpperCase().equals("RTE")) {
System.out.println("Enter the name of the executive to remove: ");
execName = input.next();
success = list.removeTargetExec(execName);
if (execName.equals(chairpersonCompany))
list.removeTargetExec(execName);
if (success) {
System.out.println(execName + " has been removed from the meeting.");
}
else {
System.out.println(execName + " could not be found.");
}
}
// remove by corporation
else if (option.toUpperCase().equals("RBC")) {
System.out.println("Enter the name of the corporation to remove: ");
execCompany = input.next();
numRemoved = list.removeByCorporation(execCompany);
if (execCompany.equals(chairperson.getCompanyName())) {
System.out.println("Invalid command: cannot remove all employees from the chairperson's corporation");
}
else if (numRemoved < 1) {
System.out.println("That corporation could not be found and no executives were removed.");
}
else {
System.out.println(numRemoved + " executive(s) from " + execCompany + " have been removed from the meeting.");
}
}
// prints by corporation
else if (option.toUpperCase().equals("PBC")) {
System.out.println("Enter the name of a corporation to display: ");
execCompany = input.next();
list.printByCorporation(execCompany);
}
// prints all counter-clockwise
else if (option.toUpperCase().equals("PCC")) {
list.printAllCounterClockwise();
}
// prints all clockwise
else if (option.toUpperCase().equals("PCL")) {
list.printAllClockwise();
}
else if (option.toUpperCase().equals("EXT")) {
System.out.println("Terminating program...");
break;
}
// Error message
else {
System.out.println("Please select a valid option.");
}
}
}
// displays menu and prompts user for input
public static void ShowMenu() {
System.out.println("\nILC) Insert an executive to the left of the chairperson\nILE) Insert an executive to the left of a given executive\nIRE) Insert an executive to the right of a given executive\nRTE) Remove Target Executive");
System.out.println("RBC) Remove By Corporation\nPBC) Print By Corporation\nPCC) Print all in counter-clockwise order\nPCL) Print all in clockwise order\nEXT) Exit the program\n\nSelect a menu option: ");
}
}
Finally, thank you to anyone who gives any sort of suggestion or advice or actual help in any way shape or form. I know people get angry when they see homework questions for some reason because they think the student is asking them to "do their homework for me", but that's not what I'm doing. I'd simply like any advice or tips, I'm not asking you to just fill in the blanks for me and fix everything (not that I'd be opposed to it :P). Thanks.
In removeByCorporation method , you are just setting the executive to null , but considering this to be a doubly linked list , dont you think you need to set the references of the previous and next executive , so that the doubly linked list doesn't break .
The trick is to make sure that, on EVERY operation, you update the item being changed and the two others which reference it (quite handily in a doubly linked list, the two which reference it are also the two it references).
Check each of your methods, and ensure that in each one you are updating 4 fields per change - two in the subject, and one each in the two that are linked from the subject.

pasword masking in console window and recursive function call in java

the following java code is executed in the console window in DR.java IDE.
i have the following two problems please help me friends.
Is it possible to make password masking ?? i tried a lot by googling but none worked for me (should use only console window for excecution).
When i call the "GetLoginDetails();" inside the "ShowAdminMainMenuFun(String EmpName)" method it is showing error ([line: 148] Error: Unhandled exception type java.io.IOException).
i thought of making recursive function but it dint worked can u correct the coding and post it back.
thanking u friends
{
import java.io.*;
import java.awt.*;
import java.io.Console;
import java.util.Scanner;
/*
UserLoginAuthentiction UserLoginAuthentictionObj = new UserLoginAuthentiction();
UserLoginAuthentictionObj.GetLoginDetails();
*/
class UserLoginAuthentiction
{
static String EmployeeID,Password;
public static byte resultRole = 0;
public static void main(String[] args) throws Exception
{
GetLoginDetails(); // it works well here but not works when called againin the following code
}
static void GetLoginDetails() throws IOException
{
Scanner sc = new Scanner(System.in);
byte resultRole = 0;
byte CountForLogin = 0;
System.out.println("Totally 3 attempts ");
do
{
if(CountForLogin<3){
System.out.print("\nEnter User Name:");
EmployeeID = sc.nextLine();
System.out.print("Enter Password :");
Password = sc.nextLine();
resultRole = ValidateUserIDAndPassword(EmployeeID,Password);
// if result is zero then the login is invalid,
// for admin it is one ,
// for quality analyser it is 2
// for project developer it is 3
// for developer it is 4
if(resultRole==0)
{
System.out.println("Username & Password does not match ");
System.out.print("Retry ::");
CountForLogin++;
if(CountForLogin>2)
{System.out.println("ur attempts are over is locked");}
}
else
{
System.out.println("here t should call the appropriate employe function");
GetRoleAndAssignFun(EmployeeID,resultRole);
break;
}
}
}while(resultRole==0);
}
static byte ValidateUserIDAndPassword(String EmployeeID,String Password)
{
byte resultRole = 0;
if((EmployeeID.equals("tcs"))&&(Password.equals("tcs")))
{
resultRole = 1;
}
/*
Code for checking the arraylist and returning the validations
this method should return the roles of the users password
*/
return resultRole;
}
static void GetRoleAndAssignFun(String EmpName ,int EmpRole)
{
// System.out.println(" ");
switch(EmpRole)
{
case 1:
System.out.println(" hi " +EmpName+ " u are logged in as admin ");
ShowAdminMainMenuFun(EmpName);
break;
case 2:
System.out.println(" hi " +EmpName+ " u are logged in as QA ");
// QualityAnalyserMainMenu(EmpName);
break;
case 3:
System.out.println(" hi " +EmpName+ " u are logged in as PM ");
// ProjectMAnagerMainMenu(EmpName);
break;
case 4:
System.out.println(" hi " +EmpName+ " u are logged in as DEVeloper ");
// DeveloperMainMenu(EmpName);
break;
default:
// System.out.println(EmpName +" You dont have any roles asigned ");
break;
}
}
public static void ShowAdminMainMenuFun(String EmpName)
{
Scanner sc = new Scanner(System.in);
int loop_option=0;
do
{
//BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(" Hi "+ EmpName + " you can perform task ussing the menu given below");
System.out.println("press the appropriate option only");
System.out.println("1.Create New Employe Profile ");
System.out.println("2.See Employee's Profile ");
System.out.println("3. LogOut ");
System.out.println("Enter the Option u need:");
int option = sc.nextInt();
switch(option)
{
case 1:
System.out.println("1.Creating New Employe Profile");
//CreateNewEmployeeProfile();
break;
case 2:
System.out.println("2.See Employee's Profile ");
// ViewEmployeeProfile();
break;
case 3:
System.out.println("3. LogOut");
System.out.println("Do u want to continue logging out ?? If yes Press 1 ..");
boolean ConformLogout = false;
ConformLogout = sc.nextBoolean();
if(ConformLogout)
{
**GetLoginDetails();** //**** error is here */ how can i call this function please help me
}
else
{
}
// LogOut();
break;
default :
System.out.println(" You .. ");
}
System.out.println("Do u want to continue to main menu ?? Press 1 to continue..");
loop_option = sc.nextInt();
}while(loop_option==1);
}
}
}
Regarding your first question,
Is it possible to make password
masking?
You can use java.io.Console class to hide the password on console window.

Categories

Resources