Java: variable not initialized - java

i am getting a "variable selection may not have been initialized in displayMenu(selection). and im not sure why. is it not initialized in the displayMenu model or am i missing something? does "selection = keyboard.nextInt" not count as an initialization? im kind of confused at why i am getting this error. here is the code:
import java.util.Scanner;
import java.io.*;
public class LanguageTranslatorIB
{
public static void main(String[] args)
{
// local variable to hold the menu selection
int selection;
do
{
// display the menu
displayMenu(selection);
// perform the selected operation
switch (selection)
{
case 1:
System.out.println("Good Morning.");
case 2:
System.out.println("Buongiorno.");
case 3:
System.out.println("Buenos dias.");
case 4:
System.out.println("Guten morgen.");
case 5:
System.out.println("GoodBye!");
}
}
while (selection != 5);
}
// the displayMenu module displays the menu and gets and validates
// the users selection.
public static void displayMenu(int selection)
{
//keyboard scanner
Scanner keyboard = new Scanner(System.in);
// display the menu
System.out.println(" select a language and i will say good morning");
System.out.println("1. English.");
System.out.println("2. Italian.");
System.out.println("3. Spanish.");
System.out.println("4. German.");
System.out.println("5. End the Program.");
System.out.println("Enter your selection");
// users selection
selection = keyboard.nextInt();
while (selection < 1 || selection > 5)
{
System.out.println ("that is an invalid select.");
System.out.println (" Enter 1, 2, 3, 4, or 5.");
selection = keyboard.nextInt();
}
}
}

When you pass the variable selection into displayMenu the original variable does not change. The variable that is changed inside that method is a copy. Anything you do inside that method has absolutely no effect on the original selection
Therefore selection has not been initialized as is correctly pointed out by the compiler
You need to redesign the displayMenu to return a value which will be assigned to selection. No input to that method is needed
On another note, you probably want to add break after each System.out.println inside the case statements. If you don't the control will fall through to each next case.

Change displayMenu not take a parameter but rather to return the selected int. Assign that to selection:
selection = displayMenu();
and...
public static int displayMenu()
{
int selection = 0;
Scanner keyboard = new Scanner(System.in);
// ....
selection = keyboard.nextInt();
while (selection < 1 || selection > 5)
{
//...
}
return selection;
}

Your primitive variables are passed to methods as copy, not reference. So when you're calling
displayMenu(selection);
this method is only working with the copy within the method, not the variable out of it itself.

in Java local/block variables need to be explicitly initialized at declaration. un-initialized local variables give this error. Ifyou assume that the selection local variable will be given the default value that an int has in Java then you are wrong. The same is not the case with class level variables, the ones which you define in your class as properties. These variables are assigned their default values automatically by compiler.
Since you havent assigned any value to 'selection' before using in later on so you get this error.

In your main method, selection does not store any value at any point. You need to setup displayMenu to return an integer to selection

When you call displayMenu(selection); java passes the value of the selection variable to the displayMenu() method. The variable hasnt been initialized yet.
Then you're trying to set the value of selection variable inside the displayMenu() method.
However, the selection variable that you have as a parameter of the displayMenu() is local to that method and even though the value of the local selection variable is set, the selection variable inside the main method still remains uninitialized.
To tackle this : Create an instance variable.
public class LanguageTranslatorIB
{
int selection;
public static void main(String[] args)
{
displayMenu();
//Rest of the code follows;
}
}
public static void displayMenu()
{
//keyboard scanner
Scanner keyboard = new Scanner(System.in);
// display the menu
System.out.println(" select a language and i will say good morning");
System.out.println("1. English.");
System.out.println("2. Italian.");
System.out.println("3. Spanish.");
System.out.println("4. German.");
System.out.println("5. End the Program.");
System.out.println("Enter your selection");
// users selection
selection = keyboard.nextInt();
while (selection < 1 || selection > 5)
{
System.out.println ("that is an invalid select.");
System.out.println (" Enter 1, 2, 3, 4, or 5.");
selection = keyboard.nextInt();
}
}
}

Related

What is the correct way to bring about a method within my if statement?

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

How can i add the static variable number in a method?

