I have an assignment to create an ArrayList of employees, to provide a menu to add, find, and delete employee records. I successfully managed to implement all the functions on my own, but there is a small problem. When I use the find or delete option, the correct record is found or deleted properly but the code goes through the array list of elements and prints out employee not found till the correct record is found, this is unnecessary as it should only print the found record. I have limited experience with coding and I am writing my own code from scratch, please help me with this.
enter image description here
I'VE ATTACHED MY CODE AND THE OUTPUT!
else if (choice.equals("4")) {
System.out.println("Enter Name: ");
String fName = myScanner.nextLine();
System.out.println("Enter Job Name: ");
String fJob = myScanner.nextLine();
for (int i = 0; i < myEList.size(); i++) {
if (myEList.get(i).getName().equals(fName) && myEList.get(i).getJob().equals(fJob)) {
System.out.println("Employee found!");
System.out.println(myEList.get(i).toString());
} else {
System.out.print("Employee not found!");
}
}
} else if (choice.equals("5")) {
System.out.println("Enter Name: ");
String dName = myScanner.nextLine();
System.out.println("Enter Job Name: ");
String dJob = myScanner.nextLine();
for (int i = 0; i < myEList.size(); i++) {
if (myEList.get(i).getName().equals(dName) && myEList.get(i).getJob().equals(dJob)) {
System.out.println("Employee record removed succesfully!");
myEList.remove(i);
} else {
System.out.print("Employee not found!");
}
}
}
This is the Output
Enter Option: 4
Enter Name: arjun
Enter Job Name: tester
Searching...
Employee not found!
Employee not found!
Employee found!
Name: arjun Job Name: tester Weekly Pay: 1200.0
else
{
System.out.print("Employee not found!");
}
This has to be AFTER the for loops are over. You need a found flag. If after the loop is false then print the message
Create a variable to track if employee not found before the loops
In the if statements sent it to false if found.
At the end of the loop check if it is true. Then print the message "Employee not found"
See the sample below
boolean notFound = true;
for(int i=0;i<myEList.size();i++)
{
if(myEList.get(i).getName().equals(fName)&&myEList.get(i).getJob().equals(fJob))
{
System.out.println("Employee found!");
System.out.println(myEList.get(i).toString());
notFound = false;
break;
}
}
if(notFound)
System.out.print("Employee not found!");
Remove this block of code
else
{
System.out.print("Employee not found!");
}
It should work fine after that.
EDIT
This is off topic but when you ask question next time remember to post image of output rather than typing it or posting a link.
And also avoid writing about your coding experience. Just be straight to the point. It just increases the size of question unnecessarily. :)
Related
Please help me to figure out how I can get a count of the result when I do a search against a specific folder?
Also how can I ask the user if they want to perform another search?
// Importing utilities
import java.io.File;
import java.util.*;
public class FileListing
{
public static void main (String[] args)
{
// Creating a Scanner
Scanner keyboard = new Scanner(System.in);
// Specifying search location
File file = new File("D:/Music");
String[] content = file.list();
// Searching for a match
System.out.println("Enter the first few characters of the folder/file to do a lookup");
String userInput = keyboard.nextLine();
// Adding text to say what the user searched for
System.out.println("Below you will find the list of folders/files with a partial match to (" + userInput + ").");
System.out.println();
// Posting the contents
for(String folders : content)
{
if(folders.toUpperCase().startsWith(userInput.toUpperCase()))
{
System.out.println("Name: " + folders);
}
}
}
}
If you want to count your matches you can do the following
int i=0;
// Posting the contents
for(String folders : content)
{
if(folders.toUpperCase().startsWith(userInput.toUpperCase()))
{
System.out.println("Name: " + folders);
i++;
}
}
System.out.println("Total number of results: " + i);`
As for asking the user, consider using a do-while loop in the following format
do{
// your code
// ask user and read his answer on a string called userChoice
}while (userChoice.equals('y'))
Experiment with our suggestions and you will find the answer easily enough!
I would add a variable
int count = 0;
right before the for loop, and just increment it if it's a match.
This should get you started. I am incrementing the variable count each time a match is found. I am also looping forever so it keeps asking the user for more input.
// Importing utilities
import java.io.File;
import java.util.*;
public class FileListing
{
public static void main (String[] args)
{
// Creating a Scanner
Scanner keyboard = new Scanner(System.in);
// Specifying search location
File file = new File("D:/Music");
String[] content = file.list();
while(true){
// Searching for a match
System.out.println("Enter the first few characters of the folder/file to do a lookup");
String userInput = keyboard.nextLine();
// Adding text to say what the user searched for
System.out.println("Below you will find the list of folders/files with a partial match to (" + userInput + ").");
System.out.println();
// Posting the contents
int count=0;
for(String folders : content)
{
if(folders.toUpperCase().startsWith(userInput.toUpperCase()))
{
System.out.println("Name: " + folders);
count++;
}
}
}
}
}
Use a while loop and prompt the user to enter a phrase (such as 'exit') if they want to stop. After reading the user input, check the phrase and call a break if it matches the exit phrase.
Use a variable as Robert suggested to count the total number of files found.
I keep getting a syntax error on my last else statement in a string of if, else if , else , and I can't figure out why nor can I find anywhere that tells me what's really confusing is I have done this type of if else statement setup before and never had this problem. I have tried using 2 coding programs (JCreator and Eclipse) but they both give me an error Eclipse gives me a syntax error on the word else and JCreator on the entire statement saying it has no if statement to pair with it, but I have done one like this and didn't need an if statement as is was the final one.
import java.util.Scanner;
public class Hotel
{
public static void main(String[] args)
{
String answer = "";
Scanner keyboard = new Scanner(System.in);
GuestInterface go = new GuestInterface();
PassswordField hotel = new PassswordField();
System.out.println("do you wish do acces the guest interface or the hotel staff interface? ");
System.out.println("Hint: hotel staff -or- guest");
answer = keyboard.nextLine();
if(answer.equalsIgnoreCase("hotel Staff"))
{
System.out.println("Enter username");
answer = keyboard.nextLine();
hotel.readPassword("Enter Passsword \n ");
System.out.print("\n" + "incorect Password");
System.out.println("System will now shut down");
System.exit(0);
}
else
if(answer.equalsIgnoreCase("Guest"))
{
go.run();
}
else //error throws on this statment
{
System.out.println("uncompatible responce");
System.out.println("System ato shut down activated");
System.exit(0);
}
}
}
You wrote a ; at the end of this line:
if(answer.equalsIgnoreCase("Guest"));
So that is a seperate if-statement. Right after that, you start with this:
{
go.run();
}
else //error throws on this statment
{
// (...)
}
Which makes no sense to the compiler, because it didn't start with an if-statement.
Remove the ; to solve the error.
I am building a parser that recognizes simple commands such as "DOWN.", "UP." and "REP 3.". It must be able to parse the commands rather freely. It should be legal to write
"DOWN % asdf asdf asdf
."
Where % represents a comment and the fullstop signifying end-of-command. This fullstop can be on the next line.
This is all good and well so far, however I'm struggling with the Rep part (represents Repeat.)
I should be able to issue a command as follows:
DOWN .DOWN. REP 3 " DOWN. DOWN.
DOWN . % hello this is a comment
REP 2 " DOWN. ""
This should give me 17 DOWNS. The semantics is as follows for repeat: REP x " commands " where x is the amount of times it shall repeat the commands listed inside the quotation marks. Note that REP can be nested inside of REP. The following code is for handling the DOWN command. The incoming text is read from System.in or a text file.
public void repeat(String workingString) {
if (workingString.matches(tokens)) {
if (workingString.matches("REP")) {
repada();
} else
if (workingString.matches("(DOWN).*")) {
String job = workingString.substring(4);
job = job.trim();
if (job.equals("")) {
String temp= sc.next();
temp= temp.trim();
// Word after DOWN.
if (temp.matches("\\.")) {
leo.down()
// If word after DOWN is a comment %
} else if (temp.matches("%.*")) {
boolean t = comment();
} else {
throw SyntaxError();
}
} else if (job.matches("\\..*")) {
workingString += job;
System.out.println("Confirm DOWN with .");
}
} else if (workingString.matches("\\.")) {
instructions += workingString;
System.out.println("Fullstop");
} else if (workingString.matches("%.*")) {
comment();
} else {
// work = sc.next();
work = work.trim().toUpperCase();
System.out.println(work);
}
} else {
System.out.println("No such token: " + workingString);
}
}
I got a working start on the repeat function:
public String repada(){
String times = sc.next();
times.trim();
if (times.matches("%.*")) {
comment();
times = sc.next();
}
String quote = sc.next();
quote.trim();
if(quote.matches("%.*")){
comment();
quote = sc.next();
}
String repeater = "";
System.out.println("REP " + times + " "+quote);}
However I'm thinking my whole system of doing things might need a rework. Any advice on how I could more easily solve this issue would be greatly appreciated!
I'm making a credential like program and it is very WIP. I placed a while loop with a Boolean condition to make the program run again whenever a person finishes creating a credential, but when it loops to the beginning of the program it prints the first part twice! like this:
run:
|-----------------------------------------------|
|Welcome to the Credential Managing System 2013!|
|-----------------------------------------------|
Would you like to create or manage a credential?
Choose: Manage | Create
Waiting for input: Create
Credential name: df
Credential ID: 34243
Credential Password: numbers or words?
Waiting for input: numbers
Credential Password: 13651
|-------------------|
|Credential created!|
|-------------------|
Would you like to create or manage a credential?
Choose: Manage | Create
Waiting for input:
from there it stops reading the input again.
here is the entire code!
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Carlinhos
*/
import java.util.Scanner;
public class Criação {
public static void main(String[] args){
Scanner e = new Scanner(System.in);
System.out.println(" |-----------------------------------------------|");
System.out.println(" |Welcome to the Credential Managing System 2013!|");
System.out.println(" |-----------------------------------------------|");
System.out.println("");
Boolean autoRun = true;
while(autoRun){
System.out.println(" Would you like to create or manage a credential?");
System.out.println("");
System.out.println(" Choose: Manage | Create");
System.out.println("");
System.out.print(" Waiting for input: ");
String op1 = e.nextLine();
autoRun = false;
if(op1.equals("Create")){
System.out.println();
System.out.print("Credential name: ");
String credName = e.nextLine();
System.out.print("Credential ID: ");
int credID = e.nextInt();
System.out.println("Credential Password: numbers or words?");
System.out.print("Waiting for input: ");
e.nextLine();
String credPassCheck = e.nextLine();
if(credPassCheck.equals("numbers")){
System.out.print("Credential Password: ");
double credPassNum = e.nextDouble();
}
else if(credPassCheck.equals("words")){
System.out.print("Credential Password: ");
String credPassLet = e.nextLine();
}
System.out.println("");
System.out.println(" |-------------------|");
System.out.println(" |Credential created!|");
System.out.println(" |-------------------|");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
autoRun = true;
}
}
}
}
Change this line:
while(autoRun = true)
to this:
while(autoRun)
= is not the equality comparison operator, it's the assignment operator. So, when you check that condition autoRun is the assigned the value true even though you set it to false earlier. You can use == instead but since autoRun is a boolean variable, you can simply use this variable without comparing it to anything else.
UPDATE:
After OP's comments that the program has started exiting after printing the prompt for the second time, I looked into the code a little more and found these lines:
if(credPassCheck.equals("numbers")){
System.out.print("Credential Password: ");
double credPassNum = e.nextDouble();
}
This is basically consuming less input than is necessary and thus the next prompt for "Waiting for Input" gets a single newline character as its input. The fix should be obvious now:
if(credPassCheck.equals("numbers")){
System.out.print("Credential Password: ");
double credPassNum = e.nextDouble();
e.nextLine(); //Add this Line
}
This always gives me a headache. I am trying to read and save multiple-word Strings for the fields "name" and "malady" within a while loop. Here is my code:
while(OR1.isFull() == false || OR2.isFull() == false)
{
// prompt for next request
System.out.println("Enter patient info:");
// read patient info
System.out.print("Name: ");
String name = input.nextLine();
input.nextLine();
System.out.print("Malady: ");
String malady = input.nextLine();
input.nextLine();
System.out.print("Priority: ");
int priority = input.nextInt();
// store patient info
Patient patient = new Patient(name, malady, priority);
OR1.add(patient);
} // end while
System.out.println("List of patients scheduled for Operating Room 1");
while(OR1.isEmpty() == false)
{
// pop and print root
System.out.print(OR1.remove());
}
And here is what my console input and output looks like:
Enter patient info:
Name: John Doe
Malady: Broken hip
Priority: 6
List of patients scheduled for Operating Room 1
Patient: Malady: Broken hip Priority: 6
// end console output.
Notice that it did not record the value I entered for "Name," and also that it prompted for an extra line of input after obtaining "Malady" (required me to press enter again to get it to ask for the next input, "Priority").
I have read the documentation at http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html. I have tried different combinations of next() and nextLine(). I just don't get it.
Problem solved by changing the code to the following:
// read patient info
System.out.print("Name: ");
input.nextLine();
String name = input.nextLine();
System.out.print("Malady: ");
String malady = input.nextLine();
System.out.print("Priority: ");
int priority = input.nextInt();
Though I am still confused about how this silly scanner works =/
I believe it should work for just:
// read patient info
System.out.println("Name: ");
String name = input.nextLine();
System.out.println("Malady: ");
String malady = input.nextLine();
System.out.println("Priority: ");
int priority = input.nextInt();
Perhaps the problem is in the Patient constructor or something?
Problem solved by changing the code to the following:
// read patient info
System.out.print("Name: ");
input.nextLine();
String name = input.nextLine();
System.out.print("Malady: ");
String malady = input.nextLine();
System.out.print("Priority: ");
int priority = input.nextInt();