I have a switch statement that allows you to search for a user in a database. The search is basically just searching for a matching character whether it is numeric or alphabetic. It doesn't seem to be working though, any ideas?
Here is main.java
package hartman;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Printer.printWelcome();
Scanner keyboard = new Scanner(System.in);
ArrayList<Person> personList = new ArrayList<>();
boolean keepRunning = true;
while (keepRunning) {
Printer.printMenu();
Printer.printPrompt("Please enter your operation: ");
String userSelection = keyboard.nextLine();
switch (userSelection) {
case "1":
Database.addPerson(personList);
break;
case "2":
Database.printDatabase(personList);
break;
case "3":
Printer.printSearchPersonTitle();
String searchFor = keyboard.nextLine();
Database.findPerson(searchFor);
break;
case "4":
keepRunning = false;
break;
default:
break;
}
}
Printer.printGoodBye();
keyboard.close();
}
}
Here is Database.java
package hartman;
import java.util.ArrayList;
import java.util.Scanner;
public class Database {
static Scanner keyboard = new Scanner(System.in);
private static ArrayList<Person> personList = new ArrayList<Person>();
public Database() {
}
public static void addPerson(ArrayList<Person> personList) {
Printer.printAddPersonTitle();
Printer.printPrompt(" Enter first name: ");
String addFirstName = keyboard.nextLine();
Printer.printPrompt(" Enter last Name: ");
String addLastName = keyboard.nextLine();
Printer.printPrompt(" Enter social Security Number: ");
String addSocial = keyboard.nextLine();
Printer.printPrompt(" Enter year of birth: ");
int addYearBorn = Integer.parseInt(keyboard.nextLine());
System.out.printf("\n%s, %s saved!\n", addFirstName, addLastName);
Person person = new Person();
person.setFirstName(addFirstName);
person.setLastName(addLastName);
person.setSocialSecurityNumber(addSocial);
person.setYearBorn(addYearBorn);
personList.add(person);
}
public static void printDatabase(ArrayList<Person> personList) {
System.out
.printf("\nLast Name First Name Social Security Number Age\n");
System.out
.printf("=================== =================== ====================== ===\n");
for (Person p : personList) {
System.out.printf("%-20s%-21s%-24s%s\n", p.getLastName(),
p.getLastName(), p.getSocialSecurityNumber(), p.getAge());
}
}
public static ArrayList<Person> findPerson(String searchFor) {
ArrayList<Person> matches = new ArrayList<>();
for (Person p : personList) {
boolean isAMatch = false;
if (p.getFirstName().equalsIgnoreCase(searchFor)) {
isAMatch = true;
}
if (p.getLastName().equalsIgnoreCase(searchFor)) {
isAMatch = true;
}
if (p.getSocialSecurityNumber().contains(searchFor)) {
isAMatch = true;
;
} else if (String.format("%d", p.getAge()).equals(searchFor))
if (isAMatch) {
}
matches.add(p);
Printer.printPersonList(matches);
}
return matches;
}
}
and here is where printer is doing.
public static void printPersonList(ArrayList<Person> personListToPrint) {
System.out
.printf("\nLast Name First Name Social Security Number Age\n");
System.out
.printf("=================== =================== ====================== ===\n");
for (Person p : personListToPrint) {
System.out.printf("%-20s%-21s%-24s%s\n", p.getLastName(),
p.getLastName(), p.getSocialSecurityNumber(), p.getAge());
}
You should not be passing personList around everywhere like you are doing Likely, you are not iterating over the copy of personList you think you are doing. Since personList is empty, printPersonList is never called. That is why you get no output.
There is really no reason to have personList in Main.java at all. As the code is written now, the copy of personList you would work with is:
private static ArrayList<Person> personList = new ArrayList<Person>();
in Database.java.
I might suggest a little further refactoring, but I think that should be enough to get you some working code.
In the method findPerson , the variable isAMatch seems did not take effort.
No matter what the value of isAMatch is, the list matches would always add the object p.
So , it may look like this:
if (isAMatch) {
matches.add(p);
}
Also , the code Printer.printPersonList(matches); should be out of the for loop.
By the way , what's the point??
else if (String.format("%d", p.getAge()).equals(searchFor))
if (isAMatch) {
}
Related
I need to remove an element from an ArrayList, based on the user input. So what I have is an ArrayList where a user can register dogs. Then if the user wants to remove a dog, he/she should be able to do it by using the command "remove dog" followed by the name of the dog.
I have tried using an iterator, but when using it only the else statement is used and "Nothing has happened" is printed out on the screen.
import java.util.Iterator;
import java.util.Scanner;
import java.util.ArrayList;
public class DogRegister {
ArrayList<Dog> dogs = new ArrayList<>();
private Scanner keyboard = new Scanner(System.in);
public static void initialize() {
System.out.println("Welcome to this dog application");
}
private boolean handleCommand(String command) {
switch (command) {
case "One":
return true;
case "register new dog":
registerNewDog();
break;
case "increase age":
increaseAge();
break;
case "list dogs":
listDogs();
break;
case "remove dog":
removeDog();
break;
default:
System.out.println("Error: Unknown command");
}
return false;
}
private void registerNewDog() {
System.out.print("What is the dog's name? ");
String dogNameQuestion = keyboard.nextLine().toLowerCase().trim();
System.out.print("Which breed does it belong to? ");
String dogBreedQuestion = keyboard.nextLine().toLowerCase().trim();
System.out.print("How old is the dog? ");
int dogAgeQuestion = keyboard.nextInt();
System.out.print("What is its weight? ");
int dogWeightQuestion = keyboard.nextInt();
keyboard.nextLine();
Dog d = new Dog(dogNameQuestion, dogBreedQuestion, dogAgeQuestion,
dogWeightQuestion);
dogs.add(d);
System.out.println(dogs.get(0).toString());
}
private void removeDog() {
System.out.print("Enter the name of the dog ");
String removeDogList = keyboard.nextLine();
for (Iterator<Dog> dogsIterator = dogs.iterator();
dogsIterator.hasNext();) {
if (removeDogList.equals(dogsIterator)) {
System.out.println("The dog has been removed ");
break;
} else {
System.out.println("Nothing has happened ");
break;
}
}
}
public void closeDown() {
System.out.println("Goodbye!");
}
public void run() {
initialize();
runCommandLoop();
}
public static void main(String[] args) {
new DogRegister().run();
}
}
You compare a String will an Iterator as said by JB Nizet :
if (removeDogList.equals(dogsIterator)) {
It will never return true.
Besides even invoking next() on the iterator will not solve the problem as a String cannot be equal to a Dog object either.
Instead of, compare String with String when you use equals() and invoke Iterator.remove() to effectively remove the current iterated element.
That should be fine :
private void removeDog() {
System.out.print("Enter the name of the dog ");
String removeDogList = keyboard.nextLine();
for (Iterator<Dog> dogsIterator = dogs.iterator();dogsIterator.hasNext();) {
Dog dog = dogsIterator.next();
if (removeDogList.equals(dog.getName())) {
dogsIterator.remove();
System.out.println("The dog has been removed");
return;
}
}
System.out.println("Nothing has been removed");
}
An Iterator<Dog> can't possibly be equal to a String: they don't even have the same type.
Only a String can be equal to a String.
You want to get the next value of the iterator, which is a Dog. Then you want to compare the name of the dog with the String input.
And then you want to remove the dog, using the iterator's remove() method. Read the javadoc of Iterator.
I had to do a bunch of methods in my code and then have it all go to the main method. Everything is working correctly, but when I enter in a string to the "getOrder" method it won't check to see if the string is true and then finish the rest of the code. Can someone please help me? I tried doing an if and else statement, but they didn't work either. thank you
import java.util.Random;
import java.util.Scanner;
public class App {
public static void main(String[] args) {
//Get banner message
welcomeUser();
//Get product array
String[] products = getProducts();
//Get prouct order from user aka the LA
getOrder(products);
//Does the product exist?
if(getOrder(products) == true) //yup it exists
{
//Get the *price*
getPrice();
double fPrice = getPrice();
//Get the TAX
getTax(fPrice);
double tax = getTax(fPrice);
//Get the total sale
getTotal(fPrice, tax);
//output the total sale
double transaction = getTotal(fPrice, tax);
printTotal(transaction);
}
else
System.out.print("Not found");
}
public static void welcomeUser()
{
System.out.println("Hello! Welcome to the Fruit Market!");
}
public static String[] getProducts()
{
String [] productList = new String [5];
productList[0] = "Banana";
productList[1] = "Pineapple";
productList[2] = "Grapes";
productList[3] = "Strawberries";
productList[4] = "Kiwi";
//System.out.println(Arrays.toString(productList));
return productList;
}
public static boolean getOrder(String[] stuff)
{
Scanner scan = new Scanner(System.in);
String usersFruitChoice;
System.out.println("Please enter a fruit you would like to buy.");
usersFruitChoice = scan.nextLine();
boolean valid = false;
while(!valid)
{
for (String stuff1 : stuff) {
valid = stuff1.equalsIgnoreCase(usersFruitChoice);
}
}
return valid;
}
}
}
The culprit seems to be your for loop:
for (String stuff1 : stuff) {
valid = stuff1.equalsIgnoreCase(usersFruitChoice);
}
This section of your code will iterate through your entire products array and will overwrite the value of valid if a later value in the array does not match whatever is in usersFruitChoice. Try entering Kiwi for usersFruitChoice and see if the code enters the while loop to verify that this error is occurring.
You can fix this by using a break statement if you found a valid entry that matches usersFruitChoice, as that will exit the loop early and not always cause the last value in the array to be checked against usersFruitChoice:
for (String stuff1 : stuff) {
if (stuff1.equalsIgnoreCase(usersFruitChoice)) {
valid = true;
break;
};
}
Consider removing this line - it does nothing:
//Get prouct order from user aka the LA
getOrder(products);
This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
I wrote a program that has an arraylist of users so it should either create a new user and store the user's name in an arraylist or choose an existing user from an arraylist. The problem is, when I run the code I can choose an option but when I want to create a new user I cannot type anything. Why does that happen and how can I fix this?
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
public class Main {
private ArrayList<String> users;
public static void main(String[] args) {
Main m = new Main();
m.menu();
}
public void createNewUser(String name) {
users.add(name);
}
public boolean search(String username) {
if (users.contains(username))
return true;
else
return false;
}
public void displayUsers() {
Iterator<String> itr = users.iterator();
while (itr.hasNext()) {
String name = itr.next();
System.out.println(name);
}
}
public void menu() {
users = new ArrayList<String>();
int choice = 0;
String name;
Scanner input = new Scanner(System.in);
System.out.println("Choose an option:");
System.out.println("1- Create new user");
System.out.println("2- Select current user");
choice = input.nextInt();
if (choice == 1) {
System.out.println("Enter your name: ");
name = input.nextLine();
createNewUser(name);
displayUsers();
} else {
do {
displayUsers();
System.out.println("Enter your username: ");
name = input.nextLine();
if (search(name)) {
System.out.println("User found");
break;
}
else
System.out.println("This username does not exist.");
} while (!search(name));
}
}
}
System.out.println("Choose an option:");
System.out.println("1- Create new user");
System.out.println("2- Select current user");
choice = input.nextInt();
input.nextLine();
Try adding input.nextLine(); after your choice.
I have to use a switch statement to allow a user to select what they want to do, if they select "1", it will allow them to add a person to a database. In the switch statement for "1", i am getting a syntax error stating that "p" cannot be resolved to a variable. However, I have tried everything i can possibly think of to get this to work and it will not. any idea?
package hartman;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Printer.printWelcome();
Scanner keyboard = new Scanner(System.in);
ArrayList<Person> personList = new ArrayList<>();
boolean keepRunning = true;
while (keepRunning) {
Printer.printMenu();
Printer.printPrompt("Please enter your operation: ");
String userSelection = keyboard.nextLine();
switch (userSelection) {
case "1":
Database.addPerson(p);
break;
case "2":
Database.printDatabase(personList);
break;
case "3":
Printer.printSearchPersonTitle();
String searchFor = keyboard.nextLine();
Database.findPerson(searchFor);
break;
case "4":
keepRunning = false;
break;
default:
break;
}
}
Printer.printGoodBye();
keyboard.close();
}
}
This is Database.java -
package hartman;
import java.util.ArrayList;
import java.util.Scanner;
public class Database {
static Scanner keyboard = new Scanner(System.in);
private static ArrayList<Person> personList;
public Database() {
}
public static void addPerson(Person personList2) {
Printer.printAddPersonTitle();
Printer.printPrompt(" Enter first name: ");
String addFirstName = keyboard.nextLine();
Printer.printPrompt(" Enter last Name: ");
String addLastName = keyboard.nextLine();
Printer.printPrompt(" Enter social Security Number: ");
String addSocial = keyboard.nextLine();
Printer.printPrompt(" Enter year of birth: ");
int addYearBorn = Integer.parseInt(keyboard.nextLine());
System.out.printf("\n%s, %s saved!\n", addFirstName, addLastName);
Person person = new Person();
person.setFirstName(addFirstName);
person.setLastName(addLastName);
person.setSocialSecurityNumber(addSocial);
person.setYearBorn(addYearBorn);
personList.add(personList2);
}
public static void printDatabase(ArrayList<Person> personList) {
System.out
.printf("\nLast Name First Name Social Security Number Age\n");
System.out
.printf("=================== =================== ====================== ===\n");
for (Person p : personList) {
System.out.printf("%-20s%-21s%-24s%s\n", p.getLastName(),
p.getLastName(), p.getSocialSecurityNumber(), p.getAge());
}
}
public static ArrayList<Person> findPerson(String searchFor) {
ArrayList<Person> matches = new ArrayList<>();
for (Person p : personList) {
boolean isAMatch = false;
if (p.getFirstName().equalsIgnoreCase(searchFor)) {
isAMatch = true;
}
if (p.getLastName().equalsIgnoreCase(searchFor)) {
isAMatch = true;
}
if (p.getSocialSecurityNumber().contains(searchFor)) {
isAMatch = true;
;
}
if (String.format("%d", p.getAge()).equals(searchFor))
if (isAMatch) {
}
matches.add(p);
}
return matches;
}
}
The compiler cant resolve p to a variable, because you declare p nowhere.
Better solution:
I think its much nicer to do the person creation process directly in the database, so do the following:
Change Database.java to this:
public static void addPerson() {
Printer.printAddPersonTitle();
Printer.printPrompt(" Enter first name: ");
String addFirstName = keyboard.nextLine();
Printer.printPrompt(" Enter last Name: ");
String addLastName = keyboard.nextLine();
Printer.printPrompt(" Enter social Security Number: ");
String addSocial = keyboard.nextLine();
Printer.printPrompt(" Enter year of birth: ");
int addYearBorn = Integer.parseInt(keyboard.nextLine());
System.out.printf("\n%s, %s saved!\n", addFirstName, addLastName);
Person person = new Person();
person.setFirstName(addFirstName);
person.setLastName(addLastName);
person.setSocialSecurityNumber(addSocial);
person.setYearBorn(addYearBorn);
personList.add(person);
}
Change first code to:
Database.addPerson();
I'm creating a very simple phone directory for a homework assignment but I'm stuck. I've tried looking through similar threads, and while those have been useful they haven't answered my question. I have a class name Directory which has an ArrayList that is compiled from another class called Person. The Person class gathers the information about the contact: First & Last Name, Phone Number and Email addresses of all the contacts. I'm trying to read the ArrayList size from another class: _MainMenu so that if I want to add another contact, the method addNewPerson can be dynamic. I'll include the code for the MainMenu and Directory. Basically I'm trying to avoid having to create a new object for the class Person by hand because I don't know how many contacts the user will have. I hope that makes sense... Sorry if it doesn't. I'll try to clarify as questions undoubtedly come in.
import java.util.Scanner;
public class _MainMenu {
public static Scanner input = new Scanner(System.in);
public static int choice;
public static String firstName = new String();
public static String lastName = "";
public static String phoneNumbers;
public static String emailAddresses;
public static Person pI = new Person ();
public static void main(String[] args) throws Exception
{
Directory d1 = new Directory("myDir.txt");
do
{
printMenu();
selectSubMenu();
if(choice == 1)
{
for(int i = 0; i < d1.getSize(); i++)
d1.addNewPerson(pI);
}
}while(choice != 3);
d1.writeToFile("myDir.txt");
}
public static void printMenu()
{
System.out.printf("%s\n%s\n%s\n%s\n",
"Select The Number Of Your Choice: ",
"1 - Add New Contact",
"2 - Search (Display/Edit/Remove)",
"3 - Exit");
}
public static void selectSubMenu()
{
choice = input.nextInt();
switch(choice)
{
case 1:
addNewContact();
break;
case 2:
// search();
break;
case 3:
break;
default:
System.out.println("Invalid selection. Please try again.");
}
}
public static void addNewContact()
{
System.out.println("Please enter the first name: ");
firstName = input.next();
System.out.println("Please enter the last name: ");
lastName = input.next();
System.out.println("Please enter up to three phone numbers: ");
phoneNumbers += input.next();
System.out.println("Please enter up to three email addresses: ");
emailAddresses += input.next();
}
}
And here's the code for class Directory:
import java.util.ArrayList;
import java.util.Formatter;
import java.io.File;
import java.util.Scanner;
public class Directory {
private ArrayList <Person> directory = new ArrayList <Person>();
public Directory(String name) throws Exception
{
File f = new File(name);
Scanner input;
if(f.exists())
{
input = new Scanner (f);
while(input.hasNext())
{
Person p = new Person();
p.setFname(input.next());
p.setLname(input.next());
int pNumber = input.nextInt();
for (int i=0; i< pNumber; i++)
p.setPhone(input.next());
int eNumber = input.nextInt();
for (int i=0; i< eNumber; i++)
p.setemail(input.next());
directory.add(p);
}
input.close();
}
else
f.createNewFile();
}
public Person find(String fName, String lName)
{
for(int i=0; i<directory.size(); i++)
{
if (directory.get(i).getLname().equals(lName) && directory.get(i).getFname().equals(fName))
return directory.get(i);
}
return null;
}
public void addNewPerson(Person p)
{
directory.add(p);
}
public void writeToFile(String name) throws Exception
{
Formatter inFile = new Formatter(name);
for( int i =0; i< directory.size(); i++){
inFile.format("%s %s %d ", directory.get(i).getFname(),directory.get(i).getLname(),directory.get(i).pNum);
for(int j=0; j<directory.get(i).pNum; j++)
inFile.format("%s ",directory.get(i).getPhones()[j]);
inFile.format("%d ", directory.get(i).eNum);
for(int j=0; j<directory.get(i).eNum; j++)
inFile.format("%s ",directory.get(i).getemails()[j]);
}
inFile.close();
}
}
I understand that the code in MainMenu within the if(choice == 1) statement doesn't work, but I can't think of how to do this. I want to have Person pI to be the dynamic variable so that if the user wants to add another contact, then he selects "Add Contact" and the program will how many contacts are already in the Directory ArrayList and it will add '1' then input that new variable into "d1.addNewPerson(pI)" so that it works something like this: "d1.addNewPerson(d1.size() + 1)"... I don't know if any of that even made sense. Anyway if someone can make sense of it and know how to work the code, I would greatly appreciate it. Thanks.
You are going to have to create a new Person object for each entry.
Person p = new Person();
p.firstname = ...
p.lastname = ..
d1.addNewPerson(p);
and to get the size of the ArrayList, you can try d1.directory.size() since director is a public field. But if possible you should make it private and add a method to Directory
public int getSize()
{
return directory.size();
}
EDIT:
you can modify your code to something like this
if(choice == 1)
{
Person p = new Person();
p.firstname = ...
p.lastname = ..
d1.addNewPerson(pI);
}