Calling methods from other methods in the same class - java

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;
}
}
}

Related

Object wont initialize - method isn't recognized [duplicate]

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.

My Do-While loop breaks when I hit my keyboard input for the second time

I am only a few weeks in on coding so I'm really new. This is a simple program that assists the user in customizing a new car. The program uses different methods for each of the respective menus. each method that isn't main asks the user which of 2 custom car options they would like then the method sends back a cost to the main. Each method that isn't main uses the same format as the method engineCost. I can't figure out why my keyboard input only functions during the first iteration of my do while loop. This is the error I am prompted with on eclipse:
Exception in thread "main" java.lang.IllegalStateException
I did some looking on stack overflow and I don't think I'm knowledgeable enough to search for the answer properly. Any help would be much appreciated.
import java.util.Scanner;
public class Ch5HW {
public static void main(String[] args){
double baseCar = 14000;
double addCost = 0;
double ttlCost = 0;
int userOpt;
Scanner keyboard = new Scanner(System.in);
System.out.println("Basic Car includes: Silver color, 4 cilinder engine, Cooper Tires; cost: $14,000");
System.out.println("");
//this do-while loops until the user enters 4 to exit
do{
System.out.println("Build Car Quote");
System.out.println("1. Engine");
System.out.println("2. Color");
System.out.println("3. Tires");
System.out.println("4. Exit");
System.out.print("Enter Option: ");
userOpt = 0;
// this keyboard input only works on the first iteration of the loop
userOpt = keyboard.nextInt();
System.out.println(userOpt);
//nested switch to determine userOpt
switch (userOpt)
{
case 1:
// calls the engineCost method
addCost = engineCost();
//adds the value received to a total value
ttlCost += addCost;
break;
case 2:
//calls the colorOpt method
addCost = colorOpt();
//adds the value received to a total value
ttlCost += addCost;
break;
case 3:
//calls the tireOpt method
addCost = tireOpt();
//adds the value received to a total value
ttlCost += addCost;
break;
}
//System.out.print(addCost + baseCar);
keyboard.close();
}
while (userOpt !=4);
//once loop has finished the total of additional purchases is added to the base car price
System.out.print("Total cost: " + (ttlCost + baseCar));
}
// this method has options for the engine
static double engineCost()
{
double engineCost = 0;
double addCost =0;
int engineOpt;
Scanner keyboard = new Scanner(System.in);
System.out.println("Engine Options: ");
System.out.println("1. 8 cylinder: $5000.00");
System.out.println("2. 6 cylinder: $3500.00");
System.out.println("3. Exit");
System.out.println("Enter Option: ");
engineOpt = keyboard.nextInt();
switch (engineOpt)
{
case 1:
engineCost = 5000.00;
addCost += engineCost;
break;
case 2:
engineCost = 3500.00;
addCost += engineCost;
break;
case 3:
engineCost = 0;
addCost += engineCost;
}
keyboard.close();
return addCost;
}
}
This is because of the line: keyboard.close(); within your loop. This closes the Scanner after your first iteration. After this you try to call nextInt() which (from the docs) will throw:
IllegalStateException - if this scanner is closed
You should only close a resource after you are completely done with it.
That being said do not close System.in. The general rule is that if you did not open it, your should not close it.

difficulty displaying items in to-do list

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");
}
}
}
}

How to pass or retrieve linked list from one method to another method?

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.

cannot find symbol errors

I'm a bit lost; I feel like I've done some things similar to this before, but this doesn't work. Is there some adjustment I'm forgetting? For some reason It's saying It can't find the three variables below, Do I need to move them elsewhere/declare in method/somehow disjoint the method from the variable call? All help greatly appreciated.
Scanner input = new Scanner(System.in);
int atmId, selection;
double atmVal;
selectId();
switch(selection){
case 1: AccArray[atmId].getBalance();
break;
case 2: System.out.print("How much would you like to withdraw? ");
atmVal=input.nextInt();
AccArray[atmId].withdraw(atmVal);
break;
case 3: System.out.print("How much would you like to deposit? ");
atmVal=input.nextInt();
AccArray[atmId].deposit(atmVal);
break;
case 4: selectId();
break;
}
} // End of main method
// Method for id selection
public static void selectId(){
// Allows for and requests user input
System.out.print("Enter an id: ");
atmId = input.nextInt();
// Checks for valid input
while (atmId>9 || atmId<0){
System.out.println("Invalid id.");
System.out.print("Enter an id (0-9): ");
atmId = input.nextInt();
}
displayMenu();
}
// Method to display menu
public static void displayMenu(){
System.out.println("Main menu");
System.out.println("1: check balance");
System.out.println("2: withdraw");
System.out.println("3:deposit");
System.out.println("4:exit");
System.out.print("Enter a choice ");
selection = input.nextInt();
// Checks for valid input
while (selection>4 || selection<1){
System.out.println("Invalid choice.");
System.out.print("Enter a choice (1-4): ");
selection = input.nextInt();
}
}
} // End of Test class
Note that you have some scoping errors -- variables declared inside of a method are visible only within that method and are not visible in other methods. To solve this, you could declare the variables within the class.
For example, using only static fields and methods:
public class Foo {
private static int bar; // I am visible throughout the class
public static void someMethod() {
int baz = 8; // I've declared a *local* variable here
}
public static void anotherMethod() {
bar = 3; // I can use bar here since it's visible throughout
baz = 7; // this won't compile since baz is visible only within someMethod()
}
}
Having said that, though shouldn't your selectId() method return an int? Shouldn't you then assign the returned int to your selection variable? If you did this, then the selection variable would not have to be declared in the class.
Note that I would have displayMenu() do just that -- display a menu, and would not have it get user input. That would be for the selectId() method to do.

Categories

Resources