Printing out an ArrayList consisting of Arrays [duplicate] - java

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
For an assignment in my programming class I need to create a program that can store countries. Every country has a name, a population & an area. (KM^2)
import java.util.ArrayList;
import java.util.Arrays;
//Main Class//**
public class P820_Country_Main {
public void run() {
Country Nederland = new Country("Netherlands", 17000000, 41543);
Country Duitsland = new Country("Gernany", 80620000, 357376);
ArrayList<Country> countries = new ArrayList<Country>();
countries.add(Nederland);
countries.add(Duitsland);
System.out.println(Arrays.toString(countries));
}
public static void main(String[] args) {
new P820_Country_Main().run();
}
}
The country class:
public class Country
{
private String countryName;
private int countryPopulation;
private int countryArea;
private double populationDensity;
public Country(String countryName, Integer countryPopulation, Integer countryArea)
{
this.countryName = countryName;
this.countryPopulation = countryPopulation;
this.countryArea = countryArea;
}
}
The issue I'm currently facing is that I can't seem to print out my ArrayList. Every spot of the ArrayList is basically an Array of its own. (Containing a String for the country's name, an int for the population & an int for the area. (Ignore the density variable, that is for later in the assignment)
The way I printed out ArrayList up until this point was as follows
System.out.println(countries);
When I do this with my current ArrayList it will print out the addresses instead of what's inside of the Array.
How do I get it to print out the ArrayList?

Try to declare toString() method in Country class:
public class Country
{
...
public String toString(){
return "Name: "+countryName+", population: "+ countryPopulation + ", area: "+countryArea;
}
...
}

Related

Issue with referncing objects that do not have a name

I´m new to programming and I have this task to implement a simple booking System for bus tickets.
We´re supposed to implement a method that adds new bus routes using the attributes: busNumber, start, destination, price, currency. To save the bus routes I´m using an arraylist and save new objects like this:
Booking.add(new Booking(1, "France", "Latvia", 2.05, Currency.EUR))
My issue now is working with those objects since they don´t have a name. I don't know the exact number of objects, so I have to do it this way (i think so at least). Where the issue occurred is at the method "remove", that is supposed to remove a bus route. I thought I could use an Iterator to iterate through the ArrayList and compare the busNumbers but it´s not working.
Another issue I have is, that when I want to print all the objects in my Array list it just prints the last object as many times as there are objects in my ArrayList. Also, my method and attributes are all static now otherwise I wouldn´t know how to use them in another class.
Does anybody has some advice for a newbie please?
My Code is below:
import java.util.ArrayList;
import java.util.Iterator;
public class Booking {
static int busNumber;
static int customerID = 1; //First customerID starts with 1
static String name;
static double price;
static int invoiceNumber = 1; //First invoicenumber starts with 1.
static String start;
static String destination;
static Currency currency;
static ArrayList<Booking> bookable = new ArrayList<Booking>();
//Constructor
public Booking(int busNumber, String start, String destination, double price, Currency currency) {
this.busNumber = busNumber;
this.start = start;
this.destination = destination;
this.price = price;
this.currency = currency;
}
public int getBusNumber() {
return busNumber;
}
public static void add(Booking add) { // add-method. Adds the bus routes to the booking system
bookable.add(add);
}
public static void remove(int busNumber) { // Here´s one of my issues. That´s what i have.
Iterator<Booking> it = bookable.iterator();
if ( == busNumber) {
bookable.remove(it);
}
}
public static void listRoute() {
for (Booking element : bookable) {
Terminal.printLine(toString(element));
}
}
public static String toString(Booking element) {
return "000" + busNumber + " " + start + " " + destination + " " + price + " " + currency;
}
}
My second class which is later supposed to be the UI:
public class Input {
public static void main(String[] args) {
Booking.add(new Booking(1, "Mannheim", "Karlsruhe", 2.05, Currency.EUR));
Booking.add(new Booking(2, "Heidelberg", "Karlsruhe", 3.05, Currency.JPY));
Booking.add(new Booking(3, "Germersheim", "Karlsruhe", 4.05, Currency.USD));
Booking.listRoute();
}
}
The Output is: "0003, "Germersheim", "Karlsruhe", 4.05, Currency.USD" 3 times..

How to store objects in ArrayList and print it? [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
for loop without braces in java
(6 answers)
Closed 4 years ago.
i am working in my project and it is about a clinic , my class is appointment , and i have to let the user to enter the day, time, section, doctor name, patient name. and store it an ArrayList
i wrote the code but when i run the project there is no output and i don't know why :(
package appointments;
import java.util.Scanner;
import java.util.ArrayList;
public class Appointment {
public static void main(String[] args) {
ArrayList<Object> appointments = new ArrayList<>();
Scanner input = new Scanner (System.in);
System.out.println("enter day, time, section , doctor , you name in order to book appointment : ");
appointment xx = new appointment();
for (int i=0; i<5; ++i)
xx.setAppDay(input.nextLine());
xx.setAppTime(input.nextLine());
xx.setAppSection(input.nextLine());
xx.setAppDoctor(input.nextLine());
xx.setAppPatient(input.nextLine());
appointments.add(xx);
System.out.println(appointments);
}
public static class appointment {
public String appDay;
public String appTime;
public String appSection;
public String appDoctor;
public String appPatient;
public appointment(String appDay, String appTime, String appSection, String appDoctor, String appPatient) {
this.appDay = appDay;
this.appTime = appTime;
this.appSection = appSection;
this.appDoctor = appDoctor;
this.appPatient = appPatient;
}
public appointment() {
}
public void setAppDay(String appDay) {
this.appDay = appDay;
}
public void setAppTime(String appTime) {
this.appTime = appTime;
}
public void setAppSection(String appSection) {
this.appSection = appSection;
}
public void setAppDoctor(String appDoctor) {
this.appDoctor = appDoctor;
}
public void setAppPatient(String appPatient) {
this.appPatient = appPatient;
}
public String getAppDay() {
return appDay;
}
public String getAppTime() {
return appTime;
}
public String getAppSection() {
return appSection;
}
public String getAppDoctor() {
return appDoctor;
}
public String getAppPatient() {
return appPatient;
}
}
}
Your loop has no braces and you only instantiate one appointment. You wanted something like,
for (int i = 0; i < 5; ++i) {
appointment xx = new appointment();
xx.setAppDay(input.nextLine());
xx.setAppTime(input.nextLine());
xx.setAppSection(input.nextLine());
xx.setAppDoctor(input.nextLine());
xx.setAppPatient(input.nextLine());
appointments.add(xx);
}
Then you need to override toString() in appointment.
Currently the same appointment object is being added to the list, so the list would only have a single entry in it.
So move the object creation and addition to the list along with setting the appointment fields inside the for loop. Please add the curly braces correctly as currently only the
xx.setAppDay(input.nextLine())
is part of the for loop.
Also appointment shouldn't be a static class multiple objects need to be created.
You need to implement a toString() Method for this purpose. And print it like this.
public String toString(){
return this.appDay; // return the output you want, so build a String using your attributes
}
System.out.println(Arrays.toString(appointments));
Edit: And do what Elliott Frisch said.

How can i add to a Linked List in Java [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 4 years ago.
am writing a program on linked list in Java but am confused on why the right values are not been added. I want to add the student name and StudentNo together as they for one student. Below is the code.
package linked;
public class PlsWork {
private String name;
private int studentNo;
public PlsWork(String name, int studentNo){
this.name=name;
this.studentNo=studentNo;
}
public String getname(){
return name;
}
public int getstudentNo(){
return studentNo;
}
}
package linked;
import java.util.LinkedList;
public class Linked {
public static void main(String[] args) {
LinkedList myLinkedList = new LinkedList();
myLinkedList.addFirst("A");
System.out.println(myLinkedList);
PlsWork ok = new PlsWork("obinna",3);
myLinkedList.add(ok);
System.out.println(myLinkedList);
}
}
when i run the code i get the answer below
[A, linked.PlsWork#6d06d69c]
Instead of [A,obinna 3]
linked.PlsWork#6d06d69c is the reference to your object. That is what toString shows by default. You may want to override toString on your PlsWork-class for example as follows:
class PlsWork {
...
#Override
public String toString() {
return name + ' ' + studentNo;
}
}

Printing address instead of array elements? [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
So in my code, I made a class named Pet, that would have both a default constructor and a non-default constructor that passes in String name, and int age of the pet.
public class Pet
{
// instance variables
private int age;
private String name;
/**
* Constructor for objects of class Pet
*/
public Pet()
{
// initialise instance variables
age = 0;
name = "somePet";
}
public Pet(int age, String name)
{
this.age = age;
this.name = name;
}
}
Then I created a class named petArray that would add to the array and print out the array...
public class PetArray
{
// instance variables
private Pet [] petArray;
/**
* Constructor for objects of class PetArray
*/
public PetArray()
{
// initialise instance variables
petArray = new Pet[5];
}
public void addPets()
{
// put your code here
Pet myPet = new Pet(4, "Spots");
petArray[0] = (myPet);
petArray[1] = new Pet(2, "Lucky");
petArray[2] = new Pet(7, "Joe");
}
public void printPets()
{
for (int i = 0; i < petArray.length; i++)
{
System.out.println(petArray[i]);
}
}
}
But then, I get this in the terminal window when trying to print it out...
Pet#13255e3c
Pet#171ac880
Pet#52185407
null
null
You forgot to override toString() method inherited from Object.
In this case you can use something like this:
#Override
public String toString() {
return (name + age);
}
Java compiler just does not know how to print it, you have to inform it :)
In your addPets() method you are only adding 3 objects to your petArray while there are 2 more spaces you need to fill as you declared that array to be a length of 5.
You could change the length of your array down to 3 or you could add 2 more objects, that should fix your problem.
And as stated above, adding the toString method will get rid of the addressing issues.
class Pet {
...
#Override
public String toString(){
// the string passed from here will be shown in console
}
}
Your output is fine according to your code. You have to override toString() method to print as per your requirement. Add this may be it will help.
#override
public string toString(){
return "your required string"; // i.e : name or name+age
}

Java - cannot make a non static reference to the non static field [duplicate]

This question already has answers here:
JAVA cannot make a static reference to non-static field
(4 answers)
Closed 8 years ago.
Hello I am trying to build a simple program that converts a string containing a number into an integer. I am receiving the error on the System.out.println and not sure why, can anyone help?
public class TypeConvert {
int strToInt;
public int convert (String s){
strToInt = Integer.parseInt(s);
return strToInt;
}
public static void main(String[] args) {
String strNumber=("100");
TypeConvert convertToInt = new TypeConvert();
convertToInt.convert(strNumber);
System.out.println(strToInt);
}
}
This has been marked as duplicate so I am editing. I did actually read all the relevant posts to my problem but as I did not understand how to fix my problem with theirs I created my own post.
Change this,
System.out.println(strToInt);
to
System.out.println(convertToInt.strToInt);
because strToInt is a field of the TypeConvert instance (which you've named convertToInt).
Alternatively, you could write
System.out.println(convertToInt.convert(strNumber));
since the convert function returns the result.
Your convert method should be a static method since she doesn't need any "state" information.
public class TypeConvert {
public static int convert (String s){
int strToInt = Integer.parseInt(s);
return strToInt;
}
public static void main(String[] args) {
String strNumber=("100");
int strToInt = TypeConvert.convert(strNumber);
System.out.println(strToInt);
}
}
Usually you create non-static fields and instance methods when you need to use a state. For example let's print the name of a person:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public static void main(String[] args) {
Person bob = new Person("Bob");
Person john = new Person("John");
System.out.println(bob.getName()); // Prints "Bob"
System.out.println(john.getName()); // Prints "John"
}
}
In this case you absolutely need to "save" the name variable in a property of the instance because each Person is going to have a different name.
In the example you gave us, for a given string, the ouput will always be the same so you can use a static method.

Categories