I want to add some different types elements into the same index in ArrayList.For example:
List account= new ArrayList();
String name;
int number;
float money;
account.add(0,name);
account.add(1,number);
account.add(2,money);
But now , i want to take String name , int number and float money save into the same index.How to do it ?If Arraylist can't. How can i do act this function?
i want to take String name , int number and float money save into the
same index.How to do it ?
You should create a model class named Account. Than define a list like List<Account>.
class Account{
String name;
int number;
float money;
// Constructor, Getter setter etc.....
}
List<Account> list= new ArrayList<Account>();
list.add(new Account("Name", 123, 50.0));
Than, account information will be at account instance at same index. You can access the Account data using list.get(index) method.
Alexis C. is right (in the question's comments).
You'll have to use a class to represents what is an account.
Then you'll be able to create instances of this class for all accounts.
Example :
class Account {
String name;
int number;
float money;
Account(String name, int number, float money) {
this.name = name;
this.number = number;
this.money = money;
}
}
// And somewhere else you'll want to use that class :
List<Account> accounts = new ArrayList<>();
account.add(new Account("Account1", 1, 1f));
account.add(new Account("Account2", 2, 2f));
account.add(new Account("Account3", 3, 3f));
I suggest you to consider learning basic object oriented programming (ie:Composition, Inheritance, Polymorphism)
Hope this example help.
PS : In a real life application, I would recommend the use of the BigDecimal class to handle money, as float (and double) have precision problems.
Related
So I am doing some revision in preparation for a uni GUI exam.
My Enum has a list of >20 items that all have a unique name and cost.
This is my current enum
public enum List
{
Brush ("Brush", 2),
Clock ("Brush", 5);
private String name;
private int cost;
private List(String name, int cost)
{
this.name = name;
this.cost = cost;
}
}
I want the user to select an item option in which it references the enum and gets the specific name and cost so I can output it into cost calculations and print lines. How would I be able to do that? All I know is that it can use indexes to search for it but I'm not too sure.
I am working on a Java app for a school project where we have to enter user information: Name, Student ID and their points. How can I store all the data for each user on an ArrayList (or an Array or really whatever type) so I can keep track of all the data.
Example:
John Doe - 401712 - 20 points
Jack Young - 664611 - 30 points
The I want to be able to call methods like setPoints to change the point values for whatever the student selected is.
Here's the problem: How can I link the ArrayList together. If I have three ArrayLists, how does Java know what name, student id and points are associated together?
All the ArrayLists are stored in a class called Data.
Data data = new Data();
Also, all the ArrayLists in the Data class should be outputted to a file which will be loaded next time the app is opened.
I will try to answer any questions.
You need to define a class which contain 3 data fields as follows
Name
Student ID
their points
But not to forget, the class has to have other necessary elements of a class like:
Constructor
Overloaded Constructors if they are necessary
Accessors
Mutators
Note: For accessing each part of an object in your arrayList, you can use accessors. For manipulating each part of an object in your arrayList, you can use mustators.
After having such a class, you can define a arrayList that contain elements with type of class you have already define
Like:
List<Your Type of class > students = new ArrayList<Your Type of class>;
After Java 7, you can do
List<Your Type of class > students = new ArrayList<>;
which is diamond inference.
If you are looking for a specific id number in your arrayList, you can do something like:
public boolean findIdNumber(int idNumber){
for(int i=0; i< students.size; i++)
if(students.get(i).getID() == idNumber)
return true;
else
return false;
}
Warning:
what I have done are suggestions for you to be able to look for what you want smoother. You need to do necessary changes in order to comply what you were
asked to do
You need to create a class named Student, and then declare an array/ArrayList of the Student type. Your Student class must have a constructor that sets the fields of an instance of the Student class (the created instance is now called an object).
So first create a Student class in the same package in which your other class is (the class in which your main method is):
public class Student {
private String firstName;
private String lastName;
private String studentId;
private int points;
public Student(String firstName, String lastName, String studentId, int points) {
this.firstName = firstName;
this.lastName = lastName;
this.studentId = studentId;
this.points = points;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
}
Then in your main method or wherever you like, create a Hashmap to hold your Student objects. A map/hashmap is a collection just like an ArrayList to hold a set of objects. In your use case, it is better to use a hashmap because finding/retrieving a specific student object is much faster and easier when you use a hashmap.
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
// a map is a "key-value" store which helps you search items quickly
// (by only one lookup)
// here you consider a unique value of each object as its 'key' in the map,
// and you store the whole object as the value for that key.
// that is why we defined Student as the second type in the following
// HashMap, it is the type of the "value" we are going to store
// in each entry of this map.
Map<String, Student> students = new HashMap<String, Student>();
Student john = new Student("John", "Doe", "401712", 20);
Student jack = new Student("Jack", "Young", "664611", 30);
students.put("401712", john);
students.put("664611", jack);
Student johnRetrieved = students.get("401712");
// each hashmap has a get() method that retrieves the object with this
// specific "key".
// The following line retrieves the student object with the key "664611".
Student jackRetrieved = students.get("664611");
// set/overwrite the points "field" of this specific student "object" to 40
johnRetrieved.setPoints(40);
int johnsPoints = johnRetrieved.getPoints();
// the value of johnsPoints "local variable" should now be 40
}
}
The classical object-oriented approach would be to create a Student class including name, ID and points and storing list of Student objects in a single ArrayList.
class Student{
private String id;
private String name;
private int points;
public Student(String id, String, name, int points){
this.id = id;
this.name = name;
this.points = points;
}
}
..
ArrayList<Student> students = new ArrayList<Student>();
students.add(new Student(1, 'John Doe', 1000));
String id = students.get(0).id;
This is related to a Java homework assignment.
I've written a class for creating instances of Course Objects, each course has parameters like course name, max number of students and a room number. However for some of the classes the room is not known. Is there a way to initialize and a Course Object without the room number?
public class ITECCourse {
private String name;
private int code;
private ArrayList<String> students;
private int maxStudents;
private int room = 0;
. . .
//Constructor
public ITECCourse(String courseName, int courseCode, int courseMaxStudents, int room) {
this.name = courseName;
this.code = courseCode;
this.students = new ArrayList<String>();
this.maxStudents = courseMaxStudents;
this.room = room;
You have a few options:
You could create a second constructor that does not take a room number:
public ITECCourse(String courseName, int courseCode, int courseMaxStudents)
You could change room from and int to an Integer. This would allow a null value.
Either way, you'd want to add a method setRoomNumber() to allow the user to provide that value later.
Yes, you can overload the constructor. As well as the constructor that you have above you can add a new one to the class that would look like this:
public ITECCourse(String courseName, int courseCode, int courseMaxStudents) {
this(courseName, courseCode, courseMaxStudents, 0);
}
This would then allow you to not have the room default to a certain value in the case that it has not been set.
Another good thing about doing it this way is that by calling the other already existing constructor you're not running into the issue of repeating code everywhere (to set all the values).
See this question for more details on best practices
Add a second constructor that doesn't take (or set) the room number.
I need to have a user type in a sixteen-digit number (without suffixes or quotes) and then pass that number to an object. Whenever I attempt to enter such a number, it is considered "datatype int out of range". I don't want the user to have to enter it as XXXXXXXXXXXXXXXXL, because the user may not know that java requires an L for longs. I also don't want it to require quotes around the numbers. Is there a way to convert this before java throws exceptions regarding datatype mismatch or out of range exceptions?
Can this even be done? I'm trying to construct a Customer object that's a field in an Order object, which itself is within an ArrayList<Order> orderList. "Sam Totman" and the number next to it are examples of the parameters I'm using.
orderList.get(1).setBuyer(new Customer("Sam Totman", 2112112121121121));
What should go where I have placed datatype in this constructor? ccn is credit card number;
public class Customer
{
private String name;
private *datatype* ccn;
Customer(String name, *datatype* ccn)
{
this.name = name;
this.ccn = ccn;
}
orderList.get(1).setBuyer(new Customer("Sam Totman", new Scanner(System.in).nextLong());
Use scanner to handle input
Scanner scan = new Scanner(System.in);
long aLong = scan.nextLong(10);
....
orderList.get(1).setBuyer(new Customer("Sam Totman", aLong));
Customer
public class Customer
{
private String name;
private long ccn;
Customer(String name, long ccn)
{
this.name = name;
this.ccn = ccn;
}
}
I am fairly new to object oriented programming, so I am still having some trouble grasping some of the basic concepts. So here I am trying to create a basic inventory program to keep track of stocks. Each stock contains couple details: company name, stock rating (AAA, AAa, Aaa, stuff like that), purchase price and numbers of shares. The program will ask user to input these details through command line prompt. And users can only input at most 12 stocks. If the user enters a stock twice, it will print out an error. And if the user has inputted one stock twice, it will also print out an error message.
Here is what I have done so far: Stock object
public class Stock {
private String companyName;
private String stockRating;
private int price;
private int numberOfShares;
public String getCompanyName() {
return companyName;
}
public int getStockRating() {
return stockRating;
}
public String getPrice() {
return price;
}
public int getNumberOfShares() {
return numberOfShares;
}
public Stock(String companyName, String stockRating, int price, int numberOfShares) {
super();
this.companyName = companyName;
this.stockRating = stockRating;
this.price = price;
this.numberOfShares = numberOfShares;
}
Now, I am trying to create stock inventory program
import java.util.*;
public class StockInvetory {
private static final int INVENTORY_SIZE = 12;
private Stock [] stocks;
public StockInvetory() {
stocks = new Stock [INVENTORY_SIZE];
}
private static void StockInventory() {
for (int i = 0; i<INVENTORY_SIZE; i++){
Scanner console = new Scanner(System.in);
System.out.println ("Stock's name:");
String stockName = console.next();
System.out.println ("Stock's rating");
String stockRating= console.next();
System.out.println ("Stock's price:");
int stockPrice = console.nextInt();
System.out.println ("Numbers of shares: ");
int numberShares= console.nextInt();
stocks [i]= new Stock(stockName, stockRatings, stockPrice, numberShares);
}
public static void main (String [] args){
StockInventory();
}
}
So my questions are the following:
The first stock object program should be okay, my problem is the stock inventory program.
With this code, private Stock [] stocks, does it mean that the stock inventory program will store the info into an array? If it is, how do I store all the details associated with a particular stock, company name, price, etcs together. Do I have to create a multi-dimensional array in order of keep track of all the details? Like one row contains all the details about one stock, and second row contains details about another stock. And to determine if the user has entered one stock twice, do I use "equalsIgnoreCase" to do the comparison? I know I probably need to create another method for the stock Inventory.
Thank you very much in advance for your assistance.
Once you read in the name, rating, price, and share count, you need to call the constructor on your class Stock to create an instance of the class and assign it to the next item in your stocks[] array.
Like so:
stocks[0] = new Stock( stockName, stockRating, stockPrice, numberShares);
Then you'll need to put the lines of code that you're using to read from the console, plus my line that creates the new Stock object into a loop so that you can read in all 12 stocks:
for( int i = 0; i < INVENTORY_SIZE; i++ )
{
System.out.println ("Stock's name:");
String stockName = console.next();
System.out.println ("Stock's rating");
String stockRating= console.next();
System.out.println ("Stock's price:");
int stockPrice = console.nextInt();
System.out.println ("Numbers of shares: ");
int numberShares= console.nextInt();
stocks[i] = new Stock( stockName, stockRating, stockPrice, numberShares);
}
Now, this isn't perfect, since it will require users to always enter a full set of 12 stocks, so you'll need to figure out how to let the user abort out of the loop if they're done, and you'll still have to add that error checking you want, to ensure that no duplicates are entered, but it should initialize your individual objects and assign eachh one to the array elements.
private Stock [] stocks, does it mean that the stock inventory program
will store the info into an array? If it is, how do I store all the
details associated with a particular stock, company name, price, etcs
together.
Your array is like a list of stocks. But just because its one object, doesn't mean it only contains one piece of data. It can hold Strings, ints, and other user-defined data types. Therefore, you can store pieces of data relating to the stock inside the Stock object.
public class Stock {
private String companyName;
private String stockRating;
private int price;
private int numberOfShares;
Those are all stored in each Stock object, and can be accessed by the getter methods you defined.
int stockdata = stocks[4].getPrice();
However, to initialize your Stock array, you want to create a new Stock object for each area, like so:
for(int i = 0; i < INVENTORY_SIZE; i++) {
stocks[i] = new Stock(foo, bar, lorem, ipsum);
}
The variables used here are just placeholders, so you can create your parameters by reading from the console like you're doing above.
These design principles for OOP should help you understand the relationship between data and containers.
For the second part of your question, you can look at just comparing one of the data values, like companyName, or implementing an interface like Comparable.
for(Stock s : stocks) {
if(stockName.equals(s.getCompanyName()) {
// ERROR!
}
}
You may want to provide some way to break the loop in certain condition if user does not want to input all 12 information. However, it is totally on your requirements.
In that case, you may have to use other options like List or vector.
Each object can have multiple variables , like in your case rating, price ,name and share which are bound to each object. So when you store an object in an index of array, you are actually storing all those information contained by that object in one single place. So in this case, you do not have to create multidimensional array.
You can override your equals method based on what defines the object as equal and use it to determine if same stock is provided again. This will return true if both object are same, otherwise false.
You can post your updated code and log here so that you can get suggestion regarding your exception
In a real world scenario some questions come to mind:
price shouldn't be an integer because a price is usually an amount in a specific currency. Check this money related question.
Stock rating would be better represented using an Enum. See doc