I am trying to create a pet app that allows user input to enter a pet name, update the pet name and delete the pet name. Here is what I have so far. I have made an array for the create method but I can't figure out how to use it in the update or delete methods.
import java.util.Scanner;
import java.io.*;
public class Menu2 {
static Scanner scan = new Scanner(System.in);
public static void main(final String[] args) {
showMainMenu();
}
public static void showMainMenu(){
System.out.println("--- MAIN MENU ---");
System.out.println("1. Create Pet");
System.out.println("2. Update Pet");
System.out.println("3. Delete Pet");
System.out.println("4. Exit");
System.out.print("Enter your Choice : ");
int option = scan.nextInt();
switch(option){
case 1:
createPet();
break;
case 2:
updatePet();
break;
case 3:
deletePet();
break;
case 4:
System.exit(0);
break;
default:
System.out.println("Invalid option!");
showMainMenu();
}
}
public static void createPet(){
Scanner myObj = new Scanner(System.in);
//String newPet = myObj.nextLine();
System.out.print("Enter Pet Name: ");
String newPet = myObj.nextLine();
String newPetArray[] = newPet.split(" ");
// newPet = scan.nextLine();
System.out.println("Pet Name is " + newPet);
// use for READ
for (int i = 0; i < newPetArray.length; i++){
System.out.println(newPetArray[i]);
}
showMainMenu();
}
public static void updatePet() {
}
public static void deletePet() {
}
}
If your goal is to store the pets in an array, for updating you would loop through the array (such as with a "for" or "while" loop), identify the index of the entry to be updated and update it. This could also be done with filters, but that would be a more advanced approach.
In order to delete the pet, you would need to find the pet (like you would in the update portion) and then shift all the remaining pets forward, so newPetArray[x] gets the value of newPetArray[x+1] and the last pet gets removed.
This task is easier with other datastructures, like ArrayList's, that support removing and inserting items directly.
As you haven't mentioned the details about the update function, I am assuming it is going to update the name of the pet present in the list. As ArrayList is more flexible when it comes to array in terms of addition of deletion and since you havent specified that you need to use array in particular, I'm providing the solution with ArrayList.
Logic for Updation
You iterate through the list and when the element matches, you simply update the name
Logic for Deletion
You iterate through the list and when the element matches, you simply remove the element present at that index.
import java.util.ArrayList;
import java.util.Scanner;
public class Menu2 {
static Scanner scan = new Scanner(System.in);
static ArrayList<String> petList;
public static void main(final String[] args) {
showMainMenu();
scan.close();
}
public static void showMainMenu() {
System.out.println("--- MAIN MENU ---");
System.out.println("1. Create Pet");
System.out.println("2. Update Pet");
System.out.println("3. Delete Pet");
System.out.println("4. Exit");
System.out.print("Enter your Choice : ");
int option = scan.nextInt();
switch (option) {
case 1:
createPet();
break;
case 2:
updatePet();
break;
case 3:
deletePet();
break;
case 4:
System.exit(0);
break;
default:
System.out.println("Invalid option!");
showMainMenu();
}
}
public static void createPet() {
Scanner myObj = new Scanner(System.in);
System.out.print("Enter Pet Name: ");
String newPet = myObj.nextLine();
String newPetArray[] = newPet.split(" ");
petList = new ArrayList<>();
// use for READ
for (int i = 0; i < newPetArray.length; i++) {
petList.add(newPetArray[i]);
}
System.out.println("pets in list are " + petList);
showMainMenu();
}
public static void updatePet() {
System.out.println("Enter the name of the pet to be updated");
String name = scan.next();
System.out.println("Enter the updated name");
String newName = scan.next();
for (int i = 0; i < petList.size(); i++) {
if (petList.get(i).equals(name)) {
petList.set(i, newName);
break;
}
}
System.out.println("pets in list after updating the pet " + petList);
showMainMenu();
}
public static void deletePet() {
System.out.println("Enter the name of the pet to be deleted");
String name = scan.next();
for (int i = 0; i < petList.size(); i++) {
if (petList.get(i).equals(name)) {
petList.remove(i);
break;
}
}
System.out.println("pets in list after deleting the specific pet " + petList);
showMainMenu();
}
}
and the output is as follows:
--- MAIN MENU ---
1. Create Pet
2. Update Pet
3. Delete Pet
4. Exit
Enter your Choice : 1
Enter Pet Name: buddy max mac
pets in list are [buddy, max, mac]
--- MAIN MENU ---
1. Create Pet
2. Update Pet
3. Delete Pet
4. Exit
Enter your Choice : 2
Enter the name of the pet to be updated
mac
Enter the updated name
macKing
pets in list after updating the pet [buddy, max, macKing]
--- MAIN MENU ---
1. Create Pet
2. Update Pet
3. Delete Pet
4. Exit
Enter your Choice : 3
Enter the name of the pet to be deleted
max
pets in list after deleting the specific pet [buddy, macKing]
--- MAIN MENU ---
1. Create Pet
2. Update Pet
3. Delete Pet
4. Exit
Enter your Choice : 4
Related
This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Closed 2 years ago.
This is the 'Lead' class, when I try to call Leads.primeLead() , I get a
"Non-static method cannot be referenced from a static context" error.
I do understand the error, but I do not understand why when I defined a constructor and initilized an object, I cannot apply the method primeLead() on object lead1 .
How do I solve this?
import java.util.ArrayList;
import java.util.Scanner;
public class Lead extends Main{
String nameLead;
int ageLead;
int phoneLead;
String cityLead;
String email;
String otherNotes;
int indexOfLead = 0;
int i = indexOfLead;
ArrayList<String> names = new ArrayList<String>();
ArrayList<Integer> ages = new ArrayList<Integer>();
ArrayList<Integer> phones = new ArrayList<Integer>();
ArrayList<String> cities = new ArrayList<String>();
ArrayList<String> emails = new ArrayList<String>();
ArrayList<String> notes = new ArrayList<String>();
Scanner leads = new Scanner(System.in);
Lead(){
i = 0;
// Need to create an ArrayList that has all the Arraylists above.
}
Lead lead1 = new Lead();
/* public mainMenuLead(){
System.out.println("Please choose one of the following options");
} */
public static void primeLead(){
i = 0;
System.out.println("============================================");
System.out.println(" Please enter by the following order : ");
System.out.println(" Name, age, phone , city, mail ");
System.out.println("============================================");
System.out.println("Please enter the name of the Lead : ");
names.add(leads.nextLine());
System.out.println("Age? : ");
ages.add(Integer.parseInt(leads.nextLine()));
System.out.println("Phone number? ");
phones.add(Integer.parseInt(leads.nextLine()));
System.out.println("Would you like to add ... ");
System.out.println("1) City? ");
System.out.println("2) Email? ");
System.out.println("3) Notes? ");
if(leads.nextLine().equals("1")){
System.out.println("Please add City: ");
cities.add(leads.nextLine());
} else if (leads.nextLine().equals("2")){
System.out.println("Please add email : ");
emails.add(leads.nextLine());
} else if(leads.nextLine().equals("3")){
System.out.println("Please add any other notes you may have: ");
notes.add(leads.nextLine());
}
}
}
public void primeLead(){
i = 0;
System.out.println("============================================");
System.out.println(" Please enter by the following order : ");
System.out.println(" Name, age, phone , city, mail ");
System.out.println("============================================");
System.out.println("Please enter the name of the Lead : ");
names.add(leads.nextLine());
System.out.println("Age? : ");
ages.add(Integer.parseInt(leads.nextLine()));
System.out.println("Phone number? ");
phones.add(Integer.parseInt(leads.nextLine()));
System.out.println("Would you like to add ... ");
System.out.println("1) City? ");
System.out.println("2) Email? ");
System.out.println("3) Notes? ");
if(leads.nextLine().equals("1")){
System.out.println("Please add City: ");
cities.add(leads.nextLine());
} else if (leads.nextLine().equals("2")){
System.out.println("Please add email : ");
emails.add(leads.nextLine());
} else if(leads.nextLine().equals("3")){
System.out.println("Please add any other notes you may have: ");
notes.add(leads.nextLine());
}
}
}
second file(Where Lead.primeLead() is called:
import java.util.Scanner;
public class Main {
boolean exit = false;
public void runMenu(){
printHeader();
while(!exit){
mainMenu();
int choice = getInput();
performAction(choice);
}
}
private void performAction(int choice){
switch(choice){
case 1:
new Lead();
Lead.primeLead();
case 2:
case 3:
case 4:
case 5:
exit = true;
System.out.println("Bye!");
break;
}
}
public void printHeader(){
System.out.println("===========================================");
System.out.println(" Hello user! ");
System.out.println(" Welcome to our lead ");
System.out.println(" Management tool ");
System.out.println("===========================================");
}
public void mainMenu(){
System.out.println("\nPlease select one of the following options: ");
System.out.println("1) Create a new lead");
System.out.println("2) View all the leads");
System.out.println("3) Connect ");
System.out.println("4) View statistics");
System.out.println("5) Exit ");
}
private int getInput(){ // Scanner takes input from user, returns his choice.
Scanner kb = new Scanner(System.in);
int choice = -1;
while(choice < 0 || choice > 5){
try{
System.out.print("\nEnter your choice: ");
choice = Integer.parseInt(kb.nextLine()); // What is Integer.parseInt ? what is . next line ?
}
catch(NumberFormatException e){
System.out.println("Invalid selection, please try again.");
}
}
return choice;
}
public static void main(String[] args){
Main menu = new Main();
menu.runMenu();
}
}
You create a Lead object and do not use it:
new Lead();
Lead.primeLead();
Instead, you should use the lead object you created:
Lead lead=new Lead();
lead.primeLead();
If you call <ClassName>.<methodName>(<parameters>);, you call a static method that has nothing to do eith the object.
If you call <objectOfTheClass>.<methodName>(<parameters>);, you call a non-static method that is part of the object.
And, as #Andreas points out in the comments, every open curly brace needs to have a closing curley brace at the appropriate position any the other way round.
I'm trying to build a text based to do list in Java but I'm having some difficulties when it comes to displaying the items.
When I run the code and enter "1" the contents of the to do list are displayed back to me, but they keep looping and they never stop. I'm assuming this has something to do with the while loop that checks the userChoice variable but my question is why does the list keep reiterating even after the break statement? What I'd like to have happen is to enter a number, have the action performed, and then have the instruction prompt displayed again.
java code:
package com.company;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
// create an arraylist to store users items
static ArrayList<String> toDoList = new ArrayList<String>(3);
public static void main(String[] args) {
// greet the user
System.out.println("**Your To-Do list** \n");
// add default items to list
toDoList.add("Buy Groceries");
toDoList.add("Work Out");
toDoList.add("Play CS");
// user menu/instruction
System.out.println("Please select from one of the following options: \n 1. Show to-do list \n 2. Add item " +
"\n 3. Remove item \n 4. Exit program \n");
// prompt user for their choice
System.out.print("Enter your choice: ");
// get user choice
Scanner input = new Scanner(System.in);
int userChoice = input.nextInt();
while (userChoice != 4) {
switch (userChoice) {
case 1:
getToDoList();
break;
case 2:
// create method that allows you to add item to the toDolist
break;
case 3:
// create method that allows you to remove item from the toDolist
break;
case 4:
// create method that terminates application
break;
}
}
}
// method that returns contents of the list
public static void getToDoList(){
for (int i = 0; i < toDoList.size(); i++) {
System.out.println(toDoList.get(i));
}
}
}
It is because you did not request to read from user again.
case 1:
getToDoList();
input.nextInt();
break;
Or move the input.nextInt(); outside of switch block (below it).
Because userChoice is always 1, so it always loop.
import java.util.ArrayList;
import java.util.Scanner;
public class Groceries {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> a=new ArrayList<String>();
a.add("Food");
a.add("Furniture");
a.add("Plywood");
while(true)
{
System.out.println("Enter your choice");
System.out.println("Your choice List\n 1:getList 2.addinthelist 3.removefromlist 4.exit");
Scanner sc=new Scanner(System.in);
int a1=sc.nextInt();
switch(a1)
{
case 1:
System.out.println(a);
break;
case 2:
System.out.println("List before addition of elemnt is :"+a);
System.out.println("Enter element to be added into the string");
String sss=sc.next();
a.add(sss);
System.out.println("List after addition of element is :"+a);
break;
case 3:
System.out.println("List before deletion of elemnt is "+a);
System.out.println("Enter an index of an element to be removed");
int abc=sc.nextInt();
a.remove(abc);
System.out.println("List after Deletion of an element is "+a);
break;
case 4:
System.exit(0);
default:
System.out.println("You entered wrong number !! Please enter 4 to exit");
}
}
}
}
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
}
}
I am trying to call a method from another method in the same class, for example when the "enterValues" method is finished, I want it to go back to the main menu. Can someone please explain how I can do this? I am also a bit confused on the use of objects here, am I right in thinking I need to create an object in every method like I have done here, in order to call other methods?
import java.util.Scanner;
public class Conversion {
int value;
public void mainMenu() {
int menuChoice;
Scanner menuScan = new Scanner(System.in);
Conversion mainMenu = new Conversion();
System.out.println("1. Enter values and type -1 to stop");
System.out.println("2. Euros");
System.out.println("3. Dollars");
System.out.println("4. Yen");
System.out.println("5. Rupees");
System.out.println("6. Exit");
while (!menuScan.hasNextInt() || (menuChoice = menuScan.nextInt()) > 6) {
menuScan.nextLine();
System.err.println("Please enter a valid menu option 1 - 6: ");
}
switch (menuChoice) {
case 1:
mainMenu.enterValues();
case 2:
}
}
public void enterValues() {
Conversion enterValues = new Conversion();
Scanner valueScan = new Scanner(System.in);
System.out.print("Enter value to convert: ");
value = valueScan.nextInt();
System.out.println("Value entered. Returning to main menu.");
valueScan.close();
enterValues.mainMenu();
}
public static void main(String[] args) {
Conversion main = new Conversion();
main.mainMenu();
}
}
When you are inside a non-static method, you already are in an instance of your Class, so no need to create another instance.
Also, when you are in an instance of a class, you just call other methods directly, like mainMenu();
I modified your code a bit to reflect this :
import java.util.Scanner;
public class Conversion {
int value;
public void mainMenu() {
int menuChoice;
Scanner menuScan = new Scanner(System.in);
System.out.println("1. Enter values and type -1 to stop");
System.out.println("2. Euros");
System.out.println("3. Dollars");
System.out.println("4. Yen");
System.out.println("5. Rupees");
System.out.println("6. Exit");
while (!menuScan.hasNextInt() || (menuChoice = menuScan.nextInt()) > 6) {
menuScan.nextLine();
System.err.println("Please enter a valid menu option 1 - 6: ");
}
switch (menuChoice) {
case 1:
enterValues();
case 2:
}
}
public void enterValues() {
Scanner valueScan = new Scanner(System.in);
System.out.print("Enter value to convert: ");
value = valueScan.nextInt();
System.out.println("Value entered. Returning to main menu.");
valueScan.close();
mainMenu();
}
public static void main(String[] args) {
Conversion main = new Conversion();
main.mainMenu();
}
}
You must not create a new object every time you call a method. Within a class you can call any method you want.
If you finish one method, you continue where you called it. So in order to keep the main menu open you would have to use a loop or something similar.
The call itself is nothing more than:
mainMenu();
respectively
enterValues();
without creating a new Conversion.
You don't want to call mainMenu from enterValues, you want to return to it.
Make a "forever" loop inside mainMenu, and add an exit condition with a break. This way simply returning from enterValues or any other method inside mainMenu would bring you back to printing main menu and asking what else you wish to do:
public void mainMenu() {
mainLoop: while (true) {
int menuChoice;
Scanner menuScan = new Scanner(System.in);
Conversion mainMenu = new Conversion();
System.out.println("1. Enter values and type -1 to stop");
System.out.println("2. Euros");
System.out.println("3. Dollars");
System.out.println("4. Yen");
System.out.println("5. Rupees");
System.out.println("6. Exit");
while (!menuScan.hasNextInt() || (menuChoice = menuScan.nextInt()) > 6) {
menuScan.nextLine();
System.err.println("Please enter a valid menu option 1 - 6: ");
}
switch (menuChoice) {
case 1:
mainMenu.enterValues();
break;
case 2:
break;
case 6:
break mainLoop;
}
}
}
First i want to retrieve patient linked list from AddPatient() method and show it on ListPatient() Method.
I try to retrieve by changing public static void ListPatient(); method to public static void ListPatient(ListInterface<PatientDetails> patient) but it doesn't work
package dsa;
import dsa.LList;
import dsa.ListInterface;
import java.sql.Time;
import java.util.Date;
import java.util.Scanner;
public class EmergencyClinic {
public static void main(String[] args){
MainMenu();
}
public static void MainMenu(){
int n = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to Emergency Clinic!");
System.out.println("1. Add Patient");
System.out.println("2. Serve Patient");
System.out.println("3. List Patient");
System.out.print("Please choose your option :");
n = scan.nextInt();
switch(n){
case 1: AddPatient();
break;
case 2: ServePatient();
break;
case 3: ListPatient();
break;
default : System.out.println("Sorry! Invalid Input. Returning to main menu...\n"); MainMenu();
break;
}
}
public static void AddPatient(){
ListInterface<PatientDetails> patient = new LList<PatientDetails>();
Scanner scan = new Scanner(System.in);
int num=0;
System.out.print("Please Enter Name :");
String name = scan.nextLine();
System.out.print("Please Enter IC No :");
String ic = scan.nextLine();
System.out.print("Please Enter Contact Number :");
String contactNum = scan.nextLine();
System.out.print("Please Enter Gender :");
String gender = scan.nextLine();
Date date = new Date();
Long time = date.getTime();
System.out.print("Please Enter Reason :");
String reason = scan.nextLine();
System.out.print("Please Enter Seriousness :");
String seriousness = scan.nextLine();
if(patient.isEmpty())
{
patient.add(new PatientDetails(name, ic, contactNum, gender,date ,time ,reason,seriousness ));
}
MainMenu();
}
public static void ServePatient(){
}
public static void ListPatient(){
ListInterface<PatientDetails> patient = new LList<PatientDetails>();
System.out.println(patient.getLength());
if (!patient.isEmpty())
{
for(int i=0;i<patient.getLength();i++){
patient.getEntry(i);
}
}
else
{
System.out.println("Error in list patients!");
}
}
}
It seems that the add, list and serve are three functions. All your methods are static, then you need a static PatientList variable. That is, when user picked add, he added elements in the list, when he chose list, the same list objects would be displayed.
In codes just in your class declare:
private static ListInterface<PatientDetails> patient = new LList<PatientDetails>();
In your add and list method, use this variable directly.
All your methods are marked as void. That means the have no return value. One might say, they are procedures, not functions.
If you want to return a List, you have to change the signature:
public static List AddPatient()
Then you can return your list from the method using keyword return.
return patient;
The parameters in brackets () are all input parameters.
This is a very basic concept of methods/functions. I suggest reading a book for begginers to understand the fundamentals of Java.
Also Java has it's own general-purpose implementation of linked list. You should use it, if you don't have any special requirements for it's implementation.