Here's my output:
-----Query-----
[1]Update
[2]Delete
[3]Search
[4]Show
Choose Query:1
Enter Your Student ID:1
Enter Your First Name: Respo
Enter Your Middle Name: Topher
Enter Your Last Name: Raspo
Do you want to back to Query?(Yes/No)
Yes
-----Query-----
[1]Update
[2]Delete
[3]Search
[4]Show
Choose Query: 4
12
Christopher
Reposo
Porras
1
Respo
Topher
Raspo
As you can see in the picture I'm trying to make a simple little system without database but using ArrayList to contain those data now my problem is in the Delete Query. Now in Delete Query I tell the user to type the student number which is 1 then delete the information of it and its contain which is first name, middle name, last name But I don't have much logic in ArrayList to do such thing. By the way is it possible to use only One ArrayList in this case or I need to make many array list to solve my problem.
public static void main(String[] args) {
//initialize Scanner for input process
Scanner scan = new Scanner(System.in);
//initialize needs variable
List<String> list = new ArrayList<String>();
int choose,chooseQuery;
String chooseYesOrNo = " ";
String chooseYesOrNo2 = " ";
do {
//Startup Program
System.out.println("=====-----LibrarySystem-----=====");
System.out.println("[1]Student Information");
System.out.println("[2]Book Information");
System.out.print("Choose Table:");
choose = scan.nextInt();
do {
if(choose == 1) {
System.out.println("-----Query-----");
System.out.println("[1]Update");
System.out.println("[2]Delete");
System.out.println("[3]Search");
System.out.println("[4]Show");
//reserved
//reserved
System.out.print("Choose Query:");
chooseQuery = scan.nextInt();
if(chooseQuery == 1) {
System.out.print("Enter Your Student ID:");
String id = scan.next();
list.add(id);
System.out.print("Enter Your First Name:");
String name = scan.next();
list.add(name);
System.out.print("Enter Your Middle Name:");
String middle_name = scan.next();
list.add(middle_name);
System.out.print("Enter Your Last Name:");
String last_name = scan.next();
list.add(last_name);
System.out.println("Do you want to back to Query?(Yes/No)");
chooseYesOrNo = scan.next();
} else if (chooseQuery == 2) { //Delete Query
System.out.print("Enter Student ID:");
String find_id = scan.next();
} else if(chooseQuery == 3) { //Search Query
} else if(chooseQuery == 4) { //Show Query
for (String s : list) {
System.out.println(s);
}
}
}
} while(chooseYesOrNo.equals("Yes"));
System.out.println("Do you want to get back at tables?(Yes/No)");
chooseYesOrNo2 = scan.next();
} while(chooseYesOrNo2.equals("Yes"));
System.out.println("-----=====Program Terminated=====-----");
}
Create Student object which contains all the fields you need (student id, name, etc)
class Student {
int studentId;
String firstname;
String middlename;
String lastname;
}
Have one array list for Student objects
java.util.List<Student> list = new java.util.ArrayList<Student>();
When Delete operation is selected, iterate through your list to find the object and remove it. Here's nice blog about ways to iterate through arraylist. My favorite method is as follows:
for (Student std:list) {
if (std.studentId == targetId) {
list.remove(std);
break; //since you've removed target, you can exit the loop
}
}
Related
no matter what I use indexof() or contains or .equals() changing everything to uppercase or to lowercase It always return false and not found can someone please tell me what is going on?
class Students{
private ArrayList<String> snames;
private String tname;
//this one combines both question 2 and 4.
public Students(String tname){
snames=new ArrayList<>();
this.tname=tname;
}
public String gettname(){return tname;}
public ArrayList<String> getsnames(){return snames;}
public void addStudent(String name){
snames.add(name);
}
public boolean studentExists(String name){
boolean e=false;
for(String i:snames){
if(i.contains(name)){
e=true;
}
}
return e;
}
}
public class Main
{
public static void main(String[] args) throws IOException{
Scanner k=new Scanner(System.in);
out.println("what is your name?");
String name=k.nextLine();
out.println(name.toUpperCase());
Students s=new Students(name);
out.println("enter student name");
String snames=k.nextLine();
while(snames!="."){
out.println("enter student name");
snames=k.nextLine();
s.addStudent(snames);
if (snames.equals("."))
break;
}
out.println("who u want to find");
String target=k.nextLine();
boolean exist=s.studentExists(target);
if(exist==true){
out.println("Found student");
}
else out.println("Student not found.");
out.println(exist);
}
}
no matter what I use indexof() or contains or .equals() changing everything to uppercase or to lowercase It always return false and not found can someone please tell me what is going on?
You have a logic issue...
out.println("enter student name");
String snames = k.nextLine();
while (snames != ".") {
out.println("enter student name");
snames = k.nextLine();
s.addStudent(snames);
if (snames.equals(".")) {
break;
}
}
You...
Prompt for the name
Read the next line of input
Check to see if it's the exit condition (by the way, snames != "." is wrong, it should be !".".equals(snames)
You prompt them to enter the name
You read the input
You write the input to Students
You check for the exit condition ... again
So, between 3 and 4, you never write what was first entered by the user, so, if you only enter
enter student name
jack
enter student name
.
Only . will be added to the list
Instead, you should be doing something more like...
Scanner scanner = new Scanner(System.in);
Students students = new Students("Test");
String name = ".";
do {
System.out.print("enter student name (or \".\" to exit) ");
name = scanner.nextLine();
if (!name.equals(".")) {
students.addStudent(name);
}
} while (!name.equals("."));
do {
System.out.print("who u want to find (or \".\" to exit) ");
name = scanner.nextLine();
if (!name.equals(".")) {
if (students.studentExists(name)) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
} while (!name.equals("."));
The important point here is to make sure when you ask for input, you are actually writing it the list, unless it's the exit value (ie .)
The code is bad-structured, and the first snames is never added to the ArrayList.
See the codes below in class Main:
public static void main(String[] args) throws IOException {
// ignore the teacher name part
Students s = new Students(name);
// when the first snames is received,
System.out.println("enter student name");
String snames = k.nextLine();
while (snames != ".") {
// the name is not saved, but another snames is received.
System.out.println("enter student name");
snames = k.nextLine();
System.out.println(snames);
s.addStudent(snames);
// the "." is also saved as well.
if (snames.equals("."))
break;
}
}
}
I would suggest modifying the while loop into something like this:
Students student = new Students(tname);
// no need to get scanner output before loop
String sname;
do {
System.out.println("enter student name");
sname = scanner.nextLine();
System.out.println(sname);
student.addStudent(sname);
} while (!sname.equals("."));
Hope this answer helps you well.
Unsure of where my code is failing, and where I should be going next with it. I need a fully functional loop menu, that seems to work so far, in which I am able to do the options the menu displays. This includes adding to lists and checking lists. I also am having an issue in which the dog list is not displaying the list of dogs by their name or information, but rather their space. Any help would be greatly appreciated.
// Complete intakeNewMonkey
//Instantiate and add the new monkey to the appropriate list
// For the project submission you must also validate the input
// to make sure the monkey doesn't already exist and the species type is allowed
public static void intakeNewMonkey(Scanner scanner) {
System.out.println("What is the new monkey's name?");
String name = scanner.nextLine();
for (Monkey monkey: monkeyList) {
if(monkey.getName().equalsIgnoreCase(name)) {
System.out.println("\n\nThis monkey is already in our system.\n\n");
return;
}
}
System.out.println("What is the monkey's tail length?");
String tailLength = scanner.nextLine();
System.out.println("What is the monkey's gender?");
String gender = scanner.nextLine();
System.out.println("What is the monkey's age?");
String age = scanner.nextLine();
System.out.println("What is the monkey's weight?");
String weight = scanner.nextLine();
System.out.println("What is the monkey's acquisition date?");
String acquisitionDate = scanner.nextLine();
System.out.println("What is the monkey's acquisition country?");
String acquisitionCountry = scanner.nextLine();
System.out.println("What is the monkey's training status?");
String trainingStatus = scanner.nextLine();
System.out.println("Is the monkey reserved? <enter true or false>");
boolean reservedBoolean = scanner.nextBoolean();
System.out.println("What is the monkey's service country?");
String serviceCountry = scanner.nextLine();
System.out.println("What is the monkey's body length?");
String bodyLength = scanner.nextLine();
System.out.println("What is the monkey's height?");
String height = scanner.nextLine();
System.out.println("What is the monkey's species?");
String species = scanner.nextLine();
}
// Complete reserveAnimal
// You will need to find the animal by animal type and in service country
public static void reserveAnimal(Scanner scanner) {
System.out.println("Enter animal type");
String type = scanner.nextLine();
if (type.equals("Monkey") || type.equals("monkey")) {
for (int i = 0; i < monkeyList.size(); i++) {
if (!monkeyList.get(i).getReserved());
System.out.println(monkeyList.get(i));
}
System.out.println("Enter name: ");
String name = scanner.nextLine();
for (Monkey obj: monkeyList) {
if (obj.name.equals(name)) {
obj.reserved = true;
return;
}
}
System.out.println("Monkey not found in list");
}
if (type.equals("Dog") || type.equals("dog")) {
for (int i = 0; i < dogList.size(); i++) {
if (dogList.get(i).getReserved())
System.out.println(dogList.get(i));
}
System.out.println("Enter name: ");
String name = scanner.nextLine();
for (Dog obj: dogList) {
if (obj.name.equals(name)) {
obj.reserved = true;
return;
}
}
System.out.println("Dog not found in list");
}
}
// Complete printAnimals
// Include the animal name, status, acquisition country and if the animal is reserved.
// Remember that this method connects to three different menu items.
// The printAnimals() method has three different outputs
// based on the listType parameter
// dog - prints the list of dogs
// monkey - prints the list of monkeys
// available - prints a combined list of all animals that are
// fully trained ("in service") but not reserved
// Remember that you only have to fully implement ONE of these lists.
// The other lists can have a print statement saying "This option needs to be implemented".
// To score "exemplary" you must correctly implement the "available" list.
public static void printAnimals() {
System.out.println("The method printAnimals needs to be implemented");
}
You need to override the toString() class provided by the Object class. You can do this by writing something like
#Override
public String toString() {
return "Name: " + this.name + ". Gender " + this.gender "." // and so on
}
i am doing a contact book information and only want to add maximum of 20 contacts but it only adds maximum of 10 contacts any help?
public class Book {
public static void main(String[] args) {
List<Contact> lsCont = new ArrayList<Contact>();
Contact[] contacts = new Contact[20];
Scanner scanner = new Scanner(System.in);
String firstName;
String lastName;
String phone;
String email;
for (int i = 0; i < contacts.length; i++) {
System.out.println("insert first name : ");
firstName = scanner.nextLine();
System.out.println("insert last Name : ");
lastName = scanner.nextLine();
System.out.println("insert phone : ");
phone = scanner.nextLine();
System.out.println("insert email : ");
email = scanner.nextLine();
Contact cont = new Contact(firstName, lastName, phone, email);
lsCont.add(cont);
Collections.sort(lsCont);
i++;
for (Contact contact : lsCont) {
System.out.println(contact.toString());
}
if (i == contacts.length) {
System.out.println("maxiumum number of adding contact has reached");
break;
}
}
}
}
You are incrementing the value of the variable i twice in your for loop, causing it to increase by 2 every time. This causes the for loop to only run half times. To fix this you can simply remove the second i++.
Also, to make it more clear, I would suggest making an int variable maxContacts, then replacing the "20" inside the brackets with the name of the variable, and writing maxContacts instead of contacts.length to make the code more clear and readable!
You are incrementing i twice. Remove i++ in the body of the for loop.
Scanner scanner = new Scanner(System.in);
int weight;
int age;
//arrays
List<String> last = new ArrayList<String>();
List<Integer> zage = new ArrayList<Integer>();
List<Integer> zweight = new ArrayList<Integer>();
int i = 0;
int userInput = 0;
//menu options
while(userInput != 2) {
userInput = scanner.nextInt(); // collects the user inputs
//several switch statements to answer each menu options
switch(userInput) {
case 1:
it saves and stores all the user inputs.
System.out.println("Enter a last name, age, weight"); //stores all the user information
String lastName = scanner.next();
last.add(lastName);
age = scanner.nextInt();
zage.add(age);
weight = scanner.nextInt();
zweight.add(weight);
break;
Need to add a search code where it will retrieve the user inputs and display it, but i'm not sure on how to do it.
case 5:
System.out.println("Enter the name; Enter DONE to exit");
System.out.println("FOUND!!! Last Name: " +last+ " Age: " +zage+ " Weight: " +zweight);
Your names are stored in a list so you can try this:
if (last.contains(searchName)) {
String foundName = last.get(last.indexOf(searchName));
System.out.println("FOUND!!! Last Name: " +foundName);
} else{
System.out.println("Last Name: " +searchName+ " NOT FOUND!!! ");
}
Note that duplicate names may be in the list so you may want to loop over the indexes.
you can do this:
String enteredLastName = scanner.next();
for (String name : last){
if (name.equals(enteredLastName ){
//do something
}
}
Why when I run my program and enter 5, it allows me to enter my records, but when the main menu runs again and I enter 6, the changePhoneNumber method is not run and it goes back to the main menu. Is the while(true) loop somehow messing things up?
I have a class called Record that looks like:
public static void main(String[] args) {
BankMethods method = new BankMethods();
Scanner input = new Scanner(System.in);
int optionSelected = 0;
while(true){
System.out.println("5. Add a New Record");
System.out.println("6. Change the Phone Number in the Current Record");
optionSelected = input.nextInt();
if (optionSelected == 5){
Scanner getRecord = new Scanner(System.in);
System.out.println("Enter First Name: ");
String firstName = getRecord.nextLine();
System.out.println("Enter Last Name: ");
String lastName = getRecord.nextLine();
System.out.println("Enter Phone Number: ");
String phoneNumber = getRecord.nextLine();
method.addNewRecord(firstName, lastName, phoneNumber);
}
if (optionSelected == 6){
System.out.println("What would you like to change your phone "
+ "number to? ");
String newNumber = input.nextLine();
method.changePhoneNumber(newNumber);
}
and the other class...BankMethods:
public class BankMethods {
LinkedList recordInformation = new LinkedList();
Bankdata mainMenu = new Bankdata();
public void addNewRecord(String firstName, String lastName,
String phoneNumber){
recordInformation.add(firstName); recordInformation.add(lastName);
recordInformation.add(phoneNumber);
}
public void changePhoneNumber(String newNumber){
recordInformation.set(2, newNumber);
System.out.println(recordInformation);
}
The problem is that you are using 2 Scanners to read the one InputStream. When you open the second Scanner you will not be able to read using the original one as the second will have exclusive access to it.
For this application you could easily use a single Scanner.
See: Do not create multiple buffered wrappers on a single InputStream
The correct way is to use one read(scanner) for a input stream. Edited the previous answer to use single read option
Complete program that works is given below
package com.stackoverflow.framework;
import java.util.LinkedList;
import java.util.Scanner;
public class Record {
static Scanner input = new Scanner(System.in);
public static String readData() {
return (input.nextLine());
}
public static void main(String[] args) {
BankMethods method = new BankMethods();
int optionSelected = 0;
while (true) {
System.out.println("5. Add a New Record");
System.out
.println("6. Change the Phone Number in the Current Record");
optionSelected = Integer.parseInt(readData());
if (optionSelected == 5) {
// Scanner getRecord = new Scanner(System.in);
System.out.println("Enter First Name: ");
String firstName = readData();
System.out.println("Enter Last Name: ");
String lastName = readData();
System.out.println("Enter Phone Number: ");
String phoneNumber = readData();
method.addNewRecord(firstName, lastName, phoneNumber);
}
if (optionSelected == 6) {
System.out.println("What would you like to change your phone "
+ "number to? ");
// Scanner getRecord = new Scanner(System.in);
String newNumber = readData();
method.changePhoneNumber(newNumber);
}
}
}
}
class BankMethods {
LinkedList recordInformation = new LinkedList();
public void addNewRecord(String firstName, String lastName,
String phoneNumber) {
recordInformation.add(firstName);
recordInformation.add(lastName);
recordInformation.add(phoneNumber);
}
public void changePhoneNumber(String newNumber) {
recordInformation.set(2, newNumber);
System.out.println(recordInformation);
}
}