package chapter10;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Customer {
private String name;
private String streetAddress;
private String phoneNumber;
private int total;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStreetAddress(){
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public int getTotal(){
return total;
}
public void setTotal(int total){
this.total = total;
}
public static void assign(){
int a = (int) (Math.random() + 10);
int r = (int) (Math.random() + 10);
int f = (int) (Math.random() + 10);
System.out.println(a + r + f + "x" + "x" + "x");
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
ArrayList <Customer > customerList = new ArrayList <Customer>();
char ans;
do
{
Customer customer = new Customer();
System.out.print("Customer name ");
customer.setName(in.next());
int i = 0;
++i;
System.out.print("Street Address ");
customer.setStreetAddress(in.next());
System.out.print("Phone Number ");
customer.setPhoneNumber(in.next());
customerList.add(customer);
System.out.println("Enter total sales ");
customer.setTotal(in.nextInt());
System.out.println("Would you like to enter in a new customer ( y/n)? ");
String answer = in.next();
ans = answer.charAt(0);
((String) customerList).concat("")
} while(ans == 'y');
for(Customer c: customerList){
System.out.print(c.getName() + "\n" + "Phone number is " +c .getPhoneNumber() +"\n" + "Total sales is "+ c.getTotal() + "\n" + "Address is"+ c.getStreetAddress());
}
for(int i=0; i<customerList.size(); i++){
//System.out.print(customerList.get(i).getName());
}
}
}
I need to assign a number to each value in the arraylist but i am getting an error that says that I have to convert to string (arraylist). How do I add it?
If what I gather from the comments is correct then I believe this is what you want:
Your current assign() is incorrect if you want random values 1-10, it should look like this instead:
public String assign(){
Random rand = new Random();
int a = rand.nextInt(10) + 1;
int r = rand.nextInt(10) + 1;
int f = rand.nextInt(10) + 1;
return a+r+f+"xxx";
}
Customer will look like this:
public class Customer {
private String name;
private String customerNumber;
private String streetAddress;
private String phoneNumber;
private int total;
...
...
...
public String getCustomerNumber() { return this.customerNumber; }
public void setCustomerNumber(String cNumber) { this.customerNumber = cNumber; }
And assigning the numbers should look like this:
for(Customer c : customerList) {
c.setCustomerNumber(assign());
}
Also avoid this line of code, it's a really bad idea:
((String) customerList).concat("")
You should probably rename the customerNumber to customerID.
Hiiii
As i understand you are trying to to add number to each value to arrayList ,And same time you are creating arrayList of customer object, So first understand about arrayList of object,
Customer c1 = new Customer();
Customer c2 = new Customer();
ArrayList<Customer> al = new ArrayList();
al.add(c1);
al.add(c2);
Here this ArrayList object save only address of customer object so how can you change the address of Customer object ; You can not add number in Customer type ArrayList Object,
There is another way typecast your ArrayList to Object type and then no need to typecast again , you can add any type of object in ArrayList
like this,
Customer c1 = new Customer();
Customer c2 = new Customer();
ArrayList<Object> al = new ArrayList();
al.add(c1);
al.add(c2);
In your code there's the following line:
((String) customerList).concat("")
Trying to cast a List to a String is doomed to failure - I'm not sure why do you think it should work.
If you want a String representation of the list, you should implement a toString() method in class Customer and then you can do something like:
System.out.println(Arrays.toString(customerList.toArray()));
Instead of using ArrayList, you can use Map. In which you can have the number as key and value as Customer.
http://examples.javacodegeeks.com/java-basics/java-map-example/ Contains the example of using Map
Answer in Storing a new object as the value of a hashmap? contains info about how to use Object as value in HashMap
Related
Here is my code
class Employee{
private String Animal;
private int Quantity;
Employee(String Animal, int Quantity){
this.Animal=Animal;
this.Quantity=Quantity;
public String getAnimal{
return animal;
}
public void setAnimal{
this.Animal=Animal;
}
public String getQuantity{
return Quantity;
}
public void setQuantity{
this.Quantity=Quantity;
}
public static void Input(){
Scanner sc = new Scanner(System.in);
int n = 0;
Employee[] list = new Employee[20];
list[no] = new Employee(" ", 0);
String nameOfAnimal = sc.nextLine();
list[n].setAnimal(nameOfAnimal);
String numberOfAnimal = sc.nextLine();
list[n].setQuantity(numberOfAnimal);
++n;
}
public static void Output(){
...
for(int i=0; i<n; ++i){
System.out.println(" -" + list[i].getAnimal + " - " + list[i].getQuantity);
}
}
}
In the Output method, I dot 3 points because I don't know how to get the array declared in the Input method and print its content within the Output method. It always shows an error that the first element is null when I create the same array in the Output function. Concisely, how can I keep an array that both functions can be used?
I don't know what I'm doing and would appreciate any help.
I'm reading a text file with the following code:
7
10 416-555-6667 Burgess Smith 15
15 905-777-8888 Thomas Patel 10
20 905-111-2222 Morris J. Stevenson 5
25 416-222-3333 Spencer Larson 30
30 416-333-4444 Adams Doe 18
35 905-122-5454 Price Hanks 15
40 905-343-5151 Clement L. Webster 8
private static void fileReader() throws FileNotFoundException
{
int eId = 0;
String nme = "";
String phne = "";
int yrs = 0;
String line ="";
Employee emp = new Employee(eId, nme, phne, yrs);
File inputfile = new File("Emp.txt");
Scanner in = new Scanner(inputfile);
n = in.nextInt() - 1;
in.nextLine();
in.useDelimiter("");
for (int i=0;i<=n;i++)
{
int l = 0;
int m = 0;
int n = 0;
line = in.nextLine();
while (Character.isDigit(line.charAt(l)))
{
l++;
}
m = l + 1;
while (!Character.isLetter(line.charAt(m)) && !Character.isWhitespace(line.charAt(m)))
{
m++;
}
n = m + 1;
while (!Character.isDigit(line.charAt(n)))
{
n++;
}
eId = Integer.parseInt(line.substring(0, l));
emp.setEmpId(eId);
phne = line.substring(l + 1, m - 1);
emp.setTelephone(phne);
nme = line.substring(m + 1, n - 1);
emp.setName(nme);
yrs = Integer.parseInt(line.substring(n));
emp.setYears(yrs);
empArr.add(i, emp);
}
in.close();
}
class for set and get methods:
public class Employee
{
private int empId;
private String telephone;
private String name;
private int yearsOfWork;
public Employee(int id, String name, String telephone, int yearsOfWork)
{
empId = id;
this.telephone = telephone;
this.name = name;
this.yearsOfWork = yearsOfWork;
}
public void setEmpId(int id)
{
empId = id;
}
public void setName(String name)
{
this.name = name;
}
public void setTelephone(String telephone)
{
this.telephone = telephone;
}
public void setYears(int years)
{
yearsOfWork = years;
}
public int getEmpId()
{
return empId;
}
public String getName()
{
return name;
}
public String getTelephone()
{
return telephone;
}
public int getYears()
{
return yearsOfWork;
}
public String toString()
{
return "ID:" + empId + ", name: " + name + ", phone: " + telephone + ", years of work: " + yearsOfWork + "\n";
}
}
When I call the get method of my ArrayList outside of its for loop, the text at each index is overwritten by the text at the last index.
I think I'm missing some fundamental concept of constructors and objects here.
Any help is appreciated. Thanks.
Your hunch is correct, you are missing the emp object creation. You have to move the emp object creation into the loop.
Your Employee class and getter/setter methods are correctly written.
Rewrite your fileReader() method similar to given below : -
String line ="";
//Declare an Arraylist for an Employee
List<Employee> employee = new ArrayList<Employee>();
//Read a file
File inputfile = new File("Emp.txt file path");
Scanner in = new Scanner(inputfile);
//Reading a number from a first sentence
int n = Integer.parseInt(in.nextLine());
for (int i=0;i<n;i++) {
// Reading each sentence
line = in.nextLine();
//Parse an Emp id
int eId = Integer.parseInt(line.substring(0, 2));
//Parse a phone number
String phone = line.substring(3, 14);
//Parse a name
String name = line.split("\\d+")[4];
//Parse years
int years = Integer.parseInt(line.split("\\D+")[4]);
//Now create an object by putting all above values in a constructor
Employee emp1 = new Employee(eId, name, phone, years);
//Add that object in an arraylist
employee.add(emp1);
}
//As you have overridden toString method, print an arraylist
System.out.println(emp.toString());
//Closing the scanner
in.close();
}
Hope this helps.
I've created all of my objects in my class "student" by hand and really just need to use an array to put the names, grades and ID numbers into. When I try, it gives me an error about incompatible types. I understand it's probably due to a restriction on some sort of syntax type of error. Could anyone help with the physical grammar of this portion please? It would be much appreciated!
package bilak_sackin_assignment_7;
public class Bilak_Sackin_Assignment_7 {
public static void main(String[] args) {
student Frank = new student("Frank", 95.2, 11231);
student Billy = new student("Billy", 65.6, 656454);
student Alex = new student("Alex", 65.2, 123456);
student Miranda = new student("Miranda", 80.0, 963852);
student Joel = new student("Joel", 89.9, 486248);
Frank.display();
Billy.display();
Alex.display();
Miranda.display();
Joel.display();
}
}
class student {
String[] name = new String[5];
double[] grade = new double[5];
int[] ID = new int[5];
public student(String[] n, double[] g, int[] d) {
name = n;
grade = g;
ID = d;
}
public void display() {
for (int i = 0; i < 4; i++) {
System.out.println("Names: " + name[i]);
System.out.println("Grades: " + grade[i]);
System.out.println("Student ID: " + ID[i]);
}
}
}
I'm quite new to this too, but surely you're not needing arrays, you're creating objects. Remove all your [ and ], like this -
public static void main(String[] args) {
student Frank = new student("Frank",95.2,11231);
student Billy = new student("Billy", 65.6, 656454);
student Alex = new student("Alex", 65.2, 123456);
student Miranda = new student("Miranda", 80.0, 963852);
student Joel = new student("Joel", 89.9, 486248);
Frank.display();
Billy.display();
Alex.display();
Miranda.display();
Joel.display();
}
}
class student
{
String name;
double grade;
int ID;
public student(String n, double g, int d)
{
name = n;
grade = g;
ID = d;
}
public void display()
{
System.out.println("Names: " + name);
System.out.println("Grades: " + grade);
System.out.println("Student ID: " + ID);
}
}
That works for me.
If I'm right, PLEASE mark me as right, I need the rep! :-)
public student(String[] n, double[] g, int[] d)
{
name = n;
grade = g;
ID = d;
}
Your constructor expects an array of Strings, an array of doubles, and an array of ints.
This, however, is what you pass:
new student("Joel", 89.9, 486248);
One single String, one single double, and a single int.
My guess, you don't need arrays in your Student class, except for the grades.
So, step one is to remove the arrays for name and id.
step two: pass an array of doubles as grades.
In your constructor for student, all of the inputs are primitive arrays however, you are not using them as such in the creation of the objects above.
If you want to use a constructor as follows:
Student billy = new Student("Billy", 23, 35);
then you must define the constructor with non-array inputs i.e.
class Student {
String name;
double grade;
int id;
public Student(String name, double grade, int id) {
this.name = name;
this.grade = grade;
this.id = id;
}
}
Alrighty, I decided to use #NickL's idea by using the array to construct the objects and then access it as an array afterwards.
package bilak_sackin_assignment_7;
public class Bilak_Sackin_Assignment_7 {
public static void main(String[] args) {
String name[] = {"Frank", "Billy","Alex", "Miranda", "Joel" };
double grades[] = {95.2, 65.6, 65.2, 80.0, 89.9};
int iD[] = {112312, 656454, 123456, 963852, 486248};
for (int i = 0; i < 5; i++)
{
String names = name[i];
double grade =(grades[i]);
int ID = (iD[i]);
System.out.println("Name: " + names + " | Grade: " + grade + " | ID number: " + ID);
}
}
}
The purpose of my code is to have the user input the name of a car. The code will use a for loop to search through an array list and print out the car that the user typed in. The code compiles, but it doesn't print anything out. Here is the code:
public class searchList
{
private static inventory inventory = new inventory();
private static ArrayList<engineSpecs> list = inventory.getList();
public void searchList()
{
//Declarations
Scanner scan = new Scanner(System.in);
String search = new String();
String car = new String();
//Prompts user to enter car name
System.out.println ("Enter car name: ");
car = scan.nextLine();
//Searches array list and prints car
for (engineSpecs item: list)
{
if (item.equals(car))
{
System.out.println (item);
}
}
}
}
The array list is declared in another class. Here is that class:
public class inventory
{
public static ArrayList<engineSpecs> list = newArrayList<engineSpecs>();
public inventory()
{
//Adds objects into array list
engineSpecs astonmartin = new engineSpecs("Aston Martin", "Vanquish", 350000, 11, "Gray",
2015, 565, 457, "automatic");
engineSpecs ferrari = new engineSpecs ("Ferrari", "458 Italia", 240000, 13, "Red", 2015,
570, 398, "automatic");
list.add(astonmartin);
list.add(ferrari);
}
public static ArrayList<engineSpecs> getList()
{
//getter method
return list;
}
}
My engineSpecs class is just a simple constructor. I'm using it so I can instantiate an object of this constructor and save it into the array list.
public class engineSpecs
{
private int HP;
private int torque;
private String transmission;
private int year;
private int MPG;
private int price;
private String model;
private String color;
private String manufacturer;
public engineSpecs (String manufacturerName, String modelName,int stickerPrice, int MPGe,
String extColor, int yearNum, int BHP, int torquelbs, String transmissionType)
{
HP = BHP;
torque = torquelbs;
transmission = transmissionType;
year = yearNum;
MPG = MPGe;
price = stickerPrice;
model = modelName;
color = extColor;
manufacturer = manufacturerName;
}
public String toString()
{
String result = "Manufacturer: " + manufacturer + "\n";
result += "Model: " + model + "\n";
result += "Price: " + price + "\n";
result += "Estimated MPG: " + MPG + "\n";
result += "Color: " + color + "\n";
result += "Year: " + year + "\n";
result += "Horse power: " + HP + "\n";
result += "Torque: " + torque + "\n";
result += "Transmission: " + transmission + "\n";
return result;
}
}
Your are using .equals() for objects which is not going to return true until they are same object in the memory. You need a new method that compares the string value of the name. Also you need toString() method to print the string conversion of the object.
Your engineSpecs class should look something like this:
public class engineSpecs{
public String name;
public engineSpecs(String s){
this.name = s;
}
public boolean is(String car){
return this.name.equals(car);
}
public String toString(){
return this.name;
}
}
Update:
change your if statement to :
if (item.is(car))
{
System.out.println (item);
}
Define this method in engineSpecs :
public boolean is(String manufacturerName){
return this.manufacturer.equals(manufacturerName);
// need to compare more values if you want to compare more properties
}
You can try to redefine the method equals() in your class engineSpecs, so the line item.equals(car) works correctly.
More info here.
I am making a bank account program and for my constructor I want it to add the customers name(which it does) and I also want it to automatically generate an account number for each customer added starting from 1 to n customers(which it does NOT do...), if I have 3 names it prints the num 3 for each of their accNum when I add these names to an ArrayList in my "BankDataBase" class.
public class Customer
{
private final String fname;
private final String lname;
Customer(String fn, String ln)
{
fname = fn;
lname = ln;
}
public class Account
{
private Customer cust;
private int accNum = 0;
private double balance;
Account(Customer c)
{
cust = c;
balance = 0;
accNum++;
}
public class DataBase
{
private Account accCust;
int getAcc = 0;
ArrayList<Account> chaseAccts = new ArrayList<>();
public void addAcct(Account me)
{
accCust = me;
chaseAccts.add(me);
}
public void display()
{
for (int i = 0; i < chaseAccts.size(); i++)
{
System.out.println(chaseAccts.get(i).getAccount() + " " + accCust.getAccNum());
}
}
Thanks in advance.
You could track the assigned account numbers statically, and assign the new account the next number in the series. Something like
public class Account
{
private static int nextAccoutNumber = 0;
private Customer cust;
private double balance;
Account(Customer c)
{
cust = c;
balance = 0;
accNum = ++nextAccountNumber;
}
}
You're adding the new account to the list, but you're also storing it in a local variable. Where you're doing this:
System.out.println(chaseAccts.get(i).getAccount() + " " + accCust.getAccNum())
you are writing out the accNum value of the same accCust each time. You need to write
System.out.println(chaseAccts.get(i).getAccount() + " " + chaseAccts.get(i).getAccNum());
And since you're using a list of type ArrayList<Account> you could just write the whole loop as:
public void display()
{
for(Account account : chaseAccts) {
System.out.println(account.getAccount() + " " + account.getAccNum());
}
}
You could try to make a static variable
private static int accSeq = 0
private Customer cust;
private int accNum = 0;
private double balance;
Account(Customer C) {
cust = c;
balance = 0;
accNum = ++accSeq;
}