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.
Related
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
My .txt file is
code1,description1,price1
code2,description2,price2
etc.
Using:
ArrayList<String> items = new ArrayList<String>();
String description;
File fn = new File("file.txt");
String[] astring = new String[4];
try{
Scanner readFile = new Scanner(fn);
Scanner as = new Scanner(System.in);
while (readFile.hasNext()){
astring = readFile.nextLine().split(",");
String code = astring[0];
items.add(code);
description = astring[1];
}
}catch(FileNotFoundException){
//
}
for(String things: items){
System.out.println("The code is: " + things + "The description is " + description);
}
My output prints out
code1 description1
code2 description1
code3 description1
I'm trying to figure out how to make the description update as the code's do. e.g.
code1 description1
code2 description2
code3 description3
If this question has been asked already, I apologize. I couldn't find out how to do it by searching around but if there's a reference to figure this out I'll close this down and go there. Thanks in advance!
The problem is with your logic. You are storing only astring[0] to the items ArrayList and overwriting the value of description each time. As a result on last value read is stored in description which you are printing in the loop.
I prefer creating a custom class as follows. (Just for the sake of demo otherwise you would declare your fields as private and provide getters and setters)
class MyObject {
public String code;
public String description;
public String price;
}
now instead of creating ArrayList of Strings you will create ArrayList of MyObject as follows
ArrayList<MyObject> items = new ArrayList<MyObject>();
now create a new instance of MyObject each time you read a line , populate its fields with the values from astring as follows
ArrayList<MyObject> items = new ArrayList<MyObject>();
File fn = new File("test.txt");
String[] astring = new String[4];
try {
Scanner readFile = new Scanner(fn);
Scanner as = new Scanner(System.in);
MyObject myObject;
while (readFile.hasNext()) {
astring = readFile.nextLine().split(",");
myObject = new MyObject();
myObject.code = astring[0];
myObject.description = astring[1];
myObject.price = astring[2];
items.add(myObject);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
and then finally print it using the same foreach loop as follows
for (MyObject item : items) {
System.out.println("The code is: " + item.code + " The description is: " + item.description + " The price is: " + item.price);
}
Output
The code is: code1 The description is: description1 The price is: price1
The code is: code2 The description is: description2 The price is: price2
The reason you're seeing that output is that you are not saving description along with the code inside the list, that is why the last description is saved within the description variable not all description values.
To solve this problem, you can create a simple Java Bean/POJO class
and wrap your data inside it and then you can simply fetch the value
you have saved it and then show it properly. Take a look at the code
below:
public class Launcher{
public static void main(String[] args) {
ArrayList<Item> items = new ArrayList<Item>();
File fn = new File("file.txt");
try {
Scanner readFile = new Scanner(fn);
while (readFile.hasNext()) {
String[] astring = readFile.nextLine().split(",");
String code = astring[0];
String description = astring[1];
String price = astring[2];
Item item = new Item(code, description, price);
items.add(item);
}
} catch (FileNotFoundException d) { // }
}
for (Item thing : items) {
System.out.println(String.format("The code is: %s\tThe description is: %s\tThe Price is %s",thing.getCode(),thing.getDescription(), thing.getPrice()));
}
}
}
class Item {
private String code;
private String description;
private String price;
public Item(String code, String description, String price) {
this.code = code;
this.description = description;
this.price = price;
}
public String getCode() {
return code;
}
public String getDescription() {
return description;
}
public String getPrice() {
return price;
}
}
public class SimpleDialogueBox {
public static void main(String[] args){
String name = JOptionPane.showInputDialog("Name");
String age = JOptionPane.showInputDialog("age");
String address = JOptionPane.showInputDialog("Address");
String contact = JOptionPane.showInputDialog("Contact Number");
JOptionPane.showMessageDialog(null, "User information is", name);
}
}
I want to have a display like this:
Explanation
The method JOptionPane#showMessageDialog takes a regular object to display, a String for example, nothing fancy. From its documentation:
public static void showMessageDialog(Component parentComponent, Object message) throws HeadlessException
Brings up an information-message dialog titled "Message".
Parameters:
parentComponent - determines the Frame in which the dialog is displayed; if null, or if the parentComponent has no Frame, a default Frame is used
message - the Object to display
So you just have to build the String you want to display and then you pass it to the method. You can concatenate Strings using the + operator:
String lineSep = System.lineSeparator();
String message = "User information is: " + name + lineSep;
And so on. You can also use a StringBuilder for this purpose, it is also more efficient to use it for various reasons.
Code
Here is the full code:
String name = JOptionPane.showInputDialog("Name");
String age = JOptionPane.showInputDialog("age");
String address = JOptionPane.showInputDialog("Address");
String contact = JOptionPane.showInputDialog("Contact Number");
String lineSep = System.lineSeparator();
StringBuilder result = new StringBuilder();
result.append("User information is: ").append(lineSep).append(lineSep);
result.append("Name: ").append(name).append(lineSep);
result.append("Age: ").append(age).append(lineSep);
result.append("Address: ").append(address).append(lineSep);
result.append("Contact Number: ").append(contact);
JOptionPane.showMessageDialog(null, result.toString());
And that is the resulting dialog:
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);
}
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.