I'm creating a banking app and I need to generate a customer number starting from number 1, keeping track of the number so that it won't repeat itself each time I enter the loop and store it into an int variable that I can use to collect the value and pass it to the customerNumber variable outside the loop. I've tried a few things like arraylists and arrays, but I was getting troubles in passing the values to the variable I wanted. Thanks in advance and sorry for my terrible noobishness...I'm new in programming... Here's what I've got so far:
import java.util.ArrayList;
public class Bank{
public void addCustomer(String name, int telephone, String email, String profession) {
ArrayList customerList = new ArrayList();
Customer customer = new Customer();
customerList.add(customer);
}
}
public class Customer{
private String name;
private int telephone;
private String email;
private String profession;
private int customerNumber;
public Customer() {
}
}
public class Menu {
Scanner sc = new Scanner(System.in);
Bank bank = new Bank();
private void createCustomer() {
String name, email, profession;
int telephone, customerNumber;
System.out.println("Enter the customer's number: ");
name = sc.nextLine();
System.out.println("Enter the customer's telephone: ");
telephone = sc.nextInt();
System.out.println("Enter the customer's email: ");
email = sc.nextLine();
System.out.println("Enter the customer's profession: ");
profession = sc.nextLine();
bank.addCustomer(name, telephone, email, profession);
}
}
One thing you can do is create a singleton class, and request a number each time you need one. The singleton class keeps a list of the numbers that have been used already, and thus can return a number that has not been used before.
If you need also to generate new numbers after your application is restarted, then you can store all numbers in a file, and read that file whenever needed.
A singleton class, is a class that can have max 1 instance. You can achieve this by making the constructor private, and creating a public static method (usually called something like getInstance() ) to get an instance of this class. This getInstance() returns the ref to the only instance, and if no instance was created yet, it first creates one.
Then, this only instance knows all account numbers in use (inyour case), regardless how often an instance of this class is requested.
The responsibility of this class is to maintain the account nrs: create a nr, print them, save them, read them, ...
Example:
private AccoutnNr singleInstance;
private AccountNr(){
}
public AccountNr getInstance(){
if (singleInstance == null) {
singleInstance = new AccountNr();
}
return singleInstance;
}
public int getAccountNr{
// do whatever is needed to create an account nr
}
more methods if you need to do more than creating account numbers
Related
I'm new to java and programming. I am stuck on one section of an assignment given to me in which I have to create a login for two different types of user which will display two different menus depending on which login is used. I am using Eclipse and the console.
The two different types of user are Boss and Worker and they must login using a username and password. The Boss menu must have the following menu options after logging in:
Setup Worker Schedule
View Worker Schedule
Move Worker
The Worker menu must have the following menu options after logging in:
View Schedule
I'd really appreciate any help with this, thanks in advance.
EDIT:
Okay, so I now have the following code:
import java.util.Scanner;
public class Depot {
public static void main(String[] arguments){
String bossName;
String bossPassword;
String workerName;
String workerPassword;
System.out.println("Enter your name: ");
Scanner authenticate = new Scanner(System.in);
String userName = authenticate.nextLine();
System.out.println("Your username is " + userName);
System.out.println("Enter your password: ");
String passWord = authenticate.nextLine();
System.out.println("Your password is " + passWord);
if (userName.equals(bossName) && passWord.equals(bossPassword)) {
int selection;
Scanner bossMenu = new Scanner(System.in);
System.out.println("1. Setup Worker Schedule");
System.out.println("2. View Worker Schedule");
System.out.println("3. Move Worker");
System.out.println("4. Quit");
do {
selection = bossMenu.nextInt();
if (selection == 1) {
System.out.println("1");
}
else if (selection == 2) {
System.out.println("2");
}
else if (selection == 3) {
System.out.println("3");
}
else {
System.out.println("4");
}
}
while(selection != 4);
bossMenu.close();
}
else if (userName.equals(workerName) && passWord.equals(workerPassword)) {
int selection;
Scanner userMenu = new Scanner(System.in);
System.out.println("1. View Worker Schedule");
System.out.println("2. Quit");
do {
selection = userMenu.nextInt();
if (selection == 1) {
System.out.println("1");
}
}
while(selection != 2);
userMenu.close();
}
}
}
However, the following two lines of code are giving me an error:
if (userName.equals(bossName) && passWord.equals(bossPassword)) {
and
else if (userName.equals(workerName) && passWord.equals(workerPassword)) {
bossName, bossPassword, workerName and workerPassword may not have been initialized?
First, get the credentials through using the Scanner, here is a basic way to construct a Scanner object, you will need to have the following import statement at the very beginning of your code, before anything else:
import java.util.Scanner;
To create a Scanner, do the following:
Scanner scannerName = new Scanner(System.in);
That tells the Scanner to read from the input stream, which will be the keyboard. To get data from the Scanner, first prompt the user for the data you need, then use one of the Scanner's .next___ methods to retrieve the input and store in a variable. I'm not going to tell you which one to use, check out the Scanner page in the Java API and see if you can figure it out on your own.
It should look something like this:
System.out.println("Enter your name");
String userLoginString = scannerName.next____();
System.out.println("Enter your password");
String userPasswordString = scannerName.next____();
Once you have the credentials stored in String variables, I'll use userLoginString and userPasswordString as examples, you will need to validate these credentials against some stored values. So, create String variables bossName, bossPassword, workerName, workerPassword.
Once you have the user's credentials, I would perform validation on these login credentials. You could do that using the logical operators and methods of the String class, like so:
if (userLoginString.equals(bossName) && userPasswordString.equals(bossPassword)) {
// print the boss menu
}
else if (userLoginString.equals(workerName) && userPasswordString.equals(workerPassword)) {
// print the user menu
}
The logical && ("and") operator will ensure that the correct menu will be displayed only if the user's credentials match the stored credentials. If the user enters the correct name (boss or worker) but the wrong password (or vice-versa), the statements inside the braces will NOT execute.
UPDATE Here is a commented version of your code so far with some hints as to how to make it better. It will compile and run fine if you just provide values for the String variables at the top, but I have some more suggestions to make it a little nicer:
import java.util.Scanner;
public class Depot {
public static void main(String[] arguments){
// you need to initialize these to some value or else there is
// nothing to compare them with. I tried some dummy values and
// your code worked as expected, as long as the user entered the
// correct values in the prompt.
String bossName;
String bossPassword;
String workerName;
String workerPassword;
// you can just use one Scanner for the whole program, since they are
// both just reading input from the standard input stream. Replace the
// other Scanners with "input" and close "input" at the end
Scanner input = new Scanner(System.in);
System.out.println("Enter your name: ");
// not needed
Scanner authenticate = new Scanner(System.in);
String userName = authenticate.nextLine();
System.out.println("Your username is " + userName);
System.out.println("Enter your password: ");
String passWord = authenticate.nextLine();
System.out.println("Your password is " + passWord);
if (userName.equals(bossName) && passWord.equals(bossPassword)) {
// this could be declared at the top of the program instead of
// redeclaring in the if...else
int selection;
Scanner bossMenu = new Scanner(System.in);
System.out.println("1. Setup Worker Schedule");
System.out.println("2. View Worker Schedule");
System.out.println("3. Move Worker");
System.out.println("4. Quit");
do {
selection = bossMenu.nextInt();
if (selection == 1) {
System.out.println("1");
}
else if (selection == 2) {
System.out.println("2");
}
else if (selection == 3) {
System.out.println("3");
}
else {
System.out.println("4");
}
} while(selection != 4); // this is usually here
bossMenu.close();
}
else if (userName.equals(workerName) && passWord.equals(workerPassword)) {
// this could be declared at the top of the program instead of
// redeclaring in the if...else
int selection;
// don't need this one, just use "input" Scanner
Scanner userMenu = new Scanner(System.in);
System.out.println("1. View Worker Schedule");
System.out.println("2. Quit");
do {
selection = userMenu.nextInt();
if (selection == 1) {
System.out.println("1");
}
} while(selection != 2); // this is usually here
// you would close the "input" Scanner here
userMenu.close();
}
}
}
UPDATED AGAIN!!! A better way to implement the Boss and Worker would be through using inheritance and polymorphism. Start with an abstract superclass that has common characteristics of the Boss and Worker. I'll call this the Employee superclass. It has firstName, lastName, and password instance variables, and you should add getters and setters for each:
// abstract class, CANNOT be instantiated but can be used as the supertype
// in an ArrayList<Employee>
public abstract class Employee {
private String firstName;
private String lastName;
private String password;
public Employee() {
// don't have to do anything, just need this so you can instantiate
// a subclass with a no-arg constructor
}
// constructor that takes only the name of the Employee
public Employee(String firstName, String lastName) {
this(firstName, lastName, null);
}
// constructor that takes name and password
public Employee(String firstName, String lastName, String password) {
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
// and so on, for the lastName and password....
// you must implement this specifically in any subclass!
public abstract void getMenu();
}
Then, your Boss and Worker classes could extends this Employee class and they would have all of the same methods and instance variables. You just must provide an overridden getMenu() method in each, since that one was abstract in the Employee class. Here is a sample of what your Boss class should look like, you need to implement the getMenu() yourself and the Worker class:
public class Boss extends Employee {
// notice we don't need the instance variables in the class declaration,
// but they are here since they are part of Employee
public Boss() {
// don't need to do anything here, just allows no-arg constructor
// to be called when creating a Boss
}
// just calls the superclass constructor, could do more if you want
public Boss(String firstName, String lastName) {
super(firstName, lastName);
}
// just calls the superclass constructor, could do more if you want
public Boss(String firstName, String lastName, String password) {
super(firstName, lastName, password);
}
#Override
public void getMenu() {
// put the print statment for Boss's menu here
}
// don't need to re-implement other methods, we can use them since
// they are part of the superclass
}
Once you have the Employee, Worker, and Boss classes, you're ready to try and re-write your program to Objects in place of simple variables as you were doing before. Here is an example of how that would get started:
import java.util.Scanner;
public class EmployeeTester {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// can make workers and bosses able to be processed polymorphically
// by assinging their references to Employee variables, since
// and Employee is the supertype of each, a Worker "is an" Employee
// and a Boss "is an" Employee.
Employee worker1 = new Worker("Bob", "Worker");
Employee worker2 = new Worker("Sue", "Bush", "Password1");
Employee worker3 = new Worker();
Employee boss1 = new Boss("Jenny", "Boss");
Employee boss2 = new Boss("Bill", "OtherBoss", "Password2");
Employee boss3 = new Boss();
// if you're going to have a lot of workers and bosses, and you don't
// need named variables for each because their info will be included
// in their constructors, you could do this
Employee[] employees = {new Worker("Bob", "Bailey", "myPassword"),
new Worker("Sue", "Sarandon", "123Seven"),
new Boss("Jenny", "Strayhorn", "hardPassword"),
new Boss("Billy", "MeanGuy", "pifiaoanaei")};
// then, you could iterate through this list to check if a password
// entered matches a firstName, lastName, and password combination
// for ANY type of employee in the array, then call the getMenu()
// method on that employee, like so: (This could all be in a loop
// if you wanted to process multiple Employees...)
System.out.println("Enter firstName:");
// you figure out which Scanner method to use!
String firstName = input._____();
System.out.println("Enter lastName:");
String lastName = input._____();
System.out.println("Enter password:");
String password = input._____();
// figure out what get____() method of the Employee class
// needs to be called in each case, and what it should be
// compared to with the .equals() method.
for (int i = 0; i < employees.length; i++) {
if (employees[i].get______().equals(______) &&
employees[i].get______().equals(______) &&
employees[i].get______().equals(______)) {
// if all of those conditions are true, print the menu
// for this employee
employees[i].get_____();
// you could do more stuff here....
// breaks out of the loop, no need to check for anymore employees
break;
}
}
}
}
I have this method addPerson (on the main) which is used to set the name of a person.
private static Person[] addPerson(Person _person[], int _minAge, int _id){
int personAge;
String personName;
Scanner scan = new Scanner(System.in);
System.out.println("What's his age?");
personAge = scan.nextInt();
if(personAge >= _minAge){
if(!_person[_id].getPerson().equals("")){
System.out.println("Person " + _person[_id].getPerson() + " already exists.");
}else{
System.out.println("Enter the name of the person");
Scanner addPerson = new Scanner(System.in);
personName = addPerson.next();
_person[_id].setPerson(personName);
}
}else{
System.out.println("Person is not old enough");
}
return _person;
}
And here is the method setPerson in my custom class which is used to set the name of the person.
public void setPerson(String name){
System.out.println("Person added");
personName = name;
}
I know I should be doing the checking on whether that person already exists inside my setPerson method, but I am sort of confused with this. As you see I am expecting the user to input an integer, so I guess that I should check that right away to not get an error in case he inputs a string.
So my question is which should be checked within the same method and which on the method on my custom class?
Your code (and your question) is a bit confusing, but from what I can understand you want to know if you should check whether a person exists in the array in setPerson() or not?
Well, from what I can gather from your code, you should not do it in setPerson(), because that's a method in the Person class. The Person class shouldn't need to know anything about your array of Person objects.
So the way you're doing it now is probably your best bet.
Some general hints about the code:
There's no need to create a new Scanner, you can just use the one you have. So this
Scanner addPerson = new Scanner(System.in);
personName = addPerson.next();
becomes this
personName = scan.next();
I would also suggest you use the name setName()instead of setPerson()for your method name, it doesn't make sense to have it named one way when what it's actually doing is something else.
I would do it this way. However I don't have java currently so I didn't test this snippet.
class Person {
private String name;
public void setName(String name) {
this.name = name;
}
}
class Main {
private static final int minAge = 22;
private static Map<Person> addPerson(Map<Person> people, int id) {
if(people.containsKey(id)) {
// print that person with this id exists
return people;
}
Scanner scanner = new Scanner(System.in);
int age = scanner.nextInt();
if(age < minAge) {
// print that given age is invalid
return people;
}
String name = scanner.next();
people.get(id).setName(name);
return people;
}
}
I am writing a pension program and I am stuck.
The program looks like this:
First I read in a file where every line has the name of the person, the age, and their first deposit.
I use a method called ReadFile to do that. Inside that method I call upon a class called class savingswhich is in a separate file to calculate their pension.
But I have the following problem: I would like to sort their names according to their pensions (highest to lowest) but I don't know how to do that.
Here is the method in the Readfile class:
#SuppressWarnings("resource")
public void readFile(double rate) {
while(scan1.hasNextLine()) {
String input = scan1.nextLine();
scan2 = new Scanner(input).useDelimiter("/");
String a = scan2.next();
int b = scan2.nextInt();
int c = scan2.nextInt();
// calculate savings
savings s = new savings();
s.totalSavings(a, b, c, rate);
// add savings to an array
}
}
1st, create a class say Person :
class Person{
private String name;
private int age;
private BigDecimal firstDeposit;
private BigDecimal pension;
//Setters and getters method
}
Now Create the List which will hold the information of every Person :
List<Person> personList=new ArrayList<Person>();
Now sort your list based on Pension :
Collections.sort(personList, new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return p1.getPension().compareTo(p2.getPension());
}
});
Given you the hint to go about your problem, but as suggested by other users, kindly go through the basics of java.
I am writing this program that will take in the names, ages and salaries for 5 different people from the user and will put them in an array.
I then want to write a method that will ask the user for another name, age and salary and add that into the array. Also a method that will as for the name of someone who's already in the array and will delete the information of the person with that age from the array.
The first method will increase the array size by 1 and the second will decrease the array size by 1. so far this is what I have:
ArrayList<details> details = new ArrayList<details>();
for(int x = 0; x < 4; x++) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first name: ");
String firstName = scan.nextLine();
System.out.println("Enter the last name: ");
String lastName = scan.nextLine();
System.out.println("Enter the age: ");
int age = scan.nextInt();
System.out.println("Enter the salary: ");
double salary = scan.nextDouble();
details.add (new details(firstName, lastName, age, salary));
}
I don't know how to go about doing this. I need some help!
thanks!
You can have a class Person with the class variables you require (name,age,salary)
class Person {
private int age;
private dobule salary;
private String firstname;
private String lastname;
}
Define the getter and setter methods for each of the class variables. For e.g
public void setAge(int age){
this.age = age;
}
public int getAge(){
return this.age;
}
In your main class read the input from STDIN as you are doing it. Instantiate the Person object for each of the 5 person.
Person employee = new Person();
employee.setAge(x);
employee.setFirstName(x);
employee.setLastName(y);
employee.setSalary(y);
Now, you can add each Person to your list and remove them too.
For removing any Person you would have to search for the Person through the ArrayList by name. That would be iterating over the length of ArrayList and comparing the name of each.
The final class would look like,
public class Solution{
private ArrayList<Person> details = new ArrayList()<Person>;
public static void main(){
// Here you loop for reading from STDIN as you are already doing.
// addPerson() would be used to add to ArrayList and removePerson() for the other
}
public addPerson(String firstName, String lastName, int age, int salary){
//Create the Person object
details.add(<person object>);
}
public removePerson(name){
details.remove(index);
// to get index it would require iterating over the ArrayList.
// It would be better if you use a Map instead (as other suggest)
// with name as the key
}
}
Hope this helps.
dud first of all, i can see that u have used arrayList name & Class name both same so please update that.
secondary use Map in place of Class like in if condition
if(){
Map userDetails = new HashMap();
map.put("firstname",firstname);
..
..
map.put("salary",scan.nextDouble());
details.add(map)
}
and on time of delete iterate ArrayList
for(int i=0;i<details.size();i++){
Map tempMap = details.get(i);
if(temp.get("firstname").toString() == "Given Name"){
}else{
// your logic
}
}
Hope will help you please let me know if any doubts.
use this code for removing employee
void removeEmployee(String name){
for(Employee emp :details){
if(name.equals(emp.getName())){
details.remove(emp);
break;
}
}
}
and do include exception handling
I'm trying to write a program that asks the user for input using the scanner class to name something. Then in a completely different class, reference that input.
For example:
class TeamInfo {
Scanner nScan = new Scanner(System.in);
public String GetName(){
String GetName = nScan.nextLine();
}
The issue I'm having is that the first time I reference the GetName method in the TeamInfo class, it works--At the right spot, it prompts for the team name.
However, it prompts for the team name every time after that. I can't seem to find anywhere online or in my Java Beginner's Guide how to make this input constant, so that I can reference the input. I'm also not entirely sure what it is I'm looking for, so that doesn't help.
In other words, what I want is to prompt the user one time, and then remember that answer and re-use it again and again.
You should make two methods: getName() and promptName() (or whatever names you like best)
One method would be for retrieving the name from the user, and the other would be for retrieving the value that you got from the user:
class TeamInfo {
private Scanner nScan = new Scanner(System.in);
private String name;
public void promptName() {
name = nScan.nextLine();
}
public String getName() {
return name;
}
}
When you want to get the name from the user, you'd call:
TeamInfo info = new TeamInfo();
info.promptName();
And when you wanted to retrieve the name for your uses:
String teamName = info.getName();
Save the result of the input to a field, then return that on request:
class TeamInfo {
private String name;
Scanner nScan = new Scanner(System.in);
public void promptForName() {
System.out.print("Name: ");
this.name = nScan.nextLine();
}
public String getName() {
return this.name;
}
}
You need to store the name you have read fro the Scanner in a class member, then return that class member when calling GetName (). Otherwise you will lose the name you have read, and will have to read it again (and thus prompt the user again for input).
For example:
class TeamInfo {
Scanner nScan = new Scanner(System.in);
String name = null;
public String GetName(){
if (name == null) {
name = nScan.nextLine();
}
return name;
}
On a different note, you should read on Java naming conventions. A method name should not start with a capital letter.