Proper use of objects - java

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

Related

Problem with comparing a value to a specific object of an ArrayList Java

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

Generate non repeating numbers to add to customerNumber int variable

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

OOP School work (beginner)

As is, it does compile.
Bug = printing breed and declawed statements on same line. Cannot get rid of this bug for some reason
Bug = unable to get the result logic to compile and print for
console (newb)
There are examples a little like mine posted but they really haven't done anything to help because they are not exactly what I think I'm supposed to be going for. One worked perfect but uses and array and we aren't even to that part yet in my course. Here are the teachers instructions and some tips he gave me and then my code so far. Some of it is commented out since I'm trying to get rid of bugs before printing the result. Also I did change some of the names for convenience until the assignment is complete. Sorry for any formatting issues. Any advice?
In this order:
assignment instruction for class file
tip from the teacher
class file code so far
assignment for the driver file
driver file code so far
ASSIGNMENT INSTRUCTIONS FOR THE CLASS FILE:
Create a new class called Cat that includes the functionality below
The new class has the attributes of:
name – type String
age – type integer
weight – type double
breed - type String
declawed - type boolean - true for has no claws, false for has claws
Be sure your classes have a reasonable complement of constructor, accessor and mutator methods. Every member variable must have at least one independent accessor and one independent mutator.
Example:
public void setName(String name) mutator used to set name
public void setBreed(String breed) mutator used to set the breed
public void set(Boolean declawed) used to set claws or not
****(You must overload the set method to set deClawed value)** what is this?**
public String getName() accessor used to get name
public String getBreed() accessor used to get breed
public boolean getBoolean() access used to get the value of declawed
Ensure you use the “this” reference from within this class when referring to every instance variable or instance method of the current object.
TIP FROM THE TEACHER:
for your IF statement you will only use Age and Claw methods but
then at the end when you print out everything you will need the rest of the
methods. You can create a display method to display all the print
statements for each category such as name, age, etc...then it becomes
easier to display this in the main method - here would be your code in the
main method:
System.out.println("The cat data entered is: \n");
myCat1.display();
myCat2.display();
myCat3.display();
code for class file so far
/*************************************************************************************************
*Cat.java
*Jonathan Nees
*
*Cha. 6 OOP
*************************************************************************************************/
import java.util.Scanner;
public class Cat
{
private String name;
private int age;
private double weight;
private String breed;
private boolean declawed;
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
public void setAge(int age)
{
this.age = age;
}
public int getAge()
{
return this.age;
}
public void setWeight(double weight)
{
this.weight = weight;
}
public double getWeight()
{
return this.weight;
}
public void setBreed(String breed)
{
this.breed = breed;
}
public String getBreed()
{
return this.breed;
}
public void setDeclawed(boolean declawed)
{
this.declawed = declawed;
}
public boolean isDeclawed()
{
if (!this.declawed == false)
{
return true;
}
else
{
return false;
}
}
Scanner input = new Scanner(System.in);
public void display()
{
System.out.print("Enter the name of Cat: ");
this.name = input.nextLine();
System.out.print("Enter the age of Cat: ");
this.age = input.nextInt();
System.out.print("Enter the weight of Cat: ");
this.weight = input.nextDouble();
System.out.print("Enter the breed of Cat: ");
this.breed = input.nextLine();
System.out.print("Does the cat have claws? True or False?: ");
this.declawed = input.nextBoolean();
}
}
Assignment instructions for the driver file
Write a driver program that reads in 3 pets of type Cat and prints out the name and age of all cats with claws and over 3 years old.
The following information should be read in:
Name (as String)
Age (as int)
Weight (as double)
Breed (as String)
DeClawed (as boolean)
Ensure you use the accessor methods to check the age and claws.
code for driver file so far
/*************************************************************************************************
*CatDriver.java
*Jonathan Nees
*
*Cha. 6 OOP Driver
*************************************************************************************************/
import java.util.Scanner;
public class CatDriver
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Cat Cat1 = new Cat();
Cat Cat2 = new Cat();
Cat Cat3 = new Cat();
Cat1.display();
System.out.println();
Cat2.display();
System.out.println();
Cat3.display();
System.out.println();
//*for (int i=0; i<3; i++)
//{
// System.out.println("The cats over 3 with claws are:");
// if ((!this.age() <= 3) && (this.Declawed() == true))
// {
// System.out.println("Name: " + this.name);
// System.out.println("Age: " + this.age + "Years Old");
// }
//}
}
}
Like I said I've commented some out to work out the bugs before doing the result.
It almost works! Sorta...
I was able to get it to work. I rewrote your display method using setter methods and it did the trick. Also, your declawed setter method is written a little confusingly so you may want to tinker with it.
Try this:
public void display()
{
System.out.print("Enter the name of Cat: ");
this.setName(input.nextLine());
System.out.print("Enter the age of Cat: ");
this.setAge(Integer.valueOf(input.nextLine()));
System.out.print("Enter the weight of Cat: ");
this.setWeight(Double.valueOf(input.nextLine()));
System.out.print("Enter the breed of Cat: ");
this.setBreed(input.nextLine());
System.out.print("Does the cat have claws? True or False?: ");
this.setDeclawed(!Boolean.valueOf(input.nextLine()));
}

how do i add or delete something from an array?

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

Referencing user input string from another class?

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.

Categories