I want to know how I can access a call a method when it has an arraylist as an argument from an another class.
import java.util.*;
class Business
{
public static void main()
{
Scanner si = new Scanner(System.in);
int t = 0;
System.out.println("Enter--");
System.out.println("1 to add a account");
System.out.println("2 to check the balance");
int d = si.nextInt();
if(d==1)
{
add_account();
}
if(d == 2)
{
check();
}
}
public static void add_account()
{
Scanner si = new Scanner(System.in);
int min = 1000;
int max = 9999;
int acn;
List<Double> ac = new ArrayList<>();
List<Integer> cl = new ArrayList<>();
List<String> al = new ArrayList<>();
System.out.println("Enter the name of the account user");
al.add(si.next());
System.out.println("Enter the amount user has deposited");
cl.add(si.nextInt());
ac.add(Math.floor(Math.random() * (max - min + 1) + min));
System.out.println("Please re-enter your name");
String name = si.next();
acn = al.indexOf(name);
System.out.println("Your account number is "+acn);
System.out.println("Your account password is "+ac.get(acn));
System.out.println(ac);
main();
}
public static void check(List<Double> ac)
{
Scanner si = new Scanner(System.in);
System.out.println("Enter the account number whoose you want to check the balance");
int c = si.nextInt();
System.out.println(ac);
}
}
Here, I want to know how to access the check method, I think I have to write in something in the brackets . If so, can you tell me what to write, if not please tell how can I access the check method from the main method.
The simplest solution would be to move the 3 lists storing the user data from the add_account to the class level as static variables like this:
public class Business {
private static List<Double> ac = new ArrayList<>();
private static List<Integer> cl = new ArrayList<>();
private static List<String> al = new ArrayList<>();
public static void main() {
//...
}
public static void add_account() {
//...
}
public static void check() {
//...
}
}
This way you can remove the input parameter from the check method and just access the class level ac list.
However a better solution would be to model the account as dedicated class like
public class Account {
String name;
Integer balance;
String password;
// getters + setters
}
and store them in a Map where the key is the accounts name/id
private static Map<String, Account> accounts = new HashMap<>();
I'm trying to understand the code
public static void check(List<Double> ac)
{
Scanner si = new Scanner(System.in);
System.out.println("Enter the account number whoose you want to check the balance");
int c = si.nextInt();
System.out.println(ac);
}
here you declare the method with a parameter of a List. So you cannot call this method without giving a parameter inside. If you want to search the account inside of the method, you can just remove the parameter of the method, get the account and display it.
public static void check() //parameter removed
{
Scanner si = new Scanner(System.in);
System.out.println("Enter the account number whoose you want to check the balance");
int c = si.nextInt(); // get the account number
List<Double> account = new ArrayList<Double>();
// ... some operation
System.out.println(account.toString());
}
After that inside of the main method, you can call this method
public static void main()
{
Scanner si = new Scanner(System.in);
int t = 0;
System.out.println("Enter--");
System.out.println("1 to add a account");
System.out.println("2 to check the balance");
int d = si.nextInt();
if(d==1)
{
add_account();
}
if(d == 2)
{
check();
}
}
Related
I have 2 methods in Java.
In the first method, I am asking the user to make a choice, then i want to store this choice for using in the future.
The second method I wrote only to call the first one to use this choice.
Now, I want to use this variable and add it into an ArrayList. Is it possible to do it?
public static void letUserChooseAgain () {
System.out.println("Please choose an option (1/2):");
System.out.println("1. Dollars to Pounds");
System.out.println("2. Pounds to Dollars");
Scanner scanner = new Scanner(System.in);
double userChoice = scanner.nextDouble();
userChoiceToRemember(userChoice);
}
public static void userChoiceToRemember (double number) {
double remember = number;
}
I belive, I understood your requirement properly if it is kindly find the source code
It can be proposed in two different approach:
APPROACH 1
import java.util.ArrayList;
static ArrayList < Double > numbers = new ArrayList < Double > ();
public static void letUserChooseAgain ()
{
System.out.println ("Please choose an option (1/2):");
System.out.println ("1. Dollars to Pounds");
System.out.println ("2. Pounds to Dollars");
Scanner scanner = new Scanner (System.in);
double userChoice = scanner.nextDouble ();
numbers.add (userChoice);
userChoiceToRemember (userChoice);
}
public static void userChoiceToRemember (double number)
{
double remember = number;
System.out.println ("Remembered User Choice :" + numbers.get (0));
}
APPROACH 2
import java.util.ArrayList;
static ArrayList < Double > numbers = new ArrayList < Double > ();
public static void letUserChooseAgain ()
{
System.out.println ("Please choose an option (1/2):");
System.out.println ("1. Dollars to Pounds");
System.out.println ("2. Pounds to Dollars");
Scanner scanner = new Scanner (System.in);
double userChoice = scanner.nextDouble ();
userChoiceToRemember (userChoice);
}
public static void userChoiceToRemember (double number)
{
double remember = number;
numbers.add (remember);
System.out.println ("Remembered User Choice :" + numbers.get (0));
}
I hope the above code will help you, have a nice day !!
If i understand you right you want to safe the number in a array like this?
Array<Double> numbers = new Array<>();
public static void letUserChooseAgain () {
System.out.println("Please choose an option (1/2):");
System.out.println("1. Dollars to Pounds");
System.out.println("2. Pounds to Dollars");
Scanner scanner = new Scanner(System.in);
double userChoice = scanner.nextDouble();
userChoiceToRemember(userChoice);
}
public static void userChoiceToRemember (double number) {
double remember = number;
numbers.add(number);
}
You need to create a data structure that will keep the value that needs to be shared . Normally, it is done by defining a class that have members that keep the data needed by the class and methods that can access and change the members. This simple java class with members and accessor methods is called Java Bean.
Another option in your case is to have a static variable of type ArrayList<Double> to keep user choices.
I would go for a simple class that keeps user choices with a ArrayList<Double> member. An additional class would be the one that controls the flow of your program using the input provided by the user.
In your main class - the entry point to your program you woould need to instantiate both the class that controls the flow and the one that stores the user choices.
Either give it an ArrayList to add to:
public static void letUserChooseAgain () {
Scanner scanner = new Scanner(System.in);
double userChoice = scanner.nextDouble();
ArrayList<Double> myArrayList = new ArrayList<Double>()
userChoiceToRemember(userChoice, myArrayList);
}
public static void userChoiceToRemember (double number, ArrayList<Double> anArrayList) {
anArrayList.add(number);
}
Have the method create it's own
public static void letUserChooseAgain () {
Scanner scanner = new Scanner(System.in);
double userChoice = scanner.nextDouble();
ArrayList<Double> userChoiceInList = userChoiceToRemember(userChoice);
}
public static ArrayList<Double> userChoiceToRemember (double number, ArrayList<Double> anArrayList) {
ArrayList<Double> myArrayList = new ArrayList<Double>()
myArrayList.add(number);
return myArrayList;
}
or add it to the ArrayList outside of the loop
public static void letUserChooseAgain () {
Scanner scanner = new Scanner(System.in);
double userChoice = scanner.nextDouble();
ArrayList<Double> myArrayList = new ArrayList<Double>()
myArrayList.add(userChoiceToRemember(userChoice));
}
public static void userChoiceToRemember (double number) {
return number;
}
That's assuming there's a good reason you can't just:
public static void letUserChooseAgain () {
Scanner scanner = new Scanner(System.in);
ArrayList<Double> myArrayList = new ArrayList<Double>()
myArrayList.add(scanner.nextDouble());
}
So my project is to make a small poker game that will ask users their name, how many players, and your bets.
However before all this, we need to ask the player if they would like to play a NEW game or a SAVED game. The saved game can be hard-coded.
I created a class1 game, and for the saved game file, I created class2. I want class2 to replace the values of class1 but I am not sure how to do this.
The issue is the values of CLASS1 are NOT being replaced by the values of CLASS2 when we call CLASS2. How can I get the variables from CLASS1 to update to CLASS2?
My First Class:
public class NoC2_Musick extends savedGame
{
public static void main(String[] args)
{
savedGame obj = new savedGame();
Scanner input = new Scanner(System.in);
Scanner inputString = new Scanner(System.in);
System.out.println("Is this a NEW Game or a PREVIOUS game?");
System.out.println("How many players will join this game?");
int totalPlayers = input.nextInt();
String[] players = new String[totalPlayers];
obj.oldsavedgame();
System.out.println("What is your name and club?");
for (int i = 0; i < totalPlayers; i++) {
players[i] = inputString.nextLine();
}
System.out.println("These are the Players: ");
for (int i = 0; i < totalPlayers; i++) {
System.out.println(players[i]);
}
System.out.println("Place your Bet.");
int bet = input.nextInt();
}
}
My Second Class:
public class savedGame
{
public int oldsavedgame()
{
int totalPlayers = 3;
String[] players;
players = new String[3];
players[0] = "Sofia";
players[1] = "Shawn";
players[2] = "Tomi";
int bet = 100;
System.out.println("Test");
return totalPlayers;
}
public static void main(String[] args)
{
}
}
I think you are missing some key things here. I do not think you should create a new class for storing the old info.
Just write a method that loads the data into instance variables.
Also, you are not reading the answer to the question: is this a new game / previous.
I would do something along these lines (note: It is not complete, but it should get you headed in the right direction, as far as loading a previous game):
public class NoC2_Musick {
int totalPlayers = 0;
ArrayList<String> players = new ArrayList<String>();
int bet = 0;
private void LoadSavedGame() {
totalPlayers = 3;
players.add("Sofia");
players.add("Shawn");
players.add("Tomi");
bet = 100;
}
public NoC2_Musick() {
Scanner input = new Scanner(System.in);
Scanner inputString = new Scanner(System.in);
System.out.println("Is this a NEW Game? (y/n)");
char newGame = input.next().charAt(0);
if(newGame == 'y')
{
System.out.println("How many players will join this game?");
totalPlayers = input.nextInt();
for (int i = 0; i < totalPlayers; i++) {
System.out.println("What is your name and club?");
players.add(inputString.nextLine());
}
}
else {
LoadSavedGame();
}
System.out.println("These are the Players: ");
for (int i = 0; i < totalPlayers; i++) {
System.out.println(players.get(i));
}
System.out.println("The current bet is: " + bet);
System.out.println("Place your Bet.");
int bet = input.nextInt();
}
public static void main(String[] args) {
new NoC2_Musick();
}
}
import java.util.Scanner;
public class ATM {
public static void main(String[] args) throws Exception {
String ATM;
ATM myATM = new ATM();
myATM.go();
ifStatement();
//Main method, declares variables and calls the go() and ifStatement() methds.
}
public void go() throws Exception {
int balance;
Scanner userInput = new Scanner(System.in);
System.out.println("Welcome to online ATM banking\nHow much do you want in your bank account?\nEnter your number");
balance = userInput.nextInt();
//Starts the program and sets a value to the variable "balance".
}
public static void ifStatement() throws Exception {
//Creats if statements that change the outcome of the program depending on what the user as inputte dinto thto the program.
//This has been done using int variables whihc have been converted into strings so that they can communicate wiht the userOption variable, the userOption variable's value has been set to whatever the user inputs int the program.
String Withdraw;
String Deposit;
String Inquire;
String Quit;
String usersOption;
int a = 1;
int b = 2;
int c = 3;
int d = 4;
String s = Integer.toString(a);
String ss = Integer.toString(b);
String sss = Integer.toString(c);
String ssss = Integer.toString(d);
//Declares variables
Scanner userInput = new Scanner(System.in); // Allows user input.
System.out.println("What do you want to do?\n1.Withdraw\n2.Deposit\n3.Inquire\n4.Quit\nEnter your number");
usersOption = userInput.nextLine();//Sets user input to a variable called userOption.
if (usersOption.equals(s)){
System.out.println("*****************************************\n Withdrawl\n*****************************************\nHow much would you like to draw?\nEnter your number");
String withdrawl;
withdrawl = userInput.nextLine();
balance = balance - withdrawl;
}
else {
System.out.println();
}
if(usersOption.equals(ss)) {
System.out.println("*****************************************\n Deposit\n*****************************************\nHow much do you want to deposit?");
userInput.nextLine(); }else {System.out.println();
}
if(usersOption.equals(sss)) {
System.out.println("*****************************************\n Your balance is 100\n*****************************************");
}
else {
System.out.println();
}
if(usersOption.equals(ssss))
{
System.out.println("*****************************************\n Goodbye!\n*****************************************");
System.exit(0); }else {System.out.println();}
}
}
I declared the balance variable in the go() method and now I am trying to store that variable's value in one of my if statements. However, the compiler is telling me that it does not recognize the variable balance. Does anybody know how to resolve this issue?
The reason why you are getting that error is because you are declaring "balance" inside the go() method.
You can set this variable like input in your ifStatement(int balance) or you can define it at the begining of the class.
Just give your balance back from go and give it to ifStatements() as parameter.
Like this go() will return u an integer.
public int go() throws Exception {
Scanner userInput = new Scanner(System.in);
System.out.println("Welcome to online ATM banking\nHow much do you want in your bank account?\nEnter your number");
return userInput.nextInt();
}
Like that you can give your ifStatements() a parameter:
public void ifStatement(int balance) throws Exception {
//Creats if statements that change the outcome of the program depending on what the user as inputte dinto thto the program.
//This has been done using int variables whihc have been converted into strings so that they can communicate wiht the userOption variable, the userOption variable's value has been set to whatever the user inputs int the program.
String Withdraw;
String Deposit;
String Inquire;
String Quit;
String usersOption;
int a = 1;
int b = 2;
int c = 3;
int d = 4;
String s = Integer.toString(a);
String ss = Integer.toString(b);
String sss = Integer.toString(c);
String ssss = Integer.toString(d);
//Declares variables
Scanner userInput = new Scanner(System.in); // Allows user input.
System.out.println("What do you want to do?\n1.Withdraw\n2.Deposit\n3.Inquire\n4.Quit\nEnter your number");
usersOption = userInput.nextLine();//Sets user input to a variable called userOption.
if (usersOption.equals(s)){
System.out.println("*****************************************\n Withdrawl\n*****************************************\nHow much would you like to draw?\nEnter your number");
String withdrawl;
withdrawl = userInput.nextLine();
balance = balance - withdrawl;
}else {System.out.println();}
if (usersOption.equals(ss)) {
System.out.println("*****************************************\n Deposit\n*****************************************\nHow much do you want to deposit?");
userInput.nextLine(); }else {System.out.println();}
if (usersOption.equals(sss)) {
System.out.println("*****************************************\n Your balance is 100\n*****************************************");
}else {System.out.println();}
if (usersOption.equals(ssss)) {
System.out.println("*****************************************\n Goodbye!\n*****************************************");
System.exit(0); }else {System.out.println();}
}
Than you could call it like that:
myATM.ifStatement(myATM.go());
Hope that helps
I am making a game-ish type of thing with three classes, combined. NOT HOMEWORK; hobby.
Codes for three classes:
Runner:
public class CounterGameRunner
{
// instance variables - replace the example below with your own
public static void main(String [] args){
Scanner input = new Scanner(System.in);
CounterGameCounter game = new CounterGameCounter();
System.out.println("You want to play a game I see. What is your name?");
String name = input.next();
game.NameIn(name);
CounterGAME game1 = new CounterGAME();
game1.actual();
}
}
Actual Game:
public class CounterGAME
{
// instance variables - replace the example below with your own
Scanner input = new Scanner(System.in);
int number;
int count=1;
boolean loop = true;
public CounterGAME(){
}
public void actual(){
CounterGameCounter game2 = new CounterGameCounter();
System.out.println("Guess a number between 1 and 101, see how many times you get it!");
number=input.nextInt();
int r = (int)(Math.random() * (100) + 1);
while(loop==true){
if(number < r){
System.out.println("Too small, try again");
number = input.nextInt();
count++;
game2.Counter(count);
} else if(number == r){
System.out.println("Wow, you won! Who'd have thought?");
count++;
game2.Counter(count);
break;
System.out.println(game2.done());
} else if(number > r){
System.out.println("Too large, try again");
number = input.nextInt();
count++;
game2.Counter(count);
}
}
}
}
Counter Class:
public class CounterGameCounter
{
// instance variables - replace the example below with your own
private String Name;
String done1;
int correct;
public CounterGameCounter(){
}
public String NameIn (String nm){
Name = nm;
return Name;
}
public String NameOut(){
return Name;
}
public void Counter(int count){
correct = count;
}
public int getCount(){
return correct;
}
public String done(){
done1 = "Name: " + NameOut() + "\n" +
"Times Answered: " + getCount();
return done1;
}
}
Problem:
The counter works properly and everything else displays and functions properly in the end. However, any name I input in the beginning always shows "null" while running the program. Why?
Your variable names are really confusing, and there are a lot of bad practices in your code, but null in name is because you create a new Counter in CounterGAME:
public void actual(){
// here
CounterGameCounter game2 = new CounterGameCounter();
// more code
}
Change actual to receive a CounterGameCounter:
public void actual(CounterGameCounter game2){
// more code
}
And call it like:
public static void main(String [] args){
Scanner input = new Scanner(System.in);
CounterGameCounter game = new CounterGameCounter();
System.out.println("You want to play a game I see. What is your name?");
String name = input.next();
game.NameIn(name);
CounterGAME game1 = new CounterGAME();
game1.actual(game);
// more stuff
}
FREE TIPS:
use String getName() and void setName(String)
start variable, object and attribute names with lowercase
String name;
Object object;
Variable names must be representative and descriptive
CounterGameCounter counterGameCounter = new CounterGameCounter();
This is also applicable to Object names:
GameCounter gameCounter = new CounterGameCounter();
try this:
String name = input.nextLine();
instead of:
String name = input.next();
Ok so, this is whats going on. I'm making a simple simple bank program.
This is what I want to do, notice the variables for my Account class (a1, a2, a3)
This works perfectly fine, but not for what I want to do.
In the switch cases, I want to be able to let the user input the name under the account and be able to edit it.
Now, I know if I were to basically do this:
Account AccountObject = new Account ();
balance.put (sc.nextLine(), AO.addFunds)
Then I would have separate users, but the funds would essentially all be the same. How would I make them separate*
I know once I figure out how to do this, I'll be set to move on to more complicated projects.
import java.util.Hashtable;
import java.util.Scanner;
class Data {
public static void main(String args[]) {
Hashtable<String, Double> balance = new Hashtable<String, Double>();
Scanner sc = new Scanner(System.in);
Scanner sa = new Scanner(System.in);
boolean quit = false;
boolean quit2 = false;
// Create account variables
Account a1 = new Account();
Account a2 = new Account();
Account a3 = new Account();
Account a4 = new Account();
Account a5 = new Account();
// Add funds to variables in Hashtable
balance.put(sc.nextLine(), a1.addFunds());
balance.put(sc.nextLine(), a2.addFunds());
balance.put(sc.nextLine(), a3.addFunds());
balance.put(sc.nextLine(), a4.addFunds());
balance.put(sc.nextLine(), a5.addFunds());
do {
System.out.println("Menu: \n 1: Check balance\n 2: Add funds\n 3: Withdraw funds\n 4: Quit");
int input = sa.nextInt();
switch (input) {
case 1:
System.out.println(balance.get(sc.nextLine()));
break;
case 2:
System.out.println(balance.put(sc.nextLine(), a1.addFunds()));
break;
case 3:
System.out.println(balance.put(sc.nextLine(), a1.withdrawFunds(sa.nextDouble())));
break;
case 4:
quit = true;
break;
}
} while(!quit);
System.out.println("Exiting menu");
}
}
Account class
import java.util.Scanner;
public class Account {
int balance;
String name;
public double addFunds() {
Scanner sa = new Scanner(System.in);
double amount = sa.nextDouble();
balance += amount;
return balance;
}
public String Acct(String names) {
Scanner sc = new Scanner(System.in);
name = names;
return name;
}
public double withdrawFunds(double amount) {
balance -= amount;
return balance;
}
public String toString() {
return String.format("Balance: %n", balance);
}
}
You should create an Account class, which is model for an account. I suggest you do not handle the user input inside the Account class.
Account class
public class Account {
private String name;
private int balance;
public Account(String name, int startBalance) {
this.name = name;
this.balance = startBalance;
}
public void addFunds(int amount) {
if (amount < 0) {
throw new IllegalArgumentException("Amount must be absolute");
}
this.balance += amount;
}
public void withdrawFunds(int amount) {
if (amount < 0) {
throw new IllegalArgumentException("Amount must be absolute");
}
else if (amount > this.balance) {
throw new IllegalArgumentException("You don't have that, so you cannot grab that.");
}
this.balance -= amount;
}
public String getName() {
this.name;
}
public int getBalance() {
return this.balance;
}
}
Now, if you want, you can create some accounts and add them to an ArrayList<Account>. I do not know why you would use a HashMap: if you have just a list with all Account objects, you have all information you need.
ArrayList<Account> accounts = new ArrayList<Account>();
Scanner sc = new Scanner(System.in);
You can implement your user input like something like:
private static ArrayList<Account> accounts = new ArrayList<Account>();
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
initializeSomeBankAccounts();
displayUI();
}
private static void initializeSomeBankAccounts() {
for (int i = 0; i < 2; i++) {
System.out.print("Insert " + (i > 0 ? "another " : "") + "account name: ");
String name = sc.nextLine();
System.out.print("Insert start balance: ");
int startBalance = sc.nextInt();
sc.nextLine();
// Create a new account using the user input
Account account = new Account(name, startBalance);
// Add the account to our list with accounts.
accounts.add(account);
}
}
public static void displayUI() {
boolean quit = false;
while (!quit) {
// Show a menu with the available actions
System.out.println("Menu: \n 1: Check balance\n 2: Add funds\n 3: Withdraw funds\n 4: Quit");
int action = sc.nextInt();
sc.nextLine();
Account account;
// Since we ask the user to insert a right account name, we can
// guarantee that the variable 'account' contains an Account
// object.
switch (action) {
case 1:
account = askAccount();
System.out.println(account.getBalance());
break;
case 2:
account = askAccount();
System.out.print("Amount: ");
int amount = sc.nextInt();
account.addFunds(amount);
break;
case 3:
account = askAccount();
System.out.print("Amount: ");
amount = sc.nextInt();
account.withdrawFunds(amount);
break;
case 4:
quit = true;
break;
}
}
}
private static Account askAccount() {
System.out.println("Which account? ");
Account account = null;
boolean accountFound = false;
// Now the user has to input a valid account name, we're going to
// search for that account name in the list. If it is found, we
// have the whole Account object stored into the variable 'account'.
// Otherwise, if it is not found, then we repeat to ask to insert
// an account name, until a account name is given which is present
// in our list.
while (!accountFound) {
String accountName = sc.nextLine();
account = searchAccount(accountName);
if (account == null) {
System.out.println("Account not found. Insert another account:");
}
else {
accountFound = true;
}
}
return account;
}
/**
* Searches an account from our list of all accounts.
*
* #param name The name to search for.
* #return The account if found, or null otherwise.
*/
private static Account searchAccount(String name) {
for (Account account : accounts) {
if (account.getName().equals(name)) {
return account;
}
}
return null;
}
I also got a few suggestions:
You have some variables which are not used, i.e. quit2. You might want to remove them.
As far as I know, you do not need to have two Scanners; one is sufficient, since you can call both nextLine() and nextInt() on the same Scanner.
You have variables starting with an uppercase character, i.e. AccountObject. In Java, it is allowed, but the Java Naming Conventions prescribe that one should start variables with a lowercase letter.
You are using the class Hashtable, but it is recommended to use HashMap<Key, Value>.