So I'm working on a program to interface with a file based database. Mostly I'm trying to figure out how to work with it so that I can make objects and store their information in the database so that I can pull the data later.
IE Object Taylor
Name = Taylor
Age = 20
School = Whatever
So that I can get back on and call that information up when queried.
This is an example of an object I want to store. I may be doing this part wrong.
package com.catalyse.db;
public class Taylor implements java.io.Serializable
{
public String name = "Taylor M May";
public int age = 20;
public String school = "UC Boulder";
}
The DB structure I'm using is based on RandomAccessFile and I didn't make it, I'm just trying to figure out how to implement it.
package com.catalyse.db;
import java.util.*;
import java.util.Scanner;
/**
* Simple test class for the RecordsFile example. To run the test,
* set you CLASSPATH and then type "java hamner.dbtest.TestRecords"
*/
public class Run {
static void log(String s) {
System.out.println(s);
}
private static String name()
{
Scanner name = new Scanner(System.in);
String name1 = name.next();
return name1;
}
public static void main (String[] args) throws Exception {
System.out.println(new Date());
Scanner SC = new Scanner(System.in);
log("What would you like to name the database?");
String filename = SC.next();
log("creating records file...");
RecordsFile recordsFile = new RecordsFile(filename+".records", 64);
log("adding a record...");
RecordWriter rw = new RecordWriter("foo.username");
rw.writeObject(new Taylor());
recordsFile.insertRecord(rw);
log("reading record...");
RecordReader rr = recordsFile.readRecord("foo.username");
Taylor name = (Taylor)rr.readObject();
System.out.println("\tlast access was at: " + name.toString());
log("test completed.");
}
}
And here is what I get back from it,
Wed Nov 20 11:56:04 MST 2013
What would you like to name the database?
save3
creating records file...
adding a record...
reading record...
last access was at: com.catalyse.db.Taylor#50aed564
test completed.
My problem is that I want it to return information about the class, not just its name and location in the DB.
You need to override the toString method.
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("Name: ");
sb.append(this.name);
//rest of fields
return sb.toString();
}
As a matter of clarity, you are not returning its location in the database. You are getting back the object hashValue + the class name.
At this point
Taylor name = (Taylor)rr.readObject();
You can access whatever information you like in the object, e.g.
Taylor name = (Taylor)rr.readObject();
System.out.println(name.age + ", " + name.name + ", " + name.school);
Alternatively, just add a
public String toString()
{
return name + ", " + age + ", " + school;
}
method in Taylor and then output it like so
Taylor name = (Taylor)rr.readObject();
System.out.println(name);
Now, concerning...
System.out.println("\tlast access was at: " + name.toString());
name.toString() isn't really required. If you append an object to a String then it automatically calls that objects toString() method to get a value.
Lastly, I'd like to note that generally we don't access object members like name, school and age by just accessing them. We generally make them private members then add methods to get and set them, so that we control and can track how they are manipulated.
Related
I am a newbie of c++.
Now I am doing a project need to read a customer list from a csv file and then search if there is a username like "Ali" and printout all the data about Ali.
How can I search "Ali" and printout all the data about Ali like CustomerNo , Name , PhoneNo and Status?
And if there is multiple data with "Ali" , how can I printout all of them either?
Here is my code:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Iterator;
public class LoadCustomer {
public static void main(String[] args) throws IOException{
System.out.println ("Load customer from file");
ArrayList<Customer> customers = readCustomerFromFile();
System.out.println (customers);
System.out.println ();
private static ArrayList<Customer> readCustomerFromFile() throws IOException{
ArrayList<Customer> customers = new ArrayList<>();
List<String> lines = Files.readAllLines(Paths.get("customer.csv"));
for (int i = 1 ; i < lines.size() ; i++){
String[] items = lines.get(i).split(",");
int customerNo = Integer.parseInt(items[0]);
int phoneNo = Integer.parseInt(items[2]);
customers.add (new Customer(customerNo,items[1],phoneNo,items[3]));
}
return customers;
}
}
Here is my Customer class:(added getName getter)
public class Customer {
private int customerNo;
private String name;
private int phoneNo;
private String status;
public Customer () {}
public Customer (int customerNo, String name, int phoneNo, String status){
this.customerNo = customerNo;
this.name = name;
this.phoneNo = phoneNo;
this.status = status;
}
public String getName(){
return name;
}
public String toString(){
return customerNo + " " + name + " " + phoneNo + " " + status;
}
public String toCSVString(){
return customerNo + "," + name + "," + phoneNo + "," + status;
}
}
And here is my data:
CustomerNo Name PhoneNo Status
1 Ali 12345 Normal
2 Siti 23456 Normal
3 Rone 78910 Normal
4 Jean 56789 Normal
5 Roby 28573 Normal
6 Ali 78532 Normal
Thank you very much for your attention.
Edited :
Here is my code for this program:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
public class FindCustomer {
public static void main(String[] args) throws IOException{
System.out.println ("Load customer from file");
java.util.Map<String, List<Customer>> customers =
Files.lines(Paths.get("customer.csv"))
.map(line -> line.split(","))
.map(field -> new Customer(
Integer.parseInt(field[0]), field[1],
Integer.parseInt(field[2]), field[3]))
.collect(Collectors
.groupingBy(Customer::getName));
System.out.println (customers);
}
}
Bit of a broad question.
If you expect to do this a lot, and on a boatload of data, do what everybody else does when they are faced with a lot of relational data that they need to run queries on. Use a database, like postgres or h2. To interact with those from java, use JDBI or JOOQ.
If this is just a small simple text file and/or you're trying to learn some java, well, you still have two options here: You can loop through the data, or, you can build a mapping.
The loop option is simple:
for (Customer c : customers) if (c.getName().equals("Ali")) {
// do what you want here. 'c' holds the customer object of Ali.
}
But this does, of course, require a full run through all the entries every time. Another option is to build a mapping:
var map = new HashMap<String, Customer>();
for (Customer c : customers) map.put(c.getName(), c);
// map now maps a customer name to the customer object.
Customer ali = map.get("Ali");
maps have the advantage that they are near instant lookup. Even if the map contains a million entries, map.get(x) is (near) instant. A decent solution if you have lots of data + the need to do lots of lookups. But, you have to build a complete map for everything you care to query on. So, if you want to do lookups on name, and then later something like 'get all customers with a 6 digit phone number whose status is Normal', then, get a database.
As was suggested a map would be useful. You can create one on the fly as you read in the file.
Splits the line
creates a customer.
and groups it by name in a map.
Now the map will hold for each name, all customers that have that name.
Map<String, List<Customer>> customers =
Files.lines(Paths.get("customer.csv"))
.map(line -> line.split("\\s*,\\s*"))
.map(field -> new Customer(
Integer.parseInt(field[0]), field[1],
Integer.parseInt(field[2]), field[3]))
.collect(Collectors
.groupingBy(Customer::getName));
To get the List of customers for the name Ali do the following.
List<Customer> ali = customers.get("Ali");
Now it's up to you to format or otherwise use the list as required. You will still need to handle exceptions via try/catch.
currently, I'm doing an assignment that deals with the ArrayList class.
at some point, I need to check of the id of the instructor and make sure that the instructor is not added twice to the ArrayList, so I made a for loop to go through all the id that has been registered and get the id and check if it exists already
the problem is when I use the method " .size()" in the loop, the JVM throws NullPointerException
and I don't know why.
==========================================================================
what I need to read is this:
\\name - id - dateOfBirth - gender - degree - speciality - city - availability
Amanda Smith, 102020, 320101200000, M, PhD, Software Engineering, NewYork, true
=======================================================================
this is the code:
public static void main(String[] args) {
/* NOTE: I HAVE A CLASS CALLED "UniversityMember" THAT IS A SUPERCLASS FOR "Instructor" CLASS */
//declare what I need
ArrayList<UniversityMember> membersList;
Scanner read = new Scanner("inputFile.txt");//the file contains the text above
//First: Split the line everytime the sign ", " shows
String[] line = read.nextLine().split(", ");
//Second: Assign each valuse to its correspondeding variable
String name = line[0];
String id = line[1];
long date = Long.parseLong(line[2]);
Date birthDate = new Date(date);
char gender = line[3].charAt(0);
String degree = line[4];
String specialization = line[5];
String address = line[6];
boolean availability = Boolean.parseBoolean(line[7]);
//check if the Id is registered already
for (int i = 0; i < membersList.size(); i++) { //ERROR OCCURE
if (membersList.get(i) == null) {
break;
}
if (membersList.get(i).id.equals(id)) {
System.out.println("The instructor is registered already, the ID is found in the system.");
System.exit(0);
}
}
//add and make a new object for the constructor
membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
System.out.println("The instructor is successfully added.");
}//end main
The problem is membersList doesn't exist when you call .size() on it
instead of
ArrayList<UniversityMember> membersList;
you need to initialize it
ArrayList<UniversityMember> membersList = new ArrayList<UniversityMember>();
You need to initialize the ArrayList.
Like that ArrayList membersList = new ArrayList();
After that, in the first size() returns 0 and not null. Remember all data structure must be initialize in java.
You haven't added anything to the membersList then asking for the size for something that has nothing in it.
Example of whats going on
String str;
for(int i = 0; i < str.length(); i++){
System.out.println("hey");
}
also you need to declare the array list like this
ArrayList<Method name> membersList = new ArrayList<Method name>();
also don't forget to import the ArrayList class
import java.util.ArrayList;
nvm I figured out that I haven't initialized my array ( ╥ω╥ )
I'll keep the question for others to be carefull
==================================================
The code after fixing it:
public static void main(String[] args) {
/* NOTE: I HAVE A CLASS CALLED "UniversityMember" THAT IS A SUPERCLASS FOR "Instructor" CLASS */
//declare what I need
ArrayList<UniversityMember> membersList;
Scanner read = new Scanner("inputFile.txt");//the file contains the text above
/* ===== FIXING THE ERROR ======*/
membersList = new ArrayList();
//First: Split the line everytime the sign ", " shows
String[] line = read.nextLine().split(", ");
//Second: Assign each valuse to its correspondeding variable
String name = line[0];
String id = line[1];
long date = Long.parseLong(line[2]);
Date birthDate = new Date(date);
char gender = line[3].charAt(0);
String degree = line[4];
String specialization = line[5];
String address = line[6];
boolean availability = Boolean.parseBoolean(line[7]);
//check if the Id is registered already
for (int i = 0; i < membersList.size(); i++) {
if (membersList.get(i) == null) {
break;
}
if (membersList.get(i).id.equals(id)) {
System.out.println("The instructor is registered already, the ID is found in the system.");
System.exit(0);
}
}
//add and make a new object for the constructor
membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
System.out.println("The instructor is successfully added.");
}//end main
I've been teaching myself java and I've stuck on a problem that no matter what I do can't seem to solve. I've done some research but all the options provided don't seem to work. Hopefully you guys might be able to teach me something.
I have a .txt file that contains:
AccountName1:Password1
AccountName2:Password2
AccountName3:Password3
AccountName4:Password4
AccountName5:Password5
The elements of the file are then read and inserted into a List:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public abstract class AccountFileReader {
private static Scanner sc;
public static void main(String[] args) {
try {
// Enables ability to find file in any OS.
String file = File.separator + "some folder name"
+ File.seperator + "AccNamePw.txt";
File f = new File(file);
sc = new Scanner(f);
List<AccountInfo> accounts = new ArrayList<AccountInfo>();
String name = "";
String password = "";
while (sc.hasNext()){
// Reads and checks if there is a new line
String line = sc.nextLine();
// Creates delimiter to make the different elements on file f
String[] details = line.split(":");
// Initializes 1st element
name = details[0];
// Initializes 2nd element
password = details[1];
// Creates new object "a" that has the 2 elements from each line
AccountInfo a = new AccountInfo(name, password);
// Adds the "a" object to the "accounts" List
accounts.add(a);
}
// Iterates list and prints out the list
for(AccountInfo a: accounts){
// The hiccup is in here somewhere. This for loop isn't working in
// a way I think it's supposed to.
// Create new object of the getter, setter class to use in this loop
AccountInfo namPw = new AccountInfo(name, password);
name = namPw.getName();
password = namPw.getPassword();
System.out.println(a.toString() + " " + name
+ " " + password);
}
} catch (FileNotFoundException e) {e.printStackTrace();}
}
}
The getter/setter class is as follows:
public class AccountInfo{
private String name;
private String password;
public AccountInfo(String name, String password) {
this.setName(name);
this.setPassword(password);
}
public void setName(String name) { this.name = name; }
public String getName() { return name; }
public void setPassword(String password) { this.password = password; }
public String getPassword() { return password; }
public String toString(){ return name + " "+ password; }
}
My output is:
AccountName1:Password1 AccountName5:Password5
AccountName2:Password2 AccountName5:Password5
AccountName3:Password3 AccountName5:Password5
AccountName4:Password4 AccountName5:Password5
AccountName5:Password5 AccountName5:Password5
But I want it to return:
AccountName1:Password1 AccountName1:Password1
AccountName2:Password2 AccountName2:Password2
AccountName3:Password3 AccountName3:Password3
AccountName4:Password4 AccountName4:Password4
AccountName5:Password5 AccountName5:Password5
I know that the a.toString() is returning correctly but my namPw.getName() and namPw.getPassword() are only giving me the last element of the List.
What am I not understanding and or missing? How do I get namPw.getName() and namPw.getPassword() to return the List correctly?
The problem is the declaration of nameand password right before the while loop. These variables store the last encountered username and password. When the while loop ends, these variables store the values AccountName5 and Password5 respectively.
When you enter the second for-loop, you first create a new UserAccount with using nameand password which store AccountName5 and Password5.
If you just want to print this list, you do not need to create a copy of the contents of the list. Just do:
for(AccountInfo a : accounts) {
System.out.println(a.toString() + " " + a.getName() + " " + a.getPassword());
}
It's because of this:
for(AccountInfo a: accounts){
**AccountInfo namPw = new AccountInfo(name, password);**
name = namPw.getName();
password = namPw.getPassword();
System.out.println(a.toString() + " " + name
+ " " + password);
You are looping through the AccountInfo objects you already created and then creating a new AccountInfo object and passing in name and password (which get set each time you read in a new line, so the value for them would be the last thing they would be set to when reading the file)
Not sure why you are creating a new AccountInfo object. But in order to get what you want, you'd need to do this:
AccountInfo namPw = new AccountInfo(a.getName(), a.getPassword());
No need to create new object in loop. You are already getting object in a.
Remove object creation line. It is creating object with name and and password which is never going to change as it is outside the loop.
Checkout the following solution:
for(AccountInfo a: accounts){
name = a.getName();
password = a.getPassword();
System.out.println(a.toString() + " " + name + " " + password);
}
How to store 2 integer in array list from result set and how to retrieve it.
I am trying to store the 2 integer to my array list and i don't know if get it correctly because when I am trying to retrieve it, it prints something like this
'tryCheckout$checkout#4f4fffa4' Thanks guys. This is my code so far.
public class checkout{
public int roomtypeid,itemid;
}
ArrayList<checkout> returncheckout = new ArrayList<checkout>();
try{
*String query ="select ri.item_id, ri.roomtype_id from roomtype_tb as rt , roomtypeitem_tb as ri , room_tb as r , reserverooms_tb as rr where rt.roomtype_id = r.roomtype_id and rt.roomtype_id = ri.roomtype_id and ri.roomtype_id = r.roomtype_id and r.room_id = rr.room_id and rr.reservation_id = 10";
PreparedStatement pst =conn.prepareStatement(query);
ResultSet rs = pst.executeQuery();
while(rs.next())
{
checkout out = new checkout();
out.roomtypeid = rs.getInt("ri.roomtype_id");
out.itemid = rs.getInt("ri.item_id");
returncheckout.add(out);
}
returncheckout.forEach(System.out::println);
}catch(Exception e)
{
e.printStackTrace();
}*
I didn't see your checkout class. Now I do. Change it to
public class checkout{
public int roomtypeid,itemid;
#Override
public String toString()
{
return "roomtypeid =" + roomtypeid + ", itemid=" + itemid;
}
}
In your checkout class override the toString() method. That is a special method that gets called when an object gets passed to System.out.println. It will look something like this:
#Override
public String toString()
{
return "roomType=" + roomType + ", id=" + id;//Not sure what your variables are. You will need to change this line
}
I think your code is doing what you want, you just need the toString() method to print the result out like you want it.
Java is actually returning the memory address for the object checkout. That is the weird numbers that are output to the screen. Add something like this to the checkout class.
public class checkout{
public int roomtypeid, itemid;
#Override
public String toString()
{
return "Room Type ID: " + roomtypeid + " Item ID: " + itemid";
}
}
The toString() method is called when the object is printed.
I am have trouble creating an array or object(with multiple fields) and sending it to an array-list. Any help would be greatly appreciated. I have spent hours looking through every video on YouTube with the words object and array-list in them and have been unable to find much help.
The program needs to prompt the user to pick a option (1. AddItem) then prompt the user for the name and format (dvd, vhs) and save multiple objects with these variables in an array-list. I either keep having the location where it is saved in memory returned to me or instead of multiple objects one large object is created.
Library:
import java.util.Scanner;
import java.util.ArrayList;
public class Library {
static ArrayList<Object> items = new ArrayList<Object>();
static int menuOption;
static Scanner scan = new Scanner(System.in);
public static void main(String args[]) {
String title, format;
boolean right = false;
do{
displayMenu();
if (menuOption == 1){
System.out.println("Enter Title: ");
title = scan.next();
System.out.println("Enter format: ");
format = scan.next();
addNewItem(title, format);
} else {System.out.println(items);
}
} while (!right);
}
static int displayMenu(){
System.out.println("Menu: ");
System.out.println("1. Add New Item");
menuOption = scan.nextInt();
return menuOption;
}
static void addNewItem(String title, String format){
MediaItem b = new MediaItem();
b.setTitle(title);
b.setFormat(format);
items.add(b);
}
}
MediaItem:
public class MediaItem {
String title;
String format;
MediaItem(){
title = null;
format = null
}
MediaItem(String title, String format){
title = new String();
format = new String();
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
}
The program will run if you:
1 - Change the line
static ArrayList<Object> items = new ArrayList<Object>();
to
static ArrayList<MediaItem> items = new ArrayList<MediaItem>();
2 - Change the line
System.out.println( items );
to
for ( MediaItem mi : items )
{
System.out.println( mi.getTitle() + ", " + mi.getFormat() );
}
3 - Insert a ";" at the end of the line
format = null
I did it here and it worked.
I either keep having the location where it is saved in memory returned to me
I am guessing you ran into this when you tried to either use System.out.println() to print a MediaItem, or you otherwise tried to automatically convert an object to a string. Whatever approach you took when you were seeing the memory addresses is probably the right way to do it, your problem was only in your displaying of the data.
Consider:
MediaItem item = ...;
System.out.println(item);
By default, Java doesn't know how to convert arbitrary objects to strings when you do stuff like that, and so it just spits out the class name and memory address. You either need to print the fields separately (e.g. Java knows how to display a String already), like:
System.out.println("Title: " + item.getTitle() + " Format: " + item.getFormat());
Or you can override toString() (declared in Object) to provide a custom string conversion:
class MediaItem {
...
#Override public String toString () {
return "Title: " + title + " Format: " + format;
}
}
And then you can print it directly:
System.out.println(item);
It is the default base implementation of Object.toString() that produces those strings with the memory address in them.
Based on your description, I'm guessing you had a roughly working implementation but ran into this issue and ended up changing around (and breaking) a bunch of other unrelated things to try and fix it.