I create a ProductMenu class to perform the add, search, delete and update product tasks and it only use the array. What problem that i face is how to add static variable in a method because i failed to add the maximum number of array after add a product into array. Hope can help and thank you.
public static void addProduct(){
Product product = new Product();
System.out.println("================================");
System.out.println(" Add Product ");
System.out.println("================================");
System.out.println("Product ID :- " + Product.getProdId());
System.out.print("Enter product name: ");
String prodName = input.next();
System.out.print("Enter product price: ");
double prodPrice = input.nextDouble();
product.setProductId(Product.getProdId());
product.setProductName(prodName);
product.setProductPrice((double)prodPrice);
products[productIndex] = product;
numOfArray++; // should be add ?
productIndex++; // should be add also?
ProductMenu.main(null); //back to main
}
My class
public class ProductMenu {
static Scanner input = new Scanner(System.in);
static int productIndex; //should be add after addProduct()
static int numOfArray = 1; //should be add after addProduct()
static Product[] products = new Product[numOfArray];
public static void main(String[] args) {
int menuOption;
do{
menu();
System.out.print("Enter your choice: ");
menuOption = input.nextInt();
switch(menuOption){
case 1:
addProduct();
break;
case 2:
System.out.print("halo" + products[0].toString());
break;
case 3:
break;
case 4:
break;
default:
System.out.print("Invalid option. Please try
again.\n");
break;
}
}while(menuOption!=1 && menuOption!=2 && menuOption!=3 &&
menuOption!=4 );
}
public static void menu(){
System.out.println("================================");
System.out.println(" Product Menu ");
System.out.println("================================");
System.out.println("1. Insert Product\n2. Update Product\n3.
Search Product\n4. Delete Product\n");
}
This is error msg that mean array number already more than limit and why i ask if i not wrong.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at ProductMenu.addProduct(ProductMenu.java:64)
at ProductMenu.main(ProductMenu.java:21)
at ProductMenu.addProduct(ProductMenu.java:68)
at ProductMenu.main(ProductMenu.java:21)
I was wondering whether you could replace array with arraylist in your code. Arraylists are backed by arrays in background and you need not worry about arrayindexoutofbound exception while handling the data
To your problem: I would use an ArrayList or a LinkedList because it has a dynamic size. The size of an array cannot be changed after initialization and yours is set to 1. That will cause problems.
Addition: You do not need to call ProductMenu.main(null); //back to main because your addProduct function is called in the main method and after executing your function your program will continue in the main function.
As you need to use Array only then create one function add() which will first check size of array, if there is space left then add element else create new array of double size , copy all previous elements and add new one at end.
Also as size is static variable you don't have to pass to your method. Your method is also static and both method and variable in same class so you can directly use variable in method.

How to make a ONE static scanner global variable without closing scan constantly and use it within methods and the main method?

I want to create a static scanner but i will like to put the try catch block around it so it can automatically close avoiding resources
leaks and or this exception:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at softwareEngineer.UserApp1.main(UserApp1.java:82)
Essentially I only want to create one static scanner declaration and use it throughout the main program and includes the static methods, at this point my code will require to create separate scanner for each method and you are force "scan.close()". the code below will recieve a exception handling error due to multiple scanner that was open and did not closein the program.
I updated the code now i get null pointer exception
import java.util.Scanner;
public class UserApp1 {
static User currentCustomer = null; //single object
static Scanner scan;
//-------------------------------------------------------
// Create a list, then repeatedly print the menu and do what the
// user asks until they quit
//-------------------------------------------------------
public static void main(String[] args) {
scan = new Scanner(System.in);)//scanner to avoid resource leak
printMenu(); //print menu system from another function
String choice = scan.nextLine(); //reads an input
final String EXIT_now = "0";
final String BACK = "back";
while (!(choice.equalsIgnoreCase(EXIT_now))){
switch(choice) {
case 1: break;
case 2:
currentCustomer = loginInput();<---- errors happens here
if(currentCustomer != null){
System.out.println("You have successfully login");
}
break;
default:
System.out.println("Sorry, invalid choice");
break;
} //ends switch
printMenu(); //print menu system from another function
choice = scan.nextLine(); //reads an input
}//ends while
System.out.println("\t\t GoodBye!\n Thank you for trying our program.");
System.exit(0);
}//ends main
//----------------------------
// Print the user's choices
//----------------------------
public static void printMenu() {
System.out.println("\t\t The User Login System ");
System.out.println("\t\t ======================");
System.out.println("The Menu Options:");
System.out.println("1: Register an Account");
System.out.println("2: Login to your Account");
System.out.println("3: Reset Password");
System.out.println("0: Quit/Exit ");
System.out.println("Please enter your selection > ");
} //ends printMenu
public static User loginInput(){
System.out.print( "\nFollow the Prompts to Log-In to your Account \n ");
System.out.print( "\nPlease enter your userid : \n ");
String userid = scan.nextLine();// <---- errors happens here
System.out.print( "\nPlease enter your password: \n ");
String pass = scan.nextLine();
currentCustomer = AccountList.loginUser(userid, pass);
if (currentCustomer != null)
{
return currentCustomer;
}
return null;
}//ends loginInput
}//ends class*
You're using a try-with-resources, which will automatically close it when you finish the try block. Try setting it to a variable like so:
public class MyClass {
private static Scanner scan;
public static void main(String[] args) {
scan = new Scanner(System.in);
}
}
Avoid making multiple scanners with the System.in input as well, as they will consume the stream and then you have an entirely different problem.
Avoid using a static global Scanner at all, by passing the Scanner instance you want to work with to the relevant methods. Consider this simplified example:
public static void main(String[] args) {
try(Scanner in = new Scanner(System.in)) {
String choice = in.nextLine().trim();
if(choice.equals("1")) {
doOp1(in);
} else if(choice.equals("2")) {
doOp2(in);
} else {
System.err.println("Invalid choice. Goodbye.");
}
}
}
// Method takes an open, functioning Scanner as an argument, therefore
// it doesn't need to close it, or worry about where it came from, it
// simply uses it, does what it needs to do, and returns, trusting
// the caller to properly close the Scanner, since it opened it.
private void doOp1(Scanner in) {
System.out.print("What is your name? ");
String name = in.nextLine().trim();
System.out.print("What is your favorite color? ");
String color = in.nextLine().trim();
}
private void doOpt2(Scanner in) {
...
}
You want to compartmentalize your resources to ensure they are limited in scope and easy to close. Putting them in global state of any kind makes that very difficult. Instead, separate the opening and closing of the resource from the code using it. This sort of compartmentalization makes for much more maintainable, readable, and testable code.
For instance, by passing an already open Scanner to your core business logic functions, you can mock a real user's behavior and create a test to ensure your code remains stable, by constructing a Scanner that reads from a hard coded String, and passing that into your method, without needing to run the whole class and type in the behavior your testing manually again and again.

Calling method from within itself?

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.

Creating a console menu for user to make a selection

Doing a program in Eclipse with Java. What I want to do is when I execute the program I want present the user with a choice. I have all the calculations etc. done, I'm just unsure as to how to make this menu to offer the user choices. Example of what I'm looking for:
To enter an original number: Press 1
To encrypt a number: Press 2
To decrypt a number: Press 3
To quit: Press 4
Enter choice:
public static void main(String[] args) {
Data data = new Data();
data.menu(); }
}
For simplicity's sake I would recommend using a static method that returns an integer value of the option.
public static int menu() {
int selection;
Scanner input = new Scanner(System.in);
/***************************************************/
System.out.println("Choose from these choices");
System.out.println("-------------------------\n");
System.out.println("1 - Enter an original number");
System.out.println("2 - Encrypt a number");
System.out.println("3 - Decrypt a number");
System.out.println("4 - Quit");
selection = input.nextInt();
return selection;
}
Once you have the method complete you would display it accordingly in your main method as follows:
public static void main(String[] args) {
int userChoice;
/*********************************************************/
userChoice = menu();
//from here you can either use a switch statement on the userchoice
//or you use a while loop (while userChoice != the fourth selection)
//using if/else statements to do your actually functions for your choices.
}
hope this helps.
You can use a scanner to read input from System.in, as follows:
public static void main(String[] args) {
Data data = new Data();
data.menu();
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
// Perform "original number" case.
break;
case 2:
// Perform "encrypt number" case.
break;
case 3:
// Perform "decrypt number" case.
break;
case 4:
// Perform "quit" case.
break;
default:
// The user input an unexpected choice.
}
}
Note that this will require the user to input a number and press enter, before continuing execution. If they enter invalid input, this will halt; if you want it to prompt them again, you will need to wrap this in a loop of some sort, depending on how you want the system to behave.
Scanner#nextInt may very well throw an exception, should the user input something that cannot be parsed to an integer. You can catch this exception and handle it appropriately. If the user enters an integer that is out of the range of valid options (i.e. it is not in the range of 1-4), it will fall to the default branch of the switch statement, where you can again handle the error case however you wish.

Categories

Resources