ArrayList & Array methods - java

I'm writing a simple code to show various details about a person. I've used arrays to create name.
When I try to run my code the location/ directory for name comes out as [Ljava.lang.String;#1f32e575.
My code runs results are:
Name
ii
jj
[Ljava.lang.String;#1f32e575 // code to remove
My code:
public static String[] name() {
System.out.println("Name");
n = new String[]{ "ii", "jj" };
for (int i = 0; i < n2.length; i++) {
System.out.println(n[i]);
}
}

Here, is your fixed code:
import java.util.ArrayList;
class Detail {
private String name;
private String nationality;
private static String[] hobby2;
public Detail() {
}
public String getName() {
return name = "A";
}
public String getNationality() {
return nationality = "abc";
}
public void setInfo(String name, String nationality) {
this.name = name;
this.nationality = nationality;
}
public static void setHobbies() {
hobby2 = new String[] { "ii", "jj" };
System.out.println("Hobbies");
for (int i = 0; i < hobby2.length; i++) {
System.out.println("\t" + hobby2[i]);
}
}
public static void setWishes() {
System.out.println("Wishes");
ArrayList<String> allWishes = new ArrayList<String>();
allWishes.add("aa");
allWishes.add("bb");
allWishes.add("cc");
allWishes.add("dd");
for (String i : allWishes) {
System.out.println("\t" + i);
}
}
public void displayDetail() {
DOB d = new DOB();
System.out.println("Name: " + getName());
System.out.println("Nationality: " + getNationality());
System.out.println("Date of birth: " + d.dateString(1, "Jan", 1000));
setHobbies();
setWishes();
}
}
class DOB {
public String dateString(int day, String month, int year) {
String dob = (day + " " + month + ", " + year);
return (dob);
}
}
class Test {
public static void main(String[] args) {
MyInfo my = new MyInfo();
my.displayDetail();
}
}
The very first value you don't want was the object ID, you simply can't return the values of an object. If you want to see the values then you have to override the toString() method.
The second value was visible just because you returned the list. If you were using print() inside your method then there was no need to return it.
Tips: You need to get a better understanding of getter and setter methods because you have messed up the entire concept in your code. Your blank constructor is not needed. Rather, you should initialize all the fields (class variables of Detail class) in the constructor.

Remove System.out.println in displayDetail() method as below,
setHobbies();
setWishes();

Related

Why is there multiple output when I call from an arraylist?

import java.util.ArrayList;
class BryanList{
public static void main (String [] args)
{
ArrayList<String> alist=new ArrayList<String>();
alist.add("Bryan");
alist.add("18");
alist.add("Chicken Rice");
for (int i = 0; i <= alist.size(); i++) {
System.out.println ("My Name: "+alist.get(i));
System.out.println ("Age: "+alist.get(i));
System.out.println ("Favourite food: "+alist.get(i));
}
}
}
How come its not just displaying just one output instead there's 3 of the same output? Does anyone have any solution for this? Thanks.
If you want one time output then use generics class structure.
Create one class which you want to save records.
class Menu {
public int age;
public String name;
public String favFood;
}
You can create getter/setter method if you need. Otherwise just declare variables with public keyword.
Create one ArrayList which will store object of Menu class.
ArrayList<Menu> alist = new ArrayList<Menu>();
Menu menu = new Menu();
menu.name = "Bryan";
menu.age = 18;
menu.favFood = "Chicken Rice";
alist.add(menu);
Print output
for (int i = 0; i <= alist.size(); i++) {
Menu menu = alist.get(i);
System.out.println("My Name: " + menu.name);
System.out.println("Age: " + menu.age);
System.out.println("Favourite food: " + menu.favFood);
}
I updated your class with your requirement, please check.
class BryanList {
public static void main(String[] args) {
ArrayList<Menu> alist = new ArrayList<Menu>();
Menu menu = new Menu();
menu.name = "Bryan";
menu.age = 18;
menu.favFood = "Chicken Rice";
alist.add(menu);
for (int i = 0; i <= alist.size(); i++) {
Menu menu = alist.get(i);
System.out.println("My Name: " + menu.name);
System.out.println("Age: " + menu.age);
System.out.println("Favourite food: " + menu.favFood);
}
}
}
class Menu {
public int age;
public String name;
public String favFood;
}
Happy coding :)
Your loop check is happening on alist.size() which is in your case 3.
Now, in each iteration, it's printing alist.get(i) 3 times.
Suggestion:
Use POJO and add it to your list.
public class Person{
String name;
int age;
String favFood;
public getName(){
return name;
}
public getAge(){
return age;
}
public getFavFood(){
return favFood;
}
public setName(String name){
this.name = name;
}
public setName(int age){
this.age = age;
}
public setName(String favFood){
this.favFood = favFood;
}
}
And now, your code will work with simple modification.
public static void main (String [] args){
ArrayList<String> alist=new ArrayList<String>();
Person person = new Person();
person.setName("Bryan");
person.setAge(18);
person.setFavFood("Chicken Rice");
// If you want multiple person to add, you need to use loops, and that way you can keep creating person objects and add them to list.
// Suggesting, use separate method for that logic.
alist.add(person);
for (int i = 0; i <= alist.size(); i++) {
Person p = alist.get(i);
System.out.println ("My Name: "+ p.getName());
System.out.println ("Age: "+ p.getAge());
System.out.println ("Favourite food: "+ p.getFavFood());
}
}
Because your printing codes in a For loop. And loop is running 3 three times
alist.size()
means 3, you have 3 item in that list.
This can be your object class:
public class Table {
int age;
String name;
String food;
public Table(int age, String name, String food) {
this.age = age;
this.name = name;
this.food = food;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFood() {
return food;
}
public void setFood(String food) {
this.food = food;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And fill arraylist with your object:
public static void main(String[] args) {
ArrayList<Table> alist = new ArrayList<>();
// this is how you fill
alist.add(new Table(18, "Bryan", "Rice");
for (int i = 0; i <= alist.size(); i++) {
System.out.println("AGE: " + alist.get(i).age);
//other stuff
}
}
import java.util.ArrayList;
public class HelloWorld {
public static void main(String []args) {
ArrayList<String> alist_name=new ArrayList<String>();
ArrayList<String> alist_value=new ArrayList<String>();
alist_name.add("My Name: ");
alist_name.add("Age: ");
alist_name.add("Favourite food: ");
alist_value.add("Bryan");
alist_value.add("18");
alist_value.add("Chicken Rice");
for (int i = 0; i < alist_name.size(); i++) {
System.out.println (alist_name.get(i)+alist_value.get(i));
}
}
}

Code not working. Ask user for 2 characters and search text file for strings that start with those two characters

The goal of this code is to ask the user for 2 characters, and output all the movies starting with those two characters from a text file. Should I make a new method for getTitle()? In MovieUsage it doesn't work right whether I use contains or equals. Not sure what to do after this. Any help is appreciated.
public class Movie
{
private String name;
public Movie (String name)
{
this.name = name;
}
public static ArrayList<Movie> loadDatabase() throws FileNotFoundException {
ArrayList<Movie> list = new ArrayList<>();
File f = new File("db.txt");
Scanner inputFile = new Scanner(f);
while (inputFile.hasNext())
{
String name = inputFile.nextLine();
int year = inputFile.nextInt();
inputFile.nextLine();
String genre = inputFile.nextLine();
Movie m = new Movie(name);
list.add(m);
}
return list;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String toSTring()
{
return name;
}
}
public class MovieUsage
{
public static void printRandomMovie(ArrayList<Movie> database)
{
System.out.println("Picking random movie from " + database.size() + " movies");
Random rng = new Random();
int subscript = rng.nextInt(database.size());
System.out.println("Your movie is: " + database.get(subscript));
}
public static void printMatchingMovies(ArrayList<Movie> database, String searchString) throws FileNotFoundException {
int numMatches = 0;
for (Movie temp : database)
{
if (temp.contains(searchString))
{
System.out.println(temp);
numMatches++;
}
}
System.out.println("Number of matches: " + numMatches);
}
public static void main(String[] args) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
ArrayList<Movie> database = Movie.loadDatabase();
System.out.println("Movie search by two characters. Enter two characters.");
String searchString = keyboard.nextLine();
System.out.println("Movies that start with " + searchString);
printMatchingMovies(database, searchString);
}
}
Thank you for the help in advanced.
You are searching if an ArrayList of Movie objects are equal to a String. I believe what you wanted to do is search for the title property (Or some similar String property) of the Movie class. So something like:
for(Movie movie: database) {
if(movie.getName().equals(searchString)) {
System.out.println(temp,toString());
//Convert the object to it's appropriate String representation
}
}
And in your Movie class (So you can access your private variables outside of your class):
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
Update the code by temp.getName().contains, since you are looking for characters under Movie object code has to be updated.
public static void printMatchingMovies(ArrayList<Movie> database, String searchString) throws FileNotFoundException {
int numMatches = 0;
for (Movie temp : database)
{
if (temp.getName().contains(searchString))
{
System.out.println(temp);
numMatches++;
}
}
System.out.println("Number of matches: " + numMatches);
}

Sorting with comparable (Java)

I've implemented the interface comparable and the method compareTo(). I have a list named randomHumans that contains 10 objects. 5 objects with three fields: name, age and year they started studying, and 5 objects with two fields: name and age. I would like to sort my list, and tried using:
Collections.sort(randomHumans);
This gave me the following error message:
The method sort(List<T>) in the type Collections is not applicable for the arguments (ArrayList<Object>)
I then tried this code:
Collections.sort((List<T>) randomObjects);
But it just gives me two new error messages. Maybe I need to specify what field it should sort after, but I can't find how to implement this. Any help would be greatly appreciated.
main method:
public static void main (String[] args) {
ArrayList<Object> randomObjects = new ArrayList<Object>();
for (int j=0; j<5; j++) {
Fysiker randomFysiker = new Fysiker();
randomObjects.add(randomFysiker);
Human randomHuman = new Human();
randomObjects.add(randomHuman);
}
System.out.println(randomObjects.toString());
//Collections.sort(randomObjects);
}
Human class:
class Human implements Comparable<Human> {
int age;
String name;
public Human (int myAge, String myName) {
name = myName;
age = myAge;
}
public Human() {
this(randomAge(),randomName());
}
public int compareTo(Human o) {
return this.age - o.age;
}
protected static int randomAge() {
Random randomGenerator = new Random();
return randomGenerator.nextInt(100);
}
protected static String randomName() {
Random randomGenerator = new Random();
return "Name"+randomGenerator.nextInt(15);
}
public int getAge(){
return age;
}
public String getName() {
return name;
}
public String toString() {
return "\nName: " + name + "\nAge: " + age + " yrs old\n";
}
}
Fysiker class:
public class Fysiker extends Human {
int year;
public Fysiker(int myAge2, String myName2, int myYear) {
name = myName2;
year = myYear+1932;
if (myAge2 >= 15+(2017-myYear)) {
age = myAge2;
} else {
age = 15+(2017-year);
}
}
public Fysiker() {
this(randomAge(),randomName(), randomYear());
}
protected static int randomYear() {
Random randomGenerator = new Random();
return randomGenerator.nextInt(83);
}
public int getYear(){
return year;
}
public String toString() {
return "\nName: " + name + "\nAge: " + age + " yrs old" + "\nStarted Physics: " + year+"\n";
}
}
Just change the generic parameter from Object to Human
public static void main (String[] args) {
List<Human> randomObjects = new ArrayList<>();
for (int j = 0; j < 5; j++) {
Fysiker randomFysiker = new Fysiker();
randomObjects.add(randomFysiker);
Human randomHuman = new Human();
randomObjects.add(randomHuman);
}
System.out.println(randomObjects);
Collections.sort(randomObjects);
}
When you write Collections.sort(randomHumans); randomHumans must be a List of Comparable. If you are 'forced' to use a List of Object, you must give a Comparator to explain how to compare each object :
Collections.sort(randomHumans, humanComparator);
It's all explained in the offcial documentation :
sort(java.util.List)
sort(java.util.List, java.util.Comparator)

Need various ways to come up with this output

I am supposed to come up with this output.
But I am getting this instead..
Here is my code:
import java.lang.*;
import java.util.*;
import java.io.*;
public class Sample{
private String name;
private Hashtable customers = new Hashtable();
private Hashtable movies = new Hashtable();
public Sample(String aName){
name = aName;
}
public String getName(){
return name;
}
public void setName(String aName){
name = aName;
}
public void addCustomer (Customer customer) {
customers.put(customer.getName(), customer);
}
public Customer getCustomer (String customerName) {
return (Customer)customers.get(customerName);
}
public void addMovie (Movie movie) {
movies.put(movie.getName(), movie);
}
public Movie getMovie (String movieName) {
return (Movie)movies.get(movieName);
}
public void error (String message) {
System.out.println ("ERROR: " + message);
}
public Enumeration getMovies() {
return movies.elements();
}
public Enumeration getCustomers() {
return customers.elements();
}
public void showAll() {
System.out.println ("name: "+ this.getName());
Enumeration kk = this.getCustomers();
while (kk.hasMoreElements()) {
Customer one = (Customer) kk.nextElement();
System.out.println (one.show());
}
Enumeration ff = this.getMovies();
while (ff.hasMoreElements()) {
Movie one = (Movie) ff.nextElement();
System.out.println (one.show());
}
}
public void test() {
Customer k1 = new Customer ("Jonah") ; this.addCustomer (k1);
Customer k2 = new Customer ("Hellen") ; this.addCustomer (k2);
Customer k3 = new Customer ("Agnes") ; this.addCustomer (k3) ;
Movie f1 = new Movie ("StarWars"); this.addMovie (f1) ;
Movie f2 = new Movie ("Shrek"); this.addMovie (f2) ;
System.out.println("-**-**- test part 1 -**-**-") ;
this.showAll();
System.out.println("-**-**- test part 2 -**-**-") ;
System.out.println("---" + k1.getName() + " rents " + f1.getName());
this.showAll();
k1.doRent(f1);
MY CUSTOMER CLASS:
package eric;
public class Customer {
String name;
public Customer(String nameCus){
name = nameCus;
}
public String getName(){
return name;
}
public String show(){
return name;
}
public void doRent(Movie f1) {
System.out.println(" -"+ " RentData" + "[" + getName() +"," + f1.getName() + "]" );
}
}
MY MOVIE CLASS:
public class Movie {
String name;
int x = 0;
public Movie(String nameMov){
name = nameMov;
}
public String getName(){
return name;
}
public String show(){
return name+"\n"+" - average: "+x +" days\n"+" - number of rentings: "+x ;
}
}
My problem is that i cannot find a way to fix -RentData [Jonah,StarWars] under the name Jonah... Instead it comes at the end of output.. I need some one to help me figure how am ganna do that.. thanks
You're calling k1.doRent(f1) before this.showAll() so naturally you will get the "RentData..." line printed before the names are printed. The way your code is now is not conducive to what you're trying to do at all. Your Customer class should have a member list called rentedMovies that is populated every time you call doRent(...) on a Customer object. Then, Customer.show() should print the name of the customer, followed by your "RentData..." stuff that comes from rentedMovies.

NullPointerException when adding Object to ArrayList

I'm very new to Java and have been trying to set-up an ArrayList CustomerList that takes object Customer, where Customer has attributes from class IAddress. When calling the .add method in my main code however, I am given a NullPointerException error, which I assume is being given because my method isn't receiving anything to add to the ArrayList. I thought it was an issue with the attributes being initialised to empty strings, but when editing them to contain some information, the error still occured.
The ArrayList CustomerList
public class CustomerList {
public ArrayList<Customer> Clients;
public CustomerList() {
Clients = new ArrayList<>();
}
public void add(Customer src) {
Clients.add(src);
}
public void remove(Customer src) {
Clients.remove(src);
}
public void Display(JTextArea jClientsTextArea) {
for (int i = 0; i < Clients.size(); i++) {
Clients.get(i).Display(jClientsTextArea);
}
}
}
Receives Customer from this class
public class Customer {
private String FirstName;
private String Surname;
private IAddress HomeAddress;
public String DOB;
public Customer() {
FirstName = "";
Surname = "";
DOB = "01/01/1900";
HomeAddress = new IAddress();
public void Display(javax.swing.JTextArea jAddressTextArea) {
jAddressTextArea.setLineWrap(true);
jAddressTextArea.append("First Name: " + FirstName + "\n");
jAddressTextArea.append("Surname: " + Surname + "\n");
jAddressTextArea.append("DOB:" + DOB + "\n");
jAddressTextArea.append("Street: " + HomeAddress.getStreet() + "\n");
jAddressTextArea.append("House Name: " + HomeAddress.getHouseName() + "\n");
jAddressTextArea.append("House Number: " + HomeAddress.getHouseNo() + "\n");
jAddressTextArea.append("Area: " + HomeAddress.getArea() + "\n");
jAddressTextArea.append("Postcode: " + HomeAddress.getPostCode() + "\n");
jAddressTextArea.append("Town: " + HomeAddress.getTown() + "\n");
jAddressTextArea.append("Country: " + HomeAddress.getCountry() + "\n");
}
public void Edit(String strfirstname, String strsurname, String strDOB, String strStreet, String strHouseName, String strHouseNo, String strHouseArea, String strPostCode, String strTown, String strCountry) {
FirstName = strfirstname;
Surname = strsurname;
DOB = strDOB;
HomeAddress.setStreet(strStreet);
HomeAddress.setHouseName(strHouseName);
HomeAddress.setHouseNo(strHouseNo);
HomeAddress.setArea(strHouseArea);
HomeAddress.setPostCode(strPostCode);
HomeAddress.setTown(strTown);
HomeAddress.setCountry(strCountry);
}
}
Which receives attributes from IAddress
public class IAddress {
private String Name;
private String Street;
private String HouseNo;
private String HouseName;
private String Area;
private String PostCode;
private String Town;
private String Country;
public IAddress() {
Name = "";
Street = "";
HouseNo = "";
HouseName = "";
Area = "";
PostCode = "";
Town = "";
Country = "";
}
public void setName(String strName) {
Name = strName;
}
public void setStreet(String strStreet) {
Street = strStreet;
}
public void setHouseNo(String strHouseNo) {
HouseNo = strHouseNo;
}
public void setHouseName(String strHouseName) {
HouseName = strHouseName;
}
public void setArea(String strArea) {
Area = strArea;
}
public void setPostCode(String strPostCode) {
PostCode = strPostCode;
}
public void setTown(String strTown) {
Town = strTown;
}
public void setCountry(String strCountry) {
Country = strCountry;
}
}
I've been banging my head against this problem for hours and am ready for it to be something stupidly simple. Thank you.
In your code above the only reason why calling myCustomerList.add(...) could throw is that myCustomerList itself is null. This is because the Clients inside it is initialized in the constructor, and never set to null again. The value of src does not matter as well - the call to Clients.add(src) would succeed even if src is null.
You need to make sure that in your main you do initialize your customer list, like this:
CustomerList list = new CustomerList();

Categories