ok so i have a method that displays a menu and returns the user selection.
public class Menu {
public static int menuSelect(){
Scanner input = new Scanner(System.in);
System.out.println("Hello, Please Select A Function: ");
System.out.println("1) Sort All Banks Alphabetically ");
System.out.println("2) Calculate Interest And Show Balance ");
System.out.println("3) Transfer Money ");
System.out.println("4) Calulate Sum & Average Of All Accounts: ");
System.out.println("5) Richest Account: ");
System.out.println("6) Poorest Account: ");
int select = input.nextInt();
Menu.menuSelect();
//i tried this as adding Menu.menuSelect();
//after the return threw an error.
// but surprise suprise this doesnt actually
//let the method return anythign to select
return select;
}
The idea is that i want menu to come up the user selects a function, the function happens and then the menu calls itself until told otherwise.
but im unsure how to do this.
any help would be greatly appreciated.
Calling the same method from itself is called a recursion, and it's infinite in your case. You obviously don't need it here.
You want to have something like this:
private static int getInput() {
int choice = menuSelect();
while(choice < 1 || choice > 6) {
System.out.println("Invalid choice, please re-enter")
choice = menuSelect();
}
return choice;
}
Note that it's bad to give menuSelect a public modifier, you don't want anyone outside the class to have an access to it.
Related
So, as you will see I have a menu system. The bit of code you're about to see shows how I intend for the user's input to determine what method/or user option in the program will be presented to them. To do this, I've tried an if statement within my menu system method which I'd like to call to the particular method which is assigned to whatever option the user has picked - to then start that option's purpose/or method. I've typed in the method I'd like option '1' to correspond to within the if statement... but it presents to me an error. Any help on how I fix this or how to go about this... would be truly appreciated. P.s. I've only been learning Java for a couple weeks, and it's my first language.
The error prints this message:
error: non-static method keepCounting() cannot be referenced from a static context
keepCounting();
^
1 error
compiler exit status 1
import java.util.Scanner;
class Main {
// instance fields
public static final Scanner userInput = new Scanner(System.in);
// constructor method (defunct)
// 0. menu system method
public static void menuSystem(){
int usersNumberChoice;
System.out.println("P4CS Mini Applications");
System.out.println("----------------------");
System.out.println("Please select an option:");
System.out.println("1. Keep Counting Game");
System.out.println("2. Number Conversion Tool");
System.out.println("3. UPC Calculator");
System.out.println("4. UPC Checker");
System.out.println("9. Quit");
System.out.println("Please enter an option:");
usersNumberChoice = userInput.nextInt();
if (usersNumberChoice == 1){
keepCounting();
}
}
// 1. keep counting game method
public void keepCounting(){
System.out.println("hello world");
}
Mark your keepCounting() as static because static method can not be called from non-static method.
public static void keepCounting(){
System.out.println("hello world");
}
I'm a BEGINNER in java. My project is a simple calorie counter.
The way it should work:
Enter calorie intake number: (user adds number)
program subtract users input by 2,000 calories
As of now, my program is subtracting the parameter for the food object from the 2,000 cal. I know this because I'VE DONE A LOT OF TESTING TRYING TO FIGURE OUT THE SOLUTION TO THIS PROBLEM MYSELF. If i had not changed the parameters for the cheesecake flavors methods to include a string and an integer, than it would have subtracted the calorie int from the last listed cake flavor(carmel) that held the variable calorie.
The problem:
I can seem to figure out how to connect the user input to the calorie calculation coded in the food class above the main. I've also tried changing the Scanner input variable to the calorie variable, but it then could not be resolved.
I'm listening my code now below. I'd be very grateful to anyone that could help me. Please remember, I'm a beginner, and read everything i've written before responding.
Thank you
int calculateCaloriesLeft() {
int caloriesLeft = 2000 - calories;
return caloriesLeft;
}
Scanner input = new Scanner(System.in);
System.out.println("Enter calorie of food: ");
int value = 0;
value = input.nextInt();
value = deserts.calculateCaloriesLeft();
System.out.println("calories left: " + value);
}
}
You are not passing the entered value into the calculateCaloriesLeft method. You would need to add a parameter and pass the users input into it.
Scanner input = new Scanner(System.in);
System.out.println("Enter calorie of food: ");
int value = 0;
value = input.nextInt();
value = deserts.calculateCaloriesLeft(value);
System.out.println("calories left: " + value);
And your method would be
int calculateCaloriesLeft(int userCalories) {
int caloriesLeft = 2000 - userCalories;
return caloriesLeft;
}
I am literally know and get the hang of the java right now and I'm writing the program that helps to records patient'd ID in the Hospital, i'll show the whole code first,then, I will tell where you will, here is the code
package hospitalsrecord;
import java.util.*;
import java.io.*;
public class HospitalsRecord {
public static Scanner read = new Scanner(System.in);
public static ArrayList nameList = new ArrayList();
public static ArrayList patientAge = new ArrayList();
public static ArrayList Disease = new ArrayList();
public static ArrayList dateHospitalized = new ArrayList();
public static ArrayList roomNumber = new ArrayList();
//adding patient function
public static void AddNewPatient () {
//Ask patient's name
System.out.println("Please enter patient's name:");
String patientName = read.next();
//Ask Patient's age
System.out.println("Please enter patient's age:");
int age = read.nextInt();
//Ask patient's illness
System.out.println("Please enter patient's Disease name (also include accidents eg. Leg broke by Car Accident):");
String illness = read.next();
//Ask patient Hospitalized date
System.out.println("Please enter patient's Hospitalized date(Total days not included):");
String HPTLdate = read.next();
//Ask patient's room number
System.out.println("Please enter patient's hospitalize room number(3 degits):");
int HRN = read.nextInt();
//Confirmation
System.out.println("Doctor, would you like to confirm the following(y/n)?");
System.out.println("Name:" + patientName);
System.out.println("Age:" + age);
System.out.println("Disease:" + illness);
System.out.println("Date Hospitalized (HPTLD):" + HPTLdate);
System.out.println("Room Number:" + HRN);
String Confirm = read.next();
if (Confirm.equals("y")) {
nameList.add(patientName);
patientAge.add(age);
Disease.add(illness);
dateHospitalized.add(HPTLdate);
roomNumber.add(HRN);
} else {
AddNewPatient();
}
}
//Searching patient that listed
public static void searchPatient (){
}
//remove the patient function
public static void removePatient() {
}
//text printing function when strat the program
public static void selectorPage(){
System.out.println("Hello Doctor, welcome to Hospital Recorder v1.0.0");
System.out.println("If you want to add new patient into this recorder type: 'add' in the next blank line line");
System.out.println("If you want to search the patient list type: 'search' in the next blank line");
System.out.println("And, if you want to remove the patient that was out of hospitalizing type: 'remove' in the next blank line");
option = read.next();
}
//text printing simmilar to selecterPage function but perform after function
public static void selecterPageAfterAction() {
System.out.println("Your action has been performed, doctor");
System.out.println("Would you like to perform another action?(y/n)");
choiceSelection = read.next();
if (choiceSelection.equals("y")){
System.out.println("If you want to add new patient into this recorder type: 'add' in the next blank line line");
System.out.println("If you want to search the patient list type: 'search' in the next blank line");
System.out.println("And, if you want to remove the patient that was out of hospitalizing type: 'remove' in the next blank line");
option = read.next();
}
}
//Selection var
public static String option;
public static String choiceSelection;
//Main program
public static void main(String[] args) {
selectorPage();
switch (option) {
case("add"): {
AddNewPatient();
break;
}
case("search"):{
searchPatient();
break;
}
case("remove"):{
removePatient();
break;
}
case("end"):{
break;
}
default: {
System.out.println("Please enter the indentified option");
break;
}
}
if (option.equalsIgnoreCase("end")){
}
}
}
I hope you guys can read every line because it was so so so so complex, but for someone who can read all of it, i'll know that you'll say I still need more time for hard working, no worry i'll spend sometime to get most knowledge from you guys first, but still working hard for program to complete while waiting for answers! anyway the point that I want you guys to focus at this point:
if (option.equalsIgnoreCase("end")){
}
It maybe too blank because I've just newly add it while i'm working on it. So, what I want to know is at the if statement I type option.equalsIgnoreCase("end"), Am I explain the computer to do the following?
1.Compare the the String variable options with the String"end"?
2.Tell the computer to do the action inside if statement's when the String option wasn't the word end?
And please tell me how this method work, i don't clearly understand it. I understand like this "It compare two strings if it wasn't the same then it's result is true" I know my explanation is wrong so could you please help me? thanks again for helping if you can.
option.equalsIgnoreCase("end") - equalsIgnoreCase will ignore whether string is in lower case or uppercase.
So it will enter into if block only when option variable has either end or END.
Your first assumption is correct, you are asking to compare String whether it is equal to end. But Second one is wrong, from above code it will enter and execute statements present inside if only when option is end/END.
If you want to go inside If block when the option is not end then add a not like this if(!option.equalsIgnoreCase("end")).
I Hope this clears your doubt!
The class String has two methods to compare one String to another.
See the example below:
public static void main(String[] args) {
String str1 = "beer";
String str2 = "Beer";
System.out.println(str1.equals(str2));
System.out.println(str1.equalsIgnoreCase(str2));
}
The first method equals() compares str1and str2and takes the case into consideration. Hence, the first comparison results in false, meaning Beer is not equal to beer.
The second method equalsIgnoreCase()does the same, except that it is not case-sensitive. Result of this comparison is true, meaning "ignoring the case, Beer is the same string as beer".
Hope this helps.
I'm wondering if anyone could steer me in the right direction, im just beginning java and i am having trouble with string validation, what i want to do here is repeat the loop for each child, repeat the loop for as many books as you want for each child and then for it to exit when there are no children left. Im struggling with the y/n option and how to make it so that only those two options are valid otherwise the user would be shown invalid option try again. Any help would be greatly appreciated!Really stumped here!
int childcounter=1;
do{
System.out.print("What is your childs first name "+childcounter+" of " +nochild+"?");
cfn=k.next();
System.out.print("What is "+cfn+"'s age?");
cage=k.nextInt();
System.out.println();
do {
System.out.print("What is the title of the book that " +cfn+ "would like?");
btitle=k.next();
System.out.print("Price of '"+btitle+"' ?");
costbook=k.nextDouble();
System.out.println();
System.out.print("Do you want to finish? y/n ");
finished=k.next();
}
while(finished.equals("N") || (finished.equals("n")));
childcounter++;
}
while (childcounter <= nochild); }
Below
System.out.print("Do you want to finish? y/n ");
String finished = k.next();
add
while (!java.util.Arrays.asList("y","n","Y","N").contains(finished)) {
System.out.println(" Invalid option. Try again.");
System.out.print("Do you want to finish? y/n ");
finished = k.next();
}
Using equalsIgnoreCase('n') would reduce the amount of code you have to type.
Use this instead.
while (finished.equalsIgnoreCase('n')
{
//method body here in the style that #halfbit suggested.
childcounter++;
}
I'm trying to figure out how to write this?
Write a Java program that will serve as a basic sales calculator. The program should present the user with a choice of four different products of your choosing in a simple menu. After the user selects a product by entering a character corresponding to a product, the program should prompt the user for the quantity and then calculate the Subtotal, Sales Tax Amount, and Total Sale Amount. The calculations should be performed as follows:
Subtotal = (Price * Quantity)
Sales Tax Amount = Subtotal * Sales Tax Percentage (use 6.5% for the sales tax percentage)
Total Sale Amount = Subtotal + Sales Tax Amount
Be sure to use variables to store temporary values. The program should output the product sold, quantity sold, and the calculated values for Subtotal, Sales Tax Amount, and Total Sale Amount. Your assignment submittal should include your java code which is properly commented, and the class file..
this is what i have so far and not sure if I am on the right track?
import java.util.scanner;
public class Sales //Defines the class
Public static void main (String args[]){
System.out.println("Welcome to Super Shopper");
System.out.println("1) Star Wars DVD");
System.out.println("2) X-box 360 ");
System.out.println("3) I-Pad 3");
System.out.println(“4) 2 liter Soda”);
System.out.println("5) Quit");
Scanner sc = new Scanner (System.in);
System.out.print("Please select item :");
int choice = keyword.nextInt();
Scanner number = new scanner (System.in);
System.out.print("Please select quantity :");
Int choice = quantity.nextInt();
String userInput;
}
}
Since this is a homework question, I won't be providing you with the answer to your problem, but hopefully I will be able to help you in figuring out how to structure your program, as well as explain how to use the Scanner class to gather input from the user. The rest will be up to you.
First you will need to develop the pseudo-code for your main program. Basically a flow of execution based on the events that should happen.
pseudo-code is NOT code that will compile, but is useful in figuring out the structure of a program. Here is the pseudo code for your program.
show greeting with choices.
get choice from user
if choice is valid and choice is not exit
prompt user for quantity
if quantity is valid
calculate total and show it to the user
restart program
if quantity is invalid
prompt user for a valid quantity again
if choice is valid and choice is exit
show exit message and exit program
if choice is invalid
show error message and restart program
Notice that upon successful completion of getting the total cost of a purchase, we "restart the program". If you were more advanced, this might entail calling a function, but my guess is that you are still a beginner, so doing the same thing more than once should remind you of a loop. In this case a while loop.
Thus we can rewrite this pseudocode to the following
done = false
while not done
get choice from user
if choice is valid and choice is not exit
prompt user for quantity
if quantity is valid
calculate total and show it to the user
if quantity is invalid
prompt user for a valid quantity again
if choice is valid and choice is exit
done = true
if choice is not valid
show error message
exit program
Now, notice how when the user inputs an invalid quantity (ie: Something that is not an integer > 1) we ask for a quantity AGAIN. Doing the same thing multiple times? That's right, that means we should probably use another while loop again.
For this second while loop, the basic thinking is, "keep asking the user for a quantity until we have a valid quantity". The simplest way to accomplish this, is to create a boolean variable we call haveQuantity, and loop until that value is true.
Our pseudo-code now becomes:
done = false
while not done
get choice from user
if choice is valid and choice is not exit
haveQuantity = false
while not haveQuantity
prompt user for quantity
get quantity from user
if quantity is valid
haveQuantity = true
calculate total and show it to the user
if choice is valid and choice is exit
done = true
if choice is not valid
show error message
exit program
This should be the general structure of your program. In the following section, I will show you how to properly use the scanner class to get input from the user.
public class EchoInt
{
import java.util.Scanner;
public static void main(String[] args)
{
//Declaration of variables outside the while loop
Scanner scan = new Scanner(System.in); //declaring variables outside of a loop saves space and speeds up execution as the jvm does not need to reallocate space for an object inside the loop.
boolean done = false; //this will be our conditional for the while loop
int input = -1;
while(!done) //while done is equal to false.
{
System.out.println("Please enter a positive int to echo or 0 to exit: ");
if(scan.hasNextInt()) //If the user has inputted a valid int
input = scan.nextInt(); //set the value of input to that int.
else //The scanner does not have a integer token to consume
{
/*
THIS IS IMPORTANT. If the scanner actually does have a token
which was not an int. For example if the user entered a string,
you need to consume the token to prepare to accept further tokens.
*/
if(scan.hasNext())
scan.next(); //Actually consumes the token
input = -1; //This is used to indicate that an invalid input was submitted
}
if(input == 0) //The user chose to exit the program
done = true; //set done to true to kick out of the while loop
else if(input == -1) //This means the user inputed an invalid input
System.out.println("ERROR! Try again."); //show error message
else //The user inputted valid input
System.out.println("echo: "+input); //Echo the int
}
scan.close(); //We are done, so close the scanner
System.out.println("Exiting. Goodbye!"); //Show a goodbye message
System.exit(0); //exit the program. The zero tells us we exited without errors.
}
}
Hope this helps. And feel free to ask more questions.
Stackoverflow really excels when you have a very specific question to ask. As for your requirements, you are asking the user for input thats good. But you are not mapping items to prices or quantities. You are hardcoding in the items position ie "3) I-Pad 3" which will make it harder to get the actual item name later and match it to it's price.