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
Related
I have the class Student with a constructor that sets the values int s_code, String name and int age.
When I create an object of the class Student I pass it into an ArrayList AllStudents.
My problem is that I want the user to enter an Id and check if there is that Id in the ArrayList. If its not let him add a new student else tell him to try again.
I tried to loop through the ArrayList with for and inside of it
I have an if statement with .contains and if it is true I have a simple println("Good") just to test it.
When I run my program though it skips it.
Here is my code:
static ArrayList<Student> AllStudents = new ArrayList<Student>();
static void InitStudents() //this is a method that creates some students when I call it in main.
{
AllStudents.add(new Student(1,"James",15));
AllStudents.add(new Student(2,"John",16));
AllStudents.add(new Student(3,"Rose",15));
}
System.out.println("Enter the ID of the student you want to add.");
Scanner get_new_code = new Scanner(System.in);
int s_code = get_new_code.nextInt();
for(Student code : AllStudents)
{
if (AllStudents.contains(s_code)) //I think that I have to include age and name for it to work.
{
System.out.println("Good");
}
}
By the way sorry if I didn't explain something or I did something completely wrong I'm new to Java.
That advanced loop is not helping you in the way you implemented it.
for(Student code : AllStudents){ //"code" is one element out of the list
if (AllStudents.contains(s_code)){ //here you are checking the whole list
System.out.println("Good");
}
}
This might be what you are looking for:
for(Student code : AllStudents){
if(code.getSCode() == s_code){ //here the one element named "code",
//out of the list, will be checked
System.out.println("Good");
}
}
A getter method (this one is called for example getSCode()) will help you here, to ask for every attribute of a student object. It will return the s_code of the object you are looking at.
EDIT AS EXAMPLE:
public class Student{
int s_code;
String name;
int age;
public Student(int code, String name, int age){
this.s_code = code;
this.name = name;
this.age = age;
}
public int getSCode(){
return s_code;
}
public int setSCode(int newSCode){
this.s_code = newSCode;
}
}
With the getter and setter you can ask for data of an object or you can set the data.
AllStudents contains students and s_code is an int.
You can search by id mapping it first. Assuming the code is in a field called Id.
allStudents.stream().map(s -> Student::getId).collect(Collectors.toList()).contains(s_code);
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'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
NOTE: I edited my code to how I think people are trying to tell me but it still doesn't give me my desired output. Now my output is "examples.search.Person#55acc1c2" however many times I enter new first and last names. At least it's making it through the code with out crashing lol
I am learning how to use ArrayLists and need to load an Array list with instances of an Object I created. I know how to do this with an array but for this assignment I need to do it with an ArrayList. Here's an example of what I need to do.
// my "main" class
package examples.search;
import java.util.ArrayList;
import dmit104.Util;
public class MyPeople {
public static void main(String[] args) {
ArrayList<Person> people = new ArrayList<Person>();
Person tempPerson = new Person();
String firstName;
String lastName;
char choice = 'y';
int count = 1;
// fill my ArrayList
do {
people.add(tempPerson);
// I have a Util class that has a prompt method in it
firstName = Util.prompt("Enter First Name: ");
lastName = Util.prompt("Enter Last Name: ");
tempPerson.setFirstName(firstName);
tempPerson.setLastName(lastName);
count++;
choice = Util.prompt(
"Enter another person? [y or n]: ")
.toLowerCase().charAt(0);
} while (choice == 'y');
// display my list of people
for(int i = 0; i < people.size(); i += 1) {
System.out.print(people.get(i));
}
}
}
// my Person class which I am trying to build from
public class Person {
// instance variables
private String firstName;
private String lastName;
// default constructor
public Person() {
}
public String getFirstName(){
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
I've tried it a number of ways but no matter what my ArrayList doesn't fill up. Like I mentioned I can do it no problem with an array or even if I had a loaded constructor method but I don't. In my actual assignment I am supposed to do it with the set methods.
I have looked everywhere and cannot find the solution for my problem and being friday my instructor isn't in.
Thank you so much in advance
Leo
You'll have to create a Person and then add it to the ArrayList.
for (int i = 0; i < count; i++) {
Person person = new Person();
person.setFirstName("Foo");
person.setLastName("Bar");
people.add(person);
}
Its crashing because your line people.get(i).setFirstName(firstName); is first trying to what is at index i, but you have not set anything yet.
Either first set people[i] to a empty Person, or make a person using firstName and lastName, and add it to people using people.add(person);
You have an ArrayList<Person>, but that alone only defines a list of potential Person instances. But so far, each of the list entries is null. The get(i) returns null, and the following null.setFirstName(..) causes a NullPointerException.
So you need to create the instances of Person that are supposed to go into the list:
firstName = Util.prompt("Enter First Name: ");
Person p = new Person(); //create the instance
people.add(p); //add the instance to the list
p.setFirstName("..."); //set any values
Now you are storing the Person Object into an ArrayList and printing that Object.
To print the firstname and lastName when you print the Person object, you will have to override toString method.
Add the following code in your Person class
public String toString(){
return String.format("[Personn: firstName:%s ,lastName: %s]", firstName,lastName);
}
As for the second question you had, you have to override the toString() method in the Person class. The outputs you are getting, such as examples.search.Person#55acc1c2 is the default toString() method from the Object class, which is defined as class#hashCode