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());
}
Related
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();
}
}
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 need help calling my method. It says "the method fahrtoCel" is undefined for the "TempConversion".
import java.util.Scanner;
public class TempConversion {
public static void main(String[] args) {
System.out.println("===CONVERTING TEMPERATURE=====");
ConvertTemp();
}
private static void ConvertTemp(){
Scanner s = new Scanner(System.in);
System.out.println("Press 1: Convert Celcius to Fahrenheit\nPress 2: Convert Fahrenheit to Celcius\n");
int select = s.nextInt();
if (select==1){
System.out.print("Enter the fahrenheit: ");
celtoFahr();
} else if (select==2){
System.out.print("Enter the celcius: ");
fahrtoCel();
} else{
System.out.println("exit");
}
private static void celtoFahr(){
double temperature = s.nextDouble();
double celcius = 5.0/9.0*(temperature-32);
}
private static void fahrtoCel(){
double temperature = s.nextDouble();
double fahrenheit = 9.0/5.0*(temperature+32);
}
}
}
You are missing a closing }
private static void ConvertTemp(){
Scanner s = new Scanner(System.in);
System.out.println("Press 1: Convert Celcius to Fahrenheit\nPress 2: Convert Fahrenheit to Celcius\n");
int select = s.nextInt();
if (select==1){
System.out.print("Enter the fahrenheit: ");
celtoFahr();
} else if (select==2){
System.out.print("Enter the celcius: ");
fahrtoCel();
} else{
System.out.println("exit");
}
// add closing curly
}
private static void celtoFahr(){
...
If you do however, s will be out of scope so change your method to accept the Scanner.
e.g.
private static void ConvertTemp(){
Scanner s = new Scanner(System.in);
....
celtoFahr(s);
....
}
private static void celtoFahr(Scanner s){
....
}
If you use an IDE like Eclipse this error will be immediately obvious
Write a java program to accept an unlimited # of double type (variable) expense records with description.
Mean time list in console O/P of the same, and accumulate the total # of entries.
heres my code I have so far
public class Quizz {
public double expense;
public double totalExpenses;
public static void main(String[] args) {
Quizz expenses = new Quizz();
Scanner intScan = new Scanner(System.in);
do
{
System.out.println("Enter an expense");
expenses.expense = intScan.nextInt();
}
while (proceed);
System.out.println("done counting");
}
}
The class definition here is rather weird. You don't really need a class, just a main method to do what you want:
Scanner doubleScan = new Scanner(System.in);
double runningTotal = 0;
do {
System.out.print("Enter an amount (-1 to exit): ");
double expense = doubleScan.nextDouble();
if (expense != -1) runningTotal += expense;
} while (expense != -1);
System.out.println("Total: " + runningTotal);
This question already has answers here:
How to use Scanner to accept only valid int as input
(6 answers)
Closed 7 years ago.
This is my current code. What I would like to do is limit the users input to only int. If a double is entered, I'd like a line printed "Please enter a whole number." I've tried to play around with scanner.hasNextint but haven't had much success. Is there a way to ignore double as an input entirely and have it round?
Thanks in advance!
public class BMI extends DecimalFormat{
public static void main(String[] args) {
int weight;
int height;
double bodyMassIndex;
DecimalFormat dfWithTwoDecimalPlaces;
Scanner scanner;
scanner = new Scanner(System.in);
System.out.print("What is your weight in kilograms (kg): ");
weight = scanner.nextInt();
System.out.print("What is your height in centimeters(cm): " );
height = scanner.nextInt();
bodyMassIndex = (weight / Math.pow(height/100.0, 2.0) );
dfWithTwoDecimalPlaces = new DecimalFormat ("0.00");
System.out.print("Your Body Mass Index is: " + dfWithTwoDecimalPlaces.format(bodyMassIndex));
}
}
Create a user defined method getNextInt() as bellow:
/**get next integer*/
public static int getNextInt(Scanner scanner) {
while (!scanner.hasNextInt()) {
scanner.next();
}
return scanner.nextInt();
}
public static void main(String[] args) {
int weight;
int height;
double bodyMassIndex;
DecimalFormat dfWithTwoDecimalPlaces;
Scanner scanner;
scanner = new Scanner(System.in);
System.out.print("What is your weight in kilograms (kg): ");
weight = getNextInt(scanner);//call user-defined method
System.out.print("What is your height in centimeters(cm): " );
height = getNextInt(scanner);//call user-defined method
bodyMassIndex = (weight / Math.pow(height/100.0, 2.0) );
dfWithTwoDecimalPlaces = new DecimalFormat ("0.00");
System.out.print("Your Body Mass Index is: " + dfWithTwoDecimalPlaces.format(bodyMassIndex));
}
You can add a message inside while loop like this:
while (!scanner.hasNextInt()) {
scanner.next();
System.out.println("Please enter a whole number");//message
}
1.use try {} catch{} block (reference java exception handling)
public class MySource extends DecimalFormat{
public static void main(String[] args) {
int weight;
int height;
double bodyMassIndex;
DecimalFormat dfWithTwoDecimalPlaces;
Scanner scanner;
scanner = new Scanner(System.in);
while(true) {
try {
System.out.print("What is your weight in kilograms (kg): ");
weight = scanner.nextInt();
System.out.print("What is your height in centimeters(cm): " );
height = scanner.nextInt();
break;
}catch(InputMismatchException e) {
System.out.println("Please enter a whole number.");
scanner.nextLine();
}
}
bodyMassIndex = (weight / Math.pow(height/100.0, 2.0) );
dfWithTwoDecimalPlaces = new DecimalFormat ("0.00");
System.out.print("Your Body Mass Index is: " + dfWithTwoDecimalPlaces.format(bodyMassIndex));
}
}