cannot find symbol errors - java

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.

Related

A right way to use Scanner and Random in Switch-statement with Try/catch

I'm trying to make a text-based game in Java. and I am going to have a lot of switch-statement with scanner, but I'm not sure which way would be the best.
What would be a best way to make switch-statement with Scanner?
is try+catch better? or do loop?
and if I have, let's say, 10 switch-statement. Is it better to have 10 different Scanner declared for each switch-statements?
I like to have try+catch styled switch-statement with individual Scanner in it, but someone said that it is not necessary, and take too much wasting memory this way. I prefer to recall the method when a wrong type input was put in, and I think try+catch was better in this way because when it was recalled it also recalled Scanner and Random, giving us a chance to reset the input a User put in and also the randomly generated number by Random.
These code down here are examples.
and is the code here not a good code?
(just when it comes to the try+catch, scanner usages)
public static void levelUpAsk_111(Character chosenMember) {
try {
Random rand = new Random();
Scanner sc = new Scanner(System.in);
int dicePercent = rand.nextInt(6) + 1;
int num = sc.nextInt();
if (num == dicePercent ) {
System.out.println("** Congratulation!!");
sc.nextLine();
System.out.println("**Which one would you like to increase?");
System.out.println("1. +20 HP");
System.out.println("2. +10 MP");
System.out.println("3. +5 ATT");
levelUpAsk_222(chosenMember); //the second method
} else if (num > 7 || num < 1) {
System.out.println("Please from 1 to 6");
levelUpAsk_111(chosenMember); //recall itself
} else {
System.out.println("** Sorry..");
sc.nextLine();
}
} catch (InputMismatchException e) {
System.out.println("Please integer only");
levelUpAsk_111(chosenMember); //recall itself
}
}
public static void levelUpAsk_222(Character chosenMember) {
try {
Scanner sc = new Scanner(System.in);
int select = sc.nextInt();
switch (select) {
case 1:
System.out.println("** HP has increased by 20.");
break;
case 2:
System.out.println("** MP has increased by 10.");
break;
case 3:
System.out.println("** ATT has incrased by 5.");
break;
default:
System.out.println("From 1 to 3");
levelUpAsk_222(chosenMember); //recall itself
break;
}
} catch (InputMismatchException e) {
System.out.println("Only integer please"); //recall itself
levelUpAsk_222(chosenMember);
}
}
For switch statements, you do not need to create a new Scanner object each time you want to use it. You can declare it once at the beginning of each method. It is more confusing if you have to deal with multiple Scanner objects in your code than if you only have one.
You can create use a switch looping menu with a default: to catch the unlisted inputs. For example
switch (option){ //assuming you declared option to an int and user has inputted a value for it
case 1:
{
//put some code here
break;
}
case 2:
{
//put more code here
break;
}
case 0:
{
//used to exit the loop
break;
}
default:
{
System.out.println("Please enter a integer only");
levelUpAsk_111(chosenMember); //you can do it this way, or use a do-while looped switch menu that keeps asking until a valid int is input
}
}

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

Calling methods from other methods in the same class

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

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.

how can i get an object from one if condition to another if condition in java?

I'm a beginner. In the below program i want to use display methods in an if condition by using the object which i created in another if condition. Is there any possible way?
package emp;
import java.util.*;
import emp.*;
public abstract class EmpMain2
{
public static void main(String args[])
{ Class cl=new Class();
System.out.println("1:Create");
System.out.println("2:Display");
System.out.println("3:Raisesalary");
System.out.println("4:Exit");
System.out.println("-------------------");
System.out.println("Enter choice:");
Scanner s1=new Scanner(System.in);
int i=s1.nextInt();
System.out.println("-------------------");
if(i==1)
{
System.out.println("1:Clerk");
System.out.println("2:Programmer");
System.out.println("3:Manager");
System.out.println("4:Exit");
System.out.println("-------------------");
System.out.println("Enter Choice:");
Scanner s2=new Scanner(System.in);
int j=s2.nextInt();
System.out.println("-------------------");
if(j==1)
{
System.out.println("Enter Name:");
Scanner s3=new Scanner(System.in);
String str1=s3.next();
System.out.println("Enter age:");
Scanner s4=new Scanner(System.in);
int i1=s4.nextInt();
Cleark c1=new Cleark(str1,i1);
System.out.println("Do u want go to main menu again:");
System.out.println("If yes press 1:");
Scanner s10=new Scanner(System.in);
int l=s10.nextInt();
if(l==1)
{
main(args);
}
else
{
System.exit(0);
}
}
if(j==2)
{
System.out.println("Enter Name:");
Scanner s5=new Scanner(System.in);
String str2=s5.next();
System.out.println("Enter age:");
Scanner s6=new Scanner(System.in);
int i2=s6.nextInt();
Programer p1=new Programer(str2,i2);
System.out.println("Do u want go to main menu again:");
System.out.println("If yes press 1:");
Scanner s11=new Scanner(System.in);
int l=s11.nextInt();
if(l==1)
{
main(args);
}
else
{
System.exit(0);
}
}
if(j==3)
{
System.out.println("Enter Name:");
Scanner s7=new Scanner(System.in);
String str3=s7.next();
System.out.println("Enter age:");
Scanner s8=new Scanner(System.in);
int i3=s8.nextInt();
Manager m1=new Manager(str3,i3);
System.out.println("Do u want go to main menu again:");
System.out.println("If yes press 1:");
Scanner s12=new Scanner(System.in);
int l=s12.nextInt();
if(l==1)
{
main(args);
}
else
{
System.exit(0);
}
}
if(j==4)
{ System.out.println();
main(args);
}
}
if(i==2)
{
System.out.println("---------------------");
//i want to use c1,m1 and p1 objects here
System.out.println("---------------------");
}
if(i==3)
{ System.out.println("----------------------");
//i want to use c1,m1 and p1 objects here
System.out.println("----------------------");
}
if(i==4)
{
System.exit(0);
}
System.out.println(Emp2.inc);
}
}
To access a variable, the variable must be in the same scope (i.e. in the same block delimited by curly braces), or in a block of a larger scope (i.e. in a block containing the current block):
{
int i = 1;
// i can be used here
{
// i can be used here
}
}
// but i can not be used here
{
// and i can't be used here either
}
So no, that's not possible with your current code. The variables would have to be declared in an outer block.
But even if they were, since they're initialized in a block that is executed if i==1, and you want to use them in a block that is executed if i==2, I don't see how you could use them. i can't be equal to 1 and 2 at the same time.
Finally, a note on your code: choose meaningful variable names. Use real words which describe what your variable represents. i, c1, m1, p1 don't mean anything and make your code unreadable.
you can globally declare the reference and then create object whenever you want and then point that created object with that global reference that you created early.
for eg:
class Abc
{
Scanner s; //creating global reference of type Scanner
if(//someCondition)
{
s = new Scanner(System.in); //creating new object of type Scanner and pointing it to reference s
}
if(//someOtherCondition)
{
String str = s.next(); // using that reference in another block
}
}
i think that you understand that if not please comment without hesitation and if it is your answer then mark it as answered so that it no longer remain in the category of unanswered.
instead of using separated ifs you should use switch case:
switch(i){
case 1:
<codes>
break;
case 2:
<codes>
break;
.
.
.
default:
<codes>
}
Also, you have to define objects out of switch to access inside of cases

Categories

Resources