When I run my program and type user input as (A-F) the program does nothing. I'm trying to figure out why when I enter any of the letters A through Z the program doesn't call the method. If I input one of the numbers they will run perfectly fine and call the methods, but the letters are giving me problems for some reason.
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput;
initializeShipList(); // initial ships
initializeCruiseList(); // initial cruises
initializePassengerList(); // initial passengers
// add loop and code here that accepts and validates user input
// and takes the appropriate action. include appropriate
// user feedback and redisplay the menu as needed
do {
displayMenu();
userInput = scnr.nextLine();
if(userInput.equals("1")) {
addShip();
}
if(userInput.equals("2")) {
editShip();
}
if(userInput.equals("3")) {
addCruise();
}
if(userInput.equals("4")) {
editCruise();
}
if(userInput.equals("5")) {
addPassenger();
}
if(userInput.equals("6")) {
editPassenger();
}
if(userInput.toUpperCase().equals("A")) {
printShipList("active");
}
if(userInput.toUpperCase().equals("B")) {
printShipList("name");
}
if(userInput.toUpperCase().equals("C")) {
printShipList("full");
}
if(userInput.toUpperCase().equals("D")) {
printCruiseList("list");
}
if(userInput.toUpperCase().equals("E")) {
printCruiseList("details");
}
if(userInput.toUpperCase().equals("F")) {
printPassengerList();
}
}while(userInput != "x");
}
Related
I just want continue a program when a user presses the y key with a do while loop in this code e.g. while('o'!=='y'). I have also tried this:
public class clac {
do {
System.out.println("\nwant to try again\n press y/n");
String o;
o=sc.next();
} while(!o.contentEquals("y"));
}
use below code if you want to ask question on "y" input :
public static void main(String r[]) throws IOException {
Scanner sc = new Scanner(System.in);
String o;
do {
System.out.println("\nwant to try again\n press y/n");
o=sc.next();
} while(!o.contentEquals("y"));
}
Hope that it is what you are looking for.
Im having difficulty understanding what exactly I should pass my third method in the main class with. Im really just sort of lost at this point. Any help would be awesome. Here is my code that I have written:
Also, here are the directions for boolean method called "getOrder":
Write a method called getOrder that takes an ArrayList of Strings as a parameter (the products ArrayList) and returns a boolean.
In the method body, prompt the user to enter a product name (a String), then check whether the product name exists in the ArrayList of strings.
If it exists, return true, otherwise return false.
public static void main(String[] args) {
// Call your methods here
bannerPrinter();
productBuilder();
getOrder(??); -----------------------------Confused as to what to pass this method with
}
// Write your methods below here
public static boolean getOrder(ArrayList<String> products) {
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
System.out.println("Please enter a product name: ");
String productName = in.nextLine();
if (products.contains(productName)) {
return true;
}
else {
return false;
}
}
public static ArrayList<String> productBuilder() {
ArrayList<String> products = new ArrayList<String>();
products.add("Desktop");
products.add("Phone");
products.add("TV");
products.add("Speaker");
products.add("Laptop");
return products;
}
public static void bannerPrinter() {
System.out.println();
System.out.println("******************************************");
System.out.println("****** Welcome to my eCommerce app! ******");
System.out.println("******************************************");
System.out.println();
}
}
You need to pass an ArrayList<String>. Looking at your code, you build one with productBuilder() which is otherwise unused. So:
ArrayList<String> products = productBuilder();
getOrder(products);
or
getOrder(productBuilder());
BTW, the following code:
if (products.contains(productName)) {
return true;
}
else {
return false;
}
is more easily written as
return products.contains(productName);
You would just pass an ArrayList. Like this:
ArrayList<String> lst = new ArrayList<String>();
lst.add("Phone");
lst.add("Laptop");
getOrder(lst);
You would fill your ArrayList first of course and then pass it.
I am going through the University of Helsinki's Java course and I have a question on one of the examples.
The code in question:
import java.util.Scanner;
public class UserInterface {
private Scanner reader;
public UserInterface(Scanner reader) {
this.reader = reader;
}
public void start() {
while (true) {
String command = reader.nextLine();
if (command.equals("end")) {
break;
} else {
handleCommand(command);
}
}
}
public void handleCommand(String command) {
if (command.equals("buy")) {
String input = readInput("What to buy: ");
System.out.println("Bought!");
} else if (command.equals("sell")) {
String input = readInput("What to sell: ");
System.out.println("Sold!");
}
}
public String readInput(String question) {
while (true) {
System.out.print(question);
String line = reader.nextLine();
if (line.equals("carrot")) {
return line;
} else {
System.out.println("Item not found!");
}
}
}
}
If you choose to buy or sell something that isn't a carrot why does it not run the line directly below the input line in the handleCommand method (printing Bought! or Sold!)? I don't understand how it terminates the conditional in the case that a carrot is not bought or sold. How is the readInput method manipulating the handleCommand method here? Thanks.
The function readInput() is rather oddly defined: it will only return if you enter carrot.
readInput() contains a while loop that keeps looping until the user enters carrot, otherwise it says Item not found! and tries again. The output lines in handleCommand() are only executed when readInput() returns.
Basically your readInput() method returns the String "line" only if the user inputs "carrot" otherwise it will keep on going inside the else part and continue printing "Item not found!". But instead of System.out.println("Item not found!") ,
if you just return that statement then either "carrot" or "Item not found!" will be returned and stored in the "input" variable of handleCommand() method. In that case now it will print your "Bought!" or "Sold!" print statement irrespective whether you choose "carrot" or something else
This question already has answers here:
"Main method not found" error when starting program? [duplicate]
(7 answers)
Closed 8 years ago.
Can someone please help me with the code below it builds without any error but when i Run it i get "Error: Main method not found in class Program, please define the main method as:
public static void main(String[] args)"...
any ideas why ?
import java.util.*;
public class Program
{
// Create an array/database for 100 prizes We can increase this number
private Prize[] prizeDatabase = new Prize[100];
// variable to store the next available position in the database
private int currentArrayPosition = 0;
/**
This method displays the menu to the user
*/
private void DisplayMenu()
{
System.out.println("Please select an option from the following:");
System.out.println("1. Enter details of a prize");
System.out.println("2. Print the details stored for all prizes");
System.out.println("3. Search for a prize by description or value");
System.out.println("4. Quit");
// Get the users selection
String selection = new Scanner(System.in).nextLine();
if (selection.equals("1"))
{
EnterPrizeDetails();
}
else if (selection.equals("2"))
{
PrintPrizes();
}
else if (selection.equals("3"))
{
SearchPrize();
}
else if (selection.equals("4"))
{
// do nothing, console will exit automatically
}
}
/**
Search a prize
*/
private void SearchPrize()
{
System.out.println("Please enter search term and press enter: ");
// get the users search term from the console
String searchTerm = new Scanner(System.in).nextLine();
System.out.println("Your following matches are: ");
// Loop round all the prizes
for (Prize prize : prizeDatabase)
{
if ((prize != null))
{
// if the prize matches the users search criters then print the prize
if (prize.MatchPrize(searchTerm))
{
prize.PrintPrize();
}
}
}
System.out.println();
DisplayMenu();
}
/**
Print all prizes in the database
*/
private void PrintPrizes()
{
System.out.println("The following prizes are in the database: ");
for (Prize prize : prizeDatabase)
{
if (prize != null)
{
prize.PrintPrize();
}
}
System.out.println();
DisplayMenu();
}
/**
Enter a prize and store it into the database
*/
private void EnterPrizeDetails()
{
// Take user input and store it to the enter the prize into the database
System.out.println("Please enter a description of the prize and then enter");
String description = new Scanner(System.in).nextLine();
System.out.println("Please enter the colour of the prize and then enter");
String color = new Scanner(System.in).nextLine();
System.out.println("Please enter a value of the prize and then enter");
String value = new Scanner(System.in).nextLine();
Prize newPrize = new Prize();
newPrize.SetPrizeDetails(description, color, value);
// Check if we can add the prize to our database
if (currentArrayPosition < 100)
{
prizeDatabase[currentArrayPosition] = newPrize;
currentArrayPosition++;
System.out.println("A prize has successfully been added to the database.");
}
else
{
System.out.println("Please contact admin to increase the size of the database");
}
System.out.println();
DisplayMenu();
}
static void main(String[] args)
{
Program program = new Program();
program.DisplayMenu();
}
}
class Prize extends Program
{
private String privateDescription;
private String getDescription()
{
return privateDescription;
}
private void setDescription(String value)
{
privateDescription = value;
}
private String privateColor;
private String getColor()
{
return privateColor;
}
private void setColor(String value)
{
privateColor = value;
}
private String privateValue;
private String getValue()
{
return privateValue;
}
private void setValue(String value)
{
privateValue = value;
}
public Prize()
{
}
/**
Setter method to set all the prize details
#param description
#param color
#param value
*/
public final void SetPrizeDetails(String description, String color, String value)
{
setDescription(description);
setColor(color);
setValue(value);
}
/**
Check if a search term matches the prize
#param searchTerm
#return
*/
public final boolean MatchPrize(String searchTerm)
{
boolean match = false;
// Check if the search matches colour or value and return true if it does
if (searchTerm.equals(getColor()) || searchTerm.equals(getValue()))
{
match = true;
}
return match;
}
/**
Print out the details of the prize
*/
public final void PrintPrize()
{
System.out.println("Description: " + getDescription() + " Colour: " + getColor() + " Value: " + getValue());
}
}
When a method don't have a visibility it's package by default. Read here too.
So you should make your
static void main(String[] args)
public.
public static void main(String[] args)
The reason that the compiler don't complain about the public is because it doesn't care about the main method. It doesn't take difference for it if a main exists or not.
It's the JVM which need a start point public and static to launch your application.
Try to make other methods named main and you will see you don't have problems. main is a name like others.
The signature for a method to be used as an entry point for a java application is public static void main(String[] args).
But if the class isn't meant to be used as entry point, static void main(String[] args) is also a valid method signature - so the compiler doesn't complain.
The compiler doesn't know that you want to use the method as the entry point.
Your main method must be declared as public so that it can be accessed by the JVM (Java Virtual Machine) that actually executes the Java bytecode. Java bytecode is what results from compiling the code you write.
The JVM is programmed to look for a specific signature for the main method before executing the program. It finds this signature by looking for a specific series of bytes in the bytecode. That signature only results from compiling a method that is - public static void main. If any of the three modifiers (public, static and void) are omitted the bytecode code will look different and the JVM will not be able to find your main method.
You would not find this error when you compile the program because technically there is nothing illegal about having a method called "main." Main is not a reserved word in Java so there's nothing stopping you from using it as a method (or variable) title. The error will only be detected at runtime when the JVM actually tries to execute the code and cannot find a main method with the appropriate signature.
My code so far:
import java.util.*;
import java.util.Scanner.*;
public class Project{ // The Main Method
public static void main(String [] args){ // Creates the Main Method
System.out.println("Name a Method (Stability, efficiency ..)"); // Asks the user to select a method
Scanner scan = new Scanner(System.in); // Creates the Scanner
String splash = scan.nextLine(); // Transitions the user to the next line after choosing a method
if(splash.equals("efficiency")) // If users chooses Efficiency then it goes to the Efficiency method
{
efficiency(); // Calls the Efficiency method
}
if(splash.equals("Stability")) // If user chooses Stability then it goes to the Stability Method
{
stable(); // Calls the Stability method
}
else // What happens if the input wasnt recognized
{
System.out.println("I don't recognize this"); // what happens if an irrelevant method is chosen
}
}
}
How would I make it so that instead of:
else // What happens if the input wasnt recognized
{
System.out.println("I don't recognize this"); // what happens if an irrelevant method is chosen
}
It will refresh or restart the main method?
Wrap your code in a while loop which you leave when the user chooses the exit command:
public static void main(String [] args){
while (true) {
System.out.println("Name a Method (Stability, efficiency ..)");
Scanner scan = new Scanner(System.in);
String splash = scan.nextLine();
if (splash.equals("exit")) {
break;
} // else if (splash.equals("efficiency")) ...
}
}