Default continue and if else statements - java

I'm using try on my code and it says illegal start of type. I'm using switch statements but default: continue; do not agree with each other I keep getting continue outside of loop. With the else statement it says illegal start type. So what can I do about try, continue, and the else statement.
public class Menu {
private Inventory database;
private char menuItem;
private Scanner input;
private char mode;
int code;
public Menu(Inventory database)
{
this.database = database;
menuItem = 'N';
input = new Scanner(System.in);
}
public Menu(MyArrayList database)
{
this.database = database;
menuItem = 'A';
input = new Scanner(System.in);
}
private void showMenu()
{
if(code == 'A'){
System.out.println();
System.out.println("------------------");
System.out.println("Display Movies : D");
System.out.println("Add Movie : A");
System.out.println("Delete Movie : X");
System.out.println("Select Mode : M");
System.out.println("Exit : E");
System.out.println("------------------");
System.out.println();
System.out.print("Please make your selection: ");
}
else
{
System.out.println();
System.out.println("------------------");
System.out.println("Display Movies : D");
System.out.println("Rent a Movie : R");
System.out.println("Reserve a Movie: S");
System.out.println("Select Mode : M");
System.out.println("Exit : E");
System.out.println("------------------");
System.out.println();
System.out.print("Please make your selection: ");
}
}
private void rentMovie(int productID)
{
int index = database.getIndex(productID);
if( index == -1)
{
System.out.println("There is not such a code.");
}
else
{
if( database.getMovie(index).getIsRented())
{
System.out.println("You cannot rent " + database.getMovie(index).getTitle() + ". It is already rented.");
}
else
{
database.getMovie(index).setIsRented(true);
System.out.println("Please take your movie.");
}
}
}
private void reserveMovie(int productID)
{
int index = database.getIndex(productID);
if( index == -1)
{
System.out.println("There is not such a code.");
}
else
{
if( database.getMovie(index).getIsReserved() )
{
System.out.println("You cannot reserve " + database.getMovie(index).getTitle() + ". It is already reserved.");
}
else
{
if( database.getMovie(index).getIsRented())
{
database.getMovie(index).setIsReserved(true);
System.out.println( database.getMovie(index).getTitle() + " is reserved for you." );
}
else
{
System.out.println( database.getMovie(index).getTitle() + " is available. You can rent it if you like.");
}
}
}
}
try{
if(mode == 'A'){
switch(menuItem){
case 'N':
break;
case 'D':
database.print();
showMenu();
menuItem = input.next().charAt(0);
break;
case 'A':
String title;
System.out.println("Enter movie title, then press enter");//movie title,
title= input.nextLine();
System.out.println("Enter movie code, then press enter");//enter movie code,then press enter
code = Integer.parseInt(input.nextLine());
addMovie(title,code);
menuItem ='N';
break;
case 'X':
System.out.println("");
deleteMovie(code);
menuItem ='N';
break;
case 'M':
selectMode();
menuItem = 'N';
case 'E':
System.out.print("Program terminated.");
System.exit(0);
break;
default:
continue;
}
}
}
else
{
public void run(){
int code;
while(true)
{
switch(menuItem)
{
case 'N':
break;
case 'D':
database.print();
showMenu();
menuItem = input.next().charAt(0);
break;
case 'R':
System.out.print("Please enter product code:");
rentMovie( input.nextInt() );
showMenu();
menuItem = input.next().charAt(0);
break;
case 'S':
System.out.print("Please enter product code:");
reserveMovie( input.nextInt() );
showMenu();
menuItem = input.next().charAt(0);
break;
case 'E':
System.out.print("Program terminated.");
System.exit(0);
break;
default :
showMenu();
menuItem = input.next().charAt(0);
}
}
}
}

You've got else following your try block, and that makes no sense. no, just bad indentation.
Where's your catch block, or finally block? It makes no sense to just have try. Also, you can't just declare a function in the middle of that else block.
Basically, I recommend you re-study the "Java Syntax" chapter of whatever guide you're using, because this code is just all kinds of wrong.

A.. Few pointers..
First of all, your Try doesn't have a catch.
Your case statements lack {} blocks.
And you can't create a method within an else block.
Further to answer your Question: Illegal start of type means you haven't initiated the variable. For example "menuItem"
Edit: To further that, default should be break; not continue;
Edit2: And further your second switch contains a boolean as argument...

With your edit, now showing the issue.
Your Try starts outside of a method body.
reserveMovie is closed just before try starts, and as such is not valid.

Related

How to exit java method

Sorry for the poor title, i didn't know a better paraphrase..
Sooo i am currently writing a Grocery List program and i am stuck on my addItemsToList method. Basically i want it to have to 'exit' points. One of which will bring you back to the main menu of the application and one of which will bring you back to the context menu of that addItemsToList method.
Unfortunately i am completely stuck.
Here is my code for the method:
private static void addItemsToList(){
System.out.println("To which category do you want to add? ");
categoryInstructions();
int choice2 = scan.nextInt();
if(choice2 == 5){ // i am "getting out" here just fine
interact(); // this is the method that instructs everything to happen in the main method
}else {
System.out.println("What do you want to add? Type 'exit' for menu");
i = scan.next(); // this is where the second "exit" point is supposed to be if someone types "exit"
if (i.compareTo(exit) != 0) {
System.out.println("Please enter the quantity ");
int quant = scan.nextInt();
if (choice2 == 1) {
GrocerieList.foodstuffsList.add(i);
GrocerieList.foodstuffsAmount.add(quant);
} else if (choice2 == 2) {
GrocerieList.hygeneList.add(i);
GrocerieList.hygeneAmount.add(quant);
} else if (choice2 == 3) {
GrocerieList.drinkList.add(i);
GrocerieList.drinkAmount.add(quant);
} else if (choice2 == 4) {
GrocerieList.otherList.add(i);
GrocerieList.otherAmount.add(quant);
}
} else {
addItemsToList();
}
}
}
Just for a better understanding here is categoryInstructions():
public static void categoryInstructions(){
System.out.println("Press");
System.out.println(" ");
System.out.println("\t\t" + "(1)" + "\t--\t" + "for foodstuffs");
System.out.println("\t\t" + "(2)" + "\t--\t" + "for hygene");
System.out.println("\t\t" + "(3)" + "\t--\t" + "for drinks");
System.out.println("\t\t" + "(4)" + "\t--\t" + "for others");
System.out.println(" ");
System.out.println("\t\t" + "(5)" + "\t--\t" + "to get back main menu");
}
Now whats happening is that i can exit addItemsToList perfectly fine if choice2 == 5 but i cannot seem to find the logical solution fo exiting if i is equal to "exit". I got it to work quick and dirty with the application first asking for the quantity and then exiting but that isn't quite what i want.
Since i am (obviously) a beginner any other comments on my style or else would also be greatly appreciated!!
You could use a switch case for this purpose, a flag to know when to execute an elegant exit and a while loop to help you stay in the menu until a user provides the correct input.
For instance:
public class Controller {
private GroceriesController groceriesController;
private boolean isRunning; // our flag that will help us to quit the menu
public Controller(GroceriesController groceriesController) {
this.groceriesController = groceriesController;
}
public void run() {
isRunning = true;
while (isRunning) {
clearScreen();
displayLogo();
displayMainMenu();
handleMainMenu(); // method that will do all the job;
}
}
private void handleMainMenu() {
int userChoice = scanner.nextInt();
switch (userChoice) {
case 1:
groceriesController.handleGroceriesMenu();
break;
case 2:
returnItems();
break;
case 0:
isRunning = false; // exit from the menu
break;
default:
System.out.println("Invalid input");
break;
}
}
private void displayMainMenu() {
System.out.println("\n Grocery store:\n"
+ "[1] Buy stuff\n"
+ "[2] Return stuff\n"
+ "[0] Leave store");
}
}
public class GroceriesController {
private boolean isRunning; // same strategy as before
public void handleGroceriesMenu() {
isRunning = true;
while (isRunning) {
clearScreen();
displayLogo();
displayMenu();
handleMenu();
}
}
private void handleMenu() {
int userChoice = scanner.nextInt();
switch (userChoice) {
case 1:
addItemToCart(item);
System.out.println("The item: " + item + "has been added.");
break;
case 2:
removeItemFromCart(item);
System.out.println("The item: " + item + "has been removed.");
break;
case 0:
isRunning = false; // exit from the menu
break;
default:
System.out.println("Invalid input");
break;
}
}
private void displayMenu() {
System.out.println("\n Select:\n"
+ "[1] Buy item\n"
+ "[2] Put back\n"
+ "[0] Leave");
}
}
In this way, you can have multiple menus that are calling each other and at the end, the program finishes on its own, without wild return; or System.exit(0);
Edit: Added one more class for better insight.

How to fix my do while loop in order to have the menu appear again and again until the user presses Letter 'Q'?

Here's my code:
import java.util.Scanner;
// I want to call the menu function in my driver class and in a do while loop .
public class Driver {
public static void main(String[] args) {
do {
Scanner scanner = new Scanner(System.in);
char choice = scanner.next().charAt(0);
} while (choice == 'Q');// How to exit the menue
}
static void createNewEmployee() {
System.out.println("What is the name of employee?");
}
static void process() {
char choice;
switch (choice) {
case 'N':
System.out.println("new employee");
createNewEmployee();
break;
case 'P':
System.out.println("Compute paychecks");
break;
case 'R':
System.out.println("Raise Wages ");
break;
case 'L':
System.out.println("List Employees ");
break;
default:
System.out.println("Error");
}
}
}
Change while (choice == 'q') into while (choice != 'q'). Think of it like "if the user presses anything apart from 'q', carry on".
I think this will help you!!
public static void main(String[] args) {
char choice;
do {
Scanner scanner = new Scanner(System.in) ;
System.out.print("Press Any Key: N -- New, P -- Paycheck, R -- Raise Wages,-- List Employee, Q -- Quit: ");
choice = scanner.next().charAt(0);
process(choice);
} while(choice !='Q');
}
static void process(char choice) {
switch (choice) {
case 'N':
System.out.println("new employee");
break;
case 'P':
System.out.println("Compute paychecks");
break;
case 'R':
System.out.println("Raise Wages ");
break;
case 'L':
System.out.println("List Employees ");
break;
case 'Q':
System.out.println("Thanks!!");
break;
default:
System.out.println("Error");
}
}

I need validation method in java

I need to make atm machine for school project.
I finished all and all is working fine, and i make the validation for the pin because it is string. So my problem is how to make validation for all other methods to check if anything else but numbers is entered to say the user that is wrong and to return him on the start of that method. All variables are stored into array as integers.
So here is my code please help i tried so many things and i cant make it work..
public class Banka {
static Scanner skener = new Scanner(System.in);
static String pin[] = {"1234","2345","3456","4567","5678"};
static String username[] = {"Mate","Nathan","John","Michelle","Angelina"};
static int balance[] = {200,100,250,150,300};
static boolean overdraft[] = {true,true,false,true,false};
static int index;
public static void main(String[] args) {
login();
}
public static void login() {
Date datum = new Date();
System.out.println("" +datum);
System.out.println("------------------------------");
System.out.println("Welcome to the Illuminati Bank \n Please log in with your PIN");
String login = skener.next();
checkpin(login);
for (int i = 0; i< pin.length; i++) {
if (login.matches(pin[i])) {
index = i;
System.out.println("\nWelcome " + username[index]);
Menu();
}
}
System.out.println("Wrong PIN entered, please login again \n");
login();
}
public static void Menu() {
System.out.println("Please select an option");
System.out.println("\n 1.View Bank Statement \n 2.Deposit \n 3.Withdraw \n 4.Change Pin \n 5.Exit \n");
int choice = skener.nextInt();
switch (choice) {
case 1: statement();
break;
case 2: deposit();
break;
case 3: withdraw();
break;
case 4: change();
break;
case 5: exit();
break;
default: System.out.println("Incorrect Choice ");
Menu();
}
}
public static void statement() {
switch(index) {
case 0: case 1: case 2: case 3: case 4:
System.out.println("" +username[index]+ ", your balance is: " +balance[index]+ "€");
if (overdraft[index] == true) {
System.out.println("You are entitled to overdraft");
}
else {
System.out.println("You are NOT entitled to overdraft");
}
Menu();
}
}
public static void deposit() {
System.out.println("" +username[index]+ ", how much you wish to deposit?");
int deposit = skener.nextInt();
balance[index] = balance[index] + deposit;
System.out.println("Thank you, you deposited " +deposit+ "€, now you have " +balance[index]+ "€ total");
depositm();
}
public static void depositm(){
System.out.println("\n 1.Deposit more \n 2.Exit to menu");
int more = skener.nextInt();
switch (more) {
case 1: deposit();
break;
case 2: Menu();
default: System.out.println("Wrong choice, please choose again");
depositm();
}
}
public static void withdraw() {
System.out.println("" +username[index]+ ", how much you wish to withdraw?");
int withdraw = skener.nextInt();
if (overdraft[index] == true) {
balance[index] = balance[index] - withdraw;
System.out.println("Thank you, you withdrawed the money, now you have " +balance[index]+ "€");
Menu();
}
if(overdraft[index] == false && balance[index] >= withdraw)
{balance[index] = balance[index] - withdraw;
System.out.println("Thank you, you withdrawed the money, now you have " +balance[index]+ "€");
Menu();
}
else {
System.out.println("You have insufficient funds \nPlease try again");
withdraw();
}
}
public static void change() {
System.out.println("" +username[index]+ ", do you want to change your pin?");
System.out.println("Press 1 to change or 2 to exit to menu");
int change = skener.nextInt();
switch (change) {
case 1: System.out.println("Please enter new PIN");
pin[index] = skener.next();
System.out.println("You successfully changed your PIN");
Menu();
case 2: System.out.println("Your PIN remains unchanged");
Menu();
default: System.out.println("Wrong choice, please choose again");
change();
}
}
public static void exit(){
System.out.println("Goodbye " +username[index]+ ", Illuminati Bank wish you all the best \n");
login();
}
public static int checkpin(String x){
while(!x.matches("\\d{4}")){
System.err.println("\n Error.\n Please enter 4 digit pin.");
login();
}
return 0;
}
}
so if any one can help me how to validate all other methods with user inputs where is INTs that would be great.
Try this
String input = "xxxx";
int pin;
try{
pin = Integer.parseInt(input);
}catch(NumberFormatException e){
// input contains letters or symbols.
}
Or here's another one using the Character class.
String input = "xxxx";
boolean allDigits = true;
for(char ch: input.toCharArray()){
if(!Character.isDigit(ch)) {
allDigits = false;
break;
}
}
if(allDigits){
// input contains only digits.
}
Edit: Answering this comment.
You can modify your method like this,
public static void checkpin(String x) {
if (x.length() == 4) {
try {
Integer.parseInt(x);
login();
} catch (NumberFormatException e) {
System.err.println("\n Error.\n Invalid pin.");
}
} else {
System.err.println("\n Error.\n Please enter 4 digit pin.");
}
}
this way the method login() is called only if the pin has 4 digits and all the digits are numbers.

How do I go back to my previous menu?

I've looked at everything mentioned about this and if I make a do/while loop it will just repeat the selection. If I make them conditionals instead of a switch it gives me "NoSuchElementException: No line found". Now its also giving me a "NoSuchElementException: No line found" even though I am back to a switch. I just want to know what I'm missing in this code that will let the user back out their first selection (while loop) to make a different one. Here is the code:
public class Zoo {
static FileRead fr = new FileRead();
private static final Scanner scnr = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException {
while (true) {
int userChoice = menu();
while (userChoice == 1) {
// Select Animal
int animal = animalSelect();
String Name = null;
switch (animal) {
case 1:
Name = "Animal - Lion";
break;
case 2:
Name = "Animal - Tiger";
break;
case 3:
Name = "Animal - Bear";
break;
case 4:
Name = "Animal - Giraffe";
break;
default:
userChoice = menu();
break;
} FileRead.readAnimal(Name);
}
while (userChoice == 2) {
// Select Habitat
int animal = habitatSelect();
String Name = null;
switch (animal) {
case 1:
Name = "Habitat - Penguin";
break;
case 2:
Name = "Habitat - Bird";
break;
case 3:
Name = "Habitat - Aquarium";
break;
default:
userChoice = menu();
break;
}
FileRead.readHabitat(Name);
}
// Exit Program
if (userChoice == 3) {
System.out.println("Thank you!");
System.exit(0);
}
// Error for invalid option
else {
System.out.println("ERROR: Invalid Selection");
}
}
}
private static int habitatSelect() {
// Habitat Menu
System.out.println("Which habitat would you like to monitor?");
System.out.println("1. Penguin Habitat");
System.out.println("2. Bird Habitat");
System.out.println("3. Aquarium");
System.out.println("4. Exit");
int userChoice = Integer.parseInt(scnr.nextLine());
return userChoice;
}
private static int animalSelect() {
// Animal Menu
System.out.println("Which animal would you like to monitor?");
System.out.println("1. Lion");
System.out.println("2. Tiger");
System.out.println("3. Bear");
System.out.println("4. Giraffe");
System.out.println("5. Exit");
int userChoice = Integer.parseInt(scnr.nextLine());
return userChoice;
}
private static int menu() {
// Main Menu
System.out.println("WELCOME! Plese choose from the following");
System.out.println("1. Monitor Animal");
System.out.println("2. Monitor Habitat");
System.out.println("3. Exit");
int userChoice = Integer.parseInt(scnr.nextLine());
return userChoice;
}
}
This all reads a from another file in the package. If that code is needed I will also post it.
Tweak your main method as below
public static void main(String[] args) throws FileNotFoundException {
while (true) {
int userChoice = menu();
switch (userChoice) {
case 1: // only for animals
int animal = animalSelect();
String Name = null;
switch (animal) {
case 1:
Name = "Animal - Lion";
break;
case 2:
Name = "Animal - Tiger";
break;
case 3:
Name = "Animal - Bear";
break;
case 4:
Name = "Animal - Giraffe";
break;
default:
System.out.println("ERROR: Invalid Selection");
break;
}
if (Name != null) // read file only if selection is correct
FileReader.readAnimal(Name);
break;
case 2: // only for habitat
int habitat = habitatSelect();
String habitatName = null;
switch (habitat) {
case 1:
habitatName = "Habitat - Penguin";
break;
case 2:
habitatName = "Habitat - Bird";
break;
case 3:
habitatName = "Habitat - Aquarium";
break;
default:
System.out.println("ERROR: Invalid Selection");
break;
}
if (habitatName != null) // read file only if selection is correct
FileRead.readHabitat(habitatName);
break;
case 3 : // only for exit
System.out.println("Thank you!");
System.exit(0);
default:
System.out.println("ERROR: Invalid Selection");
}
}
}
Thus after each sub-menu, the user is returned to the main menu. As for your exception, for now I have added a null check so that the file is read only if the selection is correct.
Also, note that the above code doesn't contain nested loop which increases the performance and also excludes (the slightly messy) recursive call.

Scanner class validation

I am having a bit difficulty with my code. After depositing an amount $30, it is suppose to bring back the Saving Menu
A- Deposit
B - Withdraw
C - Report
D-Return Main menu
Somehow it keeps scanning $30 instead of asking a new input.
Thanks to anyone who will try helping me out.
package Menu;
import java.util.Scanner;
enum Options {
A, B, C, D
}
public class Menu {
public Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
Menu menu = new Menu();
menu.mainMenu();
}
public void mainMenu() {
String userChoice;
boolean quit = false;
do {
System.out.println("Bank Menu" + "\nA: Savings" + "\nB: Checking"
+ "\nC: Exit");
userChoice = sc.next().toUpperCase();
switch (userChoice) {
case "A":
savingMenu savMen = new savingMenu();
break;
case "B":
break;
case "C":
quit = true;
break;
default:
System.out.println("Wrong entry.");
break;
}
System.out.println();
} while (!quit);
sc.close();
System.exit(0);
}
}
package Menu;
import Savings.Savings;
public class savingMenu extends Menu {
Savings sav = new Savings();
public savingMenu() {
String userChoice;
boolean quit = false;
/**
* A - Deposit B - Withdraw C - Report D - Return Menu
*/
do {
System.out.println("Savings Menu" + "\nA: Deposit "
+ "\nB: Withdraw" + "\nC: Report"
+ "\nD: Return to Bank Menu");
userChoice = sc.nextLine().toUpperCase();
switch (userChoice) {
case "A":
sav.makeDeposit();
break;
case "B":
sav.makeWithdraw();
break;
case "C":
sav.doMonthlyReport();
case "D":
quit = true;
super.mainMenu();
default:
System.out.println("Wrong choice.");
break;
}
System.out.println();
} while (!quit);
}
}
With Scanner check there is a next line with hasNextLine()
Ok I found the error or I should say mis-understanding.
One of my class that I deleted in the post was actually causing the havoc.
public void validateDepositAmount() {
boolean isDoubleDigit = false;
System.out.println("How much would you like to deposit?");
//try (Scanner sc = new Scanner(System.in)) {
Scanner sc = new Scanner(System.in);
do {
if (sc.hasNextDouble()) {
totalDeposit = sc.nextDouble();
if(totalDeposit >= 0) {
isDoubleDigit = true;
} else {
System.out.println("Your input must higher than 0.");
sc.nextLine();
}
} else {
System.out.println("Please put an amount.");
sc.nextLine();
}
} while (isDoubleDigit == false);
//} catch (Exception e) {
//e.printStackTrace();
//}
}
So basically I was using Try with resources and it just kept going in a loop.

Categories