I have been tasked with writing a code to create 4 classes(Main, Person,Account,Vehicle)and create objects of the Person class as per user requirements, doing so using an array. I had to store data within the array via user input, and retrieve them as per user choice. Which I believe I have successfully done so. One of the two inputs I had to ask from the user were, "Do you have an Account" and "Do you have a vehicle". If the User answers "Yes", I had to pass the object or something as a reference to the Account and Vehicle class to seclude them separately as well, and when the User asks for the People with an Account and Vehicle, It were to print the details of those specific users only.
.
Here is my code below
Main.java:
package com.company;
import java.util.Scanner;
public class Main {
public static int ids;
static int choice = 0;
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
menus();
}
public static void conditions(int choice){
switch (choice) {
case 1:
int i;
System.out.println("Enter id of person");
i = sc.nextInt();
Person user2[] = new Person[10];
user2[i] = new Person();
user2[i].setArray(i,user2);
//Getters
int k;
System.out.println("Enter id of existing person to retrieve info or press 0 to go to menu");
int l;
l = sc.nextInt();
if (l == 0) {
menus();
}
else {
System.out.println(user2[l].getName());
System.out.println(user2[l].getGender());
System.out.println(user2[l].getAge());
System.out.println(user2[l].isAccount());
System.out.println(user2[l].isVehicle());
}
case 2:
//Call getters
Account a1=new Account();
a1.getArrays();
case 3:
Vehicle v1=new Vehicle();
v1.printArray();
}
}
public static void menus() {
System.out.println("Choose an option");
System.out.println("1.Enter new person details");
System.out.println("2.Does not work(should display people who want an acc only");
System.out.println("3.Does not work(Should display people who have a vehicle only)");
choice = sc.nextInt();
conditions(choice);
}
}
Person.java:
package com.company;
import java.util.Scanner;
public class Person {
private String name;
private int age;
private String gender;
private static String Account;
private static String Vehicle;
Person array[];
public String isAccount() {
return Account;
}
public void setAccount(String account) {
Account = account;
}
public String isVehicle() {
return Vehicle;
}
public void setVehicle(String vehicle) {
Vehicle = vehicle;
}
public Person[] getArray() {
return array;
}
public void setArray(int i,Person[] array) {
this.array = array;
Scanner sc=new Scanner(System.in);
System.out.println("Enter name");
name=sc.next();
array[i].setName(name);
System.out.println("Enter age");
age=sc.nextInt();
array[i].setAge(age);
System.out.println("Enter gender");
gender=sc.next();
array[i].setGender(gender);
System.out.println("Enter Yes if you want an account,No if otherwise");
Account=sc.next();
if(Account=="Yes"){
Account user3[] = new Account[10];
user3[i].setArray(i,this.array);
user3[i] = new Account(i,name,gender,Account);
}
else{
array[i].setAccount("No");
}
System.out.println("Enter Yes if you have a vehicle, No if otherwise");
Vehicle=sc.next();
if(Vehicle=="Yes"){
Vehicle user4[] = new Vehicle[10];
user4[i] = new Vehicle();
user4[i].setArray(i,this.array);
}
else{
array[i].setVehicle("No");
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
Accounts.java:
package com.company;
public class Account extends Person{
Account[] arrays;
private int ages;
private String names;
private String genders;
private String vehicles;
private String accounts;
Account(int id,String names,String genders,String accounts){
arrays[id].setNames(names);
arrays[id].setAges(ages);
arrays[id].setGenders(genders);
arrays[id].setAccounts(accounts);
}
Account(){
}
public com.company.Account[] getArrays() {
return arrays;
}
public void setArrays(com.company.Account[] arrays) {
this.arrays = arrays;
}
public int getAges() {
return ages;
}
public void setAges(int ages) {
this.ages = ages;
}
public String getNames() {
return names;
}
public void setNames(String names) {
this.names = names;
}
public String getGenders() {
return genders;
}
public void setGenders(String genders) {
this.genders = genders;
}
public String getVehicles() {
return vehicles;
}
public void setVehicles(String vehicle) {
this.vehicles = vehicles;
}
public String getAccounts() {
return accounts;
}
public void setAccounts(String accounts) {
this.accounts = accounts;
}
public void printArray(){
for(int k=0;k<array.length;k++){
System.out.println(array[k]);
}
}
}
My Vehicle class is the same as Accounts.
-To seclude and print
-I have tried to pass the array from the Person class to the Accounts class and Vehicle, If the User does wish to have an Account and has a Vehicle.
-However, upon printing via for loop or a basic getter, I am met with an Error "this.array is null" which probably means my Array isnt being passed or stored within the Account class.
-Maybe there is a simpler way of secluding and printing them, as per the task I have to implement the use of Abstraction, Arrays, Constructors and Functions.
I am new to Java and the Stackoverflow platform, so please forgive me If the formatting of the question isnt precise. Hope to recieve some detailed help on getting around this.
Related
Following is stretagy design pattern example take from here.
First of all we will create the interface for our strategy, in our case to pay the amount passed as argument.
public interface PaymentStrategy {
public void pay(int amount);
}
public class CreditCardStrategy implements PaymentStrategy {
private String name;
private String cardNumber;
private String cvv;
private String dateOfExpiry;
public CreditCardStrategy(String nm, String ccNum, String cvv, String expiryDate){
this.name=nm;
this.cardNumber=ccNum;
this.cvv=cvv;
this.dateOfExpiry=expiryDate;
}
#Override
public void pay(int amount) {
System.out.println(amount +" paid with credit/debit card");
}
}
public class PaypalStrategy implements PaymentStrategy {
private String emailId;
private String password;
public PaypalStrategy(String email, String pwd){
this.emailId=email;
this.password=pwd;
}
#Override
public void pay(int amount) {
System.out.println(amount + " paid using Paypal.");
}
}
public class Item {
private String upcCode;
private int price;
public Item(String upc, int cost){
this.upcCode=upc;
this.price=cost;
}
public String getUpcCode() {
return upcCode;
}
public int getPrice() {
return price;
}
}
public class ShoppingCart {
//List of items
List<Item> items;
public ShoppingCart(){
this.items=new ArrayList<Item>();
}
public void addItem(Item item){
this.items.add(item);
}
public void removeItem(Item item){
this.items.remove(item);
}
public int calculateTotal(){
int sum = 0;
for(Item item : items){
sum += item.getPrice();
}
return sum;
}
public void pay(PaymentStrategy paymentMethod){
int amount = calculateTotal();
paymentMethod.pay(amount);
}
}
public class ShoppingCartTest {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
Item item1 = new Item("1234",10);
Item item2 = new Item("5678",40);
cart.addItem(item1);
cart.addItem(item2);
//pay by paypal
cart.pay(new PaypalStrategy("myemail#example.com", "mypwd"));
//pay by credit card
cart.pay(new CreditCardStrategy("Pankaj Kumar", "1234567890123456", "786", "12/15"));
}
}
I want to ask what is use of strategy pattern here?Once we have created a strategy in main.We have access to Strategy class now.We can directly call pay() method from there?Why do we need interface , all which does is call a method?
1. I want to ask what is use of strategy pattern here?
The answer is the user who has the ShoppingCart (ShoppingCart cart = new ShoppingCart();)
2. We can directly call pay() method from there?
I don't know exactly you mean
3. Why do we need interface , all which does is call a method?
We need the interface PaymentStrategy because we need use Polymorphism to implement many way to pay (paypal or credit card), let's change the source a bit and you can see clearer:
public class ShoppingCart {
// other functions
public void pay(PaymentStrategy paymentMethod, int amount){
paymentMethod.pay(amount);
}
public void payWithStrategy() {
int amount = calculateTotal();
if (amount > 10000) { // because your credit card limit is 10000$ so you must use paypal
pay(new PaypalStrategy("myemail#example.com", "mypwd"), amount);
}
else { // you really like credit card so when the money lower than the card limit, you always choose it
pay(new CreditCardStrategy("Pankaj Kumar", "1234567890123456", "786", "12/15"), amount);
}
}
}
public class ShoppingCartTest {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
Item item1 = new Item("1234",10);
Item item2 = new Item("5678",40);
cart.addItem(item1);
cart.addItem(item2);
cart.payWithStrategy();
}
}
I am trying to write a program which stores information about a person in a linked list. I made a simple person class to store the name, age and addresses in the list. I would also like to store multiple addresses for EACH person, and a fact about the place in another linked list, inside the person class.
So for example, "Tara" can have a home address of "10 Central Ave" and a work address of "5 Willow street" etc. The problem is, I don't know how to have a linked list inside another.
My goal is to check whether the person's name is already on the list, and if so, add another address for them. (So that there is no repeats). I am a beginner and can really use some help.
public class Person {
private String name;
private int age;
public LinkedList <String> adresses;
public Person() {
name = "default";
age = 0;
adresses = new LinkedList<>();
}
public Person(String n, int a) {
name = n;
age = a;
}
public LinkedList<Adress> getAdresses() {
return adresses;
}
public void setAdresses(LinkedList<Adress> adresses) {
this.adresses = adresses;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return name+" "+age+" "+adresses;
}
}
public class Adress {
public String adress;
public String fact;
public Adress(String a, String f) {
adress = a;
fact = f;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public String getFact() {
return fact;
}
public void setFact(String fact) {
this.fact = fact;
}
}
public class Test {
public static void main(String[] args) {
Person Tara = new Person("Tara",35);
Person Judah = new Person("Judah",28);
Person Mark = new Person("Mark",45);
Person Seth = new Person("Seth",23);
LinkedList<Object> tester = new LinkedList<>();
tester.add(Tara);
tester.add(Judah);
tester.addLast(Mark);
tester.addLast(Seth);
System.out.println(tester);
}
}
How is about to use the next classic data structure for your project?
public class Person {
private String name
private int age;
public List<Address> addresses;
//...
}
I need to write up a static method that takes an array of Vehicles and print each registration number in the array. The object in the array is either a Vehicle, a Car, or a Truck object reference. Finally, I need to print the registration number of the object on a single line on its own.
So the code is:
public class Vehicle {
private String registrationNumber;
public Vehicle(String rego) {
registrationNumber = rego;
}
public String getRegistrationNumber() {
return registrationNumber;
}
}
public class Car extends Vehicle {
int passengers;
public Car(String rego, int pass) {
super(rego);
passengers = pass;
}
public int getPassengers() {
return passengers;
}
}
public class Truck extends Vehicle {
int tons;
public Truck(String rego, int tons) {
super(rego);
this.tons = tons;
}
public int getTons() {
return tons;
}
}
I have to write up a static method for the following test and get the following, but I am having some trouble.
Test and expected Result
This is what I have done so far:
public static void printRegNum(Vehicle[] list){
for (int i = 0; i < list.length; i++){
System.out.println(list[i]);
}
}
The 1st way to play with your System.out.println(list[i]); is to override the toString() method in class Vehicle:
public class Vehicle {
private String registrationNumber;
public Vehicle(String rego) {
registrationNumber = rego;
}
public String getRegistrationNumber() {
return registrationNumber;
}
public String toString() {
return registrationNumber;
}
}
The 2nd way is change:
from:
System.out.println(list[i]);
to:
System.out.println(list[i].getRegistrationNumber());
Hope those can help.
Not getting where's the problem
i.e.
public static void main(String[] args){
Car car = new Car("MYCAR",4);
Truck t = new Truck("MYTRUCK", 16);
Vehicle[] myList = new Vehicle[] {car, t};
printRegNum(myList);
}
Also seems that you only need to print the "rego".
System.out.println(list[i].getRegistrationNumber());
I'm trying to compare a bunch of Objects of the same class to search for matching ID's?
This is the GroupClass, when a new entry is entered it will test against the idNumber to see if there is a match.
Public GroupClass {
private int idNumber;
private String name;
private double income;
public GroupClass(int id, String name, double income){
this.idNumber = id;
this.name = name;
this.income = income;
}
public int getIdNumber() {
return idNumber;
}
public void setIdNumber(int idNumber) {
this.idNumber = idNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getIncome() {
return income;
}
public void setIncome(double income) {
this.income = income;
}
}
This is the Main Method
import static java.lang.reflect.Array.set;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class ListTester {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Set<GroupClass> groupArray = new LinkedHashSet<>();
System.out.println("Enter a ID Number");
int id = input.nextInt();
System.out.println("Enter a First Name");
String name = input.next();
System.out.println("Enter a an Income");
double income = input.nextDouble();
groupArray.add(new GroupClass(1111, "Billy", 178000));
groupArray.add(new GroupClass(1112, "Sam", 78000));
groupArray.add(new GroupClass(1113, "Mark", 79000));
groupArray.add(new GroupClass(id, name, income));
printTheClass(groupArray);
}
public static void printTheClass(Set group){
for(Object theArray: group){
System.out.println(theArray + " ");
}
}
}
Ive seen a few questions like it but just cant get it to work for my particular case, thanks in advance.
As per the above comment you override the equals method, but this may not be suitable for the long term growth of the class.
But using your existing code try
public static void printTheClass(Set<GroupClass> group){
for(GroupClass theArray: group){
System.out.println(theArray + " ");
}
}
and
public static GroupClass findTheClass(Set<GroupClass> group, int id){
for(GroupClass obj: group){
if(obj.getIdNumber == id) return obj;
}
return null;
}
This can be used as
if (findTheClass (groupArray, id) == null) {
groupArray.add (new GroupClass(id, name, income));
}
Not quite sure what is your goal. If you want to reject any new entry if the id already exist, you need to override the hashCode and equals methods of the GroupClass so that LinkedHashSet knows if two GroupClass objects are different:
#Override
public int hashCode() {
return this.idNumber;
}
#Override
public boolean equals(Object obj) {
return obj instanceof GroupClass && ((GroupClass) obj).getIdNumber() == this.idNumber;
}
However, in most cases, you might want to retrieve an entry using its id number. Then it might be better to use a map with id as key, and the GroupoClass object itself as value
Map<Integer, GroupClass> groupmap = new HashMap<>()
groupmap.put(id, new GroupClass(id, name, income));
and you will have to use groupmap.keySet() to iterate the map.
I'm doing a homework assignment, where we were asked to create a banking system. The first option is to create a customer and to store their information in a customer object. The start of my create_customer() method asks for their name and stores it into a newly create Customer object, but when i call the getName() method, nothing comes back. Here's the initial class Atm which holds all the actions for each option.
import java.util.ArrayList;
public class Atm
{
private ArrayList<Customer> cust;
private int starting_account_number;
private int starting_customer_number;
private String admin_pin;
private int interest_rate;
private int transaction_counter;
ConsoleReader console = new ConsoleReader(System.in);
public Atm() // constructor
{
cust = new ArrayList<>(100);
starting_account_number = 1001;
starting_customer_number = 101;
admin_pin = "abcd";
interest_rate = 5;
transaction_counter = 0;
}
void create_customer()
{
Customer customer = new Customer();
System.out.println("Please input your name: ");
customer.setName(console.readLine());
customer.getName();
while (customer.istrue)
{
System.out.println("Please input a 4 digit alphanumeric PIN: ");
customer.setPin(console.readLine());
if (customer.istrue == false) break;
}
System.out.println("A system generated ID was created for you, it is: ");
String customer_id = String.valueOf(starting_customer_number);
customer.setId(customer_id); // set customer ID
starting_customer_number++; //incrememnt customer ID
System.out.print(customer.getId());
cust.add(customer); //puts the customer object into atm class arraylist
}
Here's the customer class
import java.util.ArrayList;
public class Customer
{
public boolean istrue;
private String name;
private String id; // 3 digits string
private String pin; // 4 digits string
private ArrayList<Account> acct;
private double total_bal; // for all accounts
public Customer() //constructor
{
acct = new ArrayList<>(100);
istrue = true;
name = "NoName";
id = "000";
pin = "0000";
total_bal = 0;
}
// public cal_total_bal() { }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
if (pin.length() != 4)
{
System.out.println("That was not 4 digits, please input a 4 digit alphanumeric PIN: ");
}
else istrue = false;
}
You are calling a method
customer.getName();
But you are not actually doing anything with it.. you might want to print it:
System.out.println(customer.getName());