How can I show segmented information in an array? - java

I have to create a program which has a list of houses. In this houses there has to be this information:
direction, zipcode, number of rooms and the square meters of the house.
One of my biggest problems is that this information has to be segmented. So, first the list of directions have to be shown, then the list of zipcodes, then the number of rooms...
I created a class House and I set the String variables for each one (direction, zipcode, number of rooms and the square meters of the house).
I know that I should be using arrays, for and objects but It's my first assignment and I am really lost on how or where should I start.
I really want to learn how to do it, so if you have any idea, tip or suggestion I would appreciate it. I don't want people to do my assignment I just want to know how can I get started.
thank you!
This is my code so far:
package ejerciciofinalt3;
public class HouseExercise {
public static void main(String[] args) {
// TODO Auto-generated method stub
House house1 = new House();
house1.showHouseInfo();
house1.direction = "abc";
house1.postCode = "08397";
house1.roomNumber = "4";
house1.squareMeter = "100";
house1.showHouseInfo();
}
}

Create an ArrayList and add each house in that List. Then for each of the segments (directions, zipCodes, etc) do a for loop and print the segment:
List <House> houseL = new ArrayList();
houseL.add(house1);
houseL.add(house2);
houseL.add(house3);
System.out.println("-- Directions --");
for (House house:houseL){
System.out.println(house.getDirection());
}
System.out.println("-- Zip Codes--");
for (House house:houseL){
System.out.println(house.getPostCode());
}
//etc
You should have getters in House class.

Initialize a String Array like this:
String[] housePropertiesArray = new String[]{"abc", "08397", "4", "100"};
...in the House class.
Then you could write a method to return all of them:
public String getProperties(){
String output = "";
for(String property : housePropertiesArray){
output += property + "\n";
}
return output;
}
In the outputString you would have a superfluous \n in the end, just a newLine-Tag but wouldnt matter much I hope.

Try to override the toString() method like
class House{
...
#override
public String toString(){
return String.format("direction: %s postCode: %s roomNumber: %s squareMeter : %s",
this.direction, this.postCode, this.roomNumber, this.squareMeter);
}
after if you want to display just call
System.out.println(house.toString());
Or
System.out.println(house);

Related

How to pull specific data from an object in an arraylist

Ok, not sure if the title worded that correctly but say I have three objects with two strings of data each(Lets say a stateName and a cityName) stored into an arraylist. Is it possible to enter in a state name in as a string variable(call it searchStateName), then have a method search through the objects in the list and compare searchStateName to the stateName inside each object in the arraylist, and when a match is found have it return the cityName that is inside the same object as the matching stateName?
I am trying to do something similar currently and would like to figure it out myself, but I have been working on this for the past hour and am completely lost. Could anyone point me in the right direction?
This is the approach. Say you have a class called SC and you have two instance variables in it and getters and setters for them. You need to initialize 3 objects of them inside your main:
SC a = new SC("Illinois ","Chicago ");
SC b = new SC("Michigan ","Detroit");
SC c = new SC("New York"," New York");
And then create an ArrayList of object SC and add those 3 objects of SC to that ArrayList.
ArrayList<SC> list = new ArrayList<SC>();
list.add(a);
list.add(b);
list.add(c);
Now call the method that search for a state name and returns the city name if it finds it:
this.searchStateName("Illinois");
The actual implementation of this method with for-each loop:
public String searchStateName(String stateName){
String result = "No city found.";
for (SC sc : list )
if (sc.getStateName().equalsIgnoreCase(stateName)){
result = sc.getCityName();
break;
}
}
return result;
}
If you are not comfortable with for-each loop then you can use the regular for loop below. I commented out on purpose. But it will work correctly and give you the correct city name.
//public String searchStateName(String stateName){
// String result = null;
// for (int i = 0; i < list.size(); i++){
// if (list.get(i).getStateName() .equalsIgnoreCase(stateName)){
// result = list.get(i).getCityName();
// break;
// }
// }
// return result;
//}
And thats it. Let me know if you need help further.

How to compare a string to a specific compartment of an array of strings?

I'm making a quiz like game. I have two arrays (One with the states and the other with the capitals). Basically it asks the user what capital goes with a random state. I want that if the user inputs the correct state for it to be like nice job or whatever but I do not know how to compare the user input to the specific array compartment. I tried .contains but no avail...
Any help?
My bad - I'm using Java
For Example
if(guess.equals(capitals[random]))
where guess is the string and capitals is the array and random is the random number
Basically you want a mapping String -> String (State -> Capital). This could be done using a Map<String, String> or by creating a State class which will contains its name and its capital as attributes.
But to my mind, the best option is to use an enum as you know that there is 50 states. Here's a small example.
public class Test {
static final State[] states = State.values();
static Random r = new Random();
static Scanner sc = new Scanner(System.in);
public static void main (String[] args){
State random = states[r.nextInt(states.length)];
random.askQuestion();
String answer = sc.nextLine();
if(answer.equals(random.getCapital())){
System.out.println("Congrats");
} else {
System.out.println("Not really");
}
}
}
enum State {
//Some states, add the other ones
ALABAMA("Montgomery"),
ALASKA("Juneau");
private final String capital;
private State(String capital){
this.capital = capital;
}
public String getCapital(){
return this.capital;
}
public void askQuestion(){
System.out.println("What capital goes with "+this.name()+"?");
}
}
Logic similar to this should work. You want to save the user input to a String variable, and then compare it to an n sized array.
for(int i=0; i<arrayName.length();i++)
{
if(userinputString.equalsIgnorCase(arrayName[i])
{
System.out.println("HUrray!");
}//end if
}//end for
Ok so you are somehow producing a random number, and then need to compare the input to the String in the capital Array for that random number/
Im assuming the arrays are ordered such that capitals[10] gives you the capital for states[10].
If so, just save the index to a variable.
int ranNum=RandomNumFunction();
Then just see if
if(capitals[ranNum].equalsIgnoreCase(userInput))
//do something

find a specific object in a ArrayList

I am making a small program that should have a class for people(Name, BirthYear) and a class for pets(Name, AnimalType).
In the main I have created a menu so a user can add peoples then the pets.
Now to my question, if I create 4 people "Bruce, Tony, Kevin, William" and the user want to give Kevin a pet, how can i know where in the list Kevin are? Becuse you cant use the contains(), can you? well i cant anyways...
The thing is that I have a method in the class for people that creates the pet, because I want them to be linked...
public void setAnimal(String dName, String dType)
{
Animal.add(new Pet(dName, dType));
}
This is how my method to create pets work..
private static void createA()
{
String P = JOptionPane.showInputDialog(null,"This is the people you can give a pet, please write a name:\n" + People);
P = P.toUpperCase();
//I want to write some code here to give a int a number so i cant but it in the get downbelow insted //of "???"
boolean b =true;
while (b != false)
{
try
{
ggr3 = Integer.parseInt(JOptionPane.showInputDialog("How many pets do you want to add: "));
b = false;
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e + "\nWrite with numbers!");
}
}
while (ggr3 != ggr4)
{
dNamn = JOptionPane.showInputDialog("Write the name: ");
dTyp = JOptionPane.showInputDialog("Write animal type: ");
People.get(???).setAnimal(dName, dType);
ggr4++;
}
}
Becuse you cant use the contains(), can you?
yes you can only you need to do is to override equals() method based on your requirement
List<Person> arr = new ArrayList<Person>();
Person kevin = new Person("kevin");
arr.add(kevin);
Person newKevin = arr.get(kevin);
System.out.println(kevin == newKevin); // True b/c they point to the same object.
System.out.println(kevin.equals(newKevin)); // True b/c they have equal values.
You need to add a .equals() method to your Person class.
The way of searching for an object in an array list is with the indexOf method.
Example:
int x = myAList.indexOf(myObject)
It returns the position of myObject in the ArrayList or -1 if it's not there.

Error: Constructor Room in class Room cannot be applied to given types

I am completely new to java. I have searched for hours upon hours for the solution to this problem but every answer involves passing args or using a void which I do not do in this situation.
I have two java files, one for Room class, and one for TourHouse class. I am trying to create a new Room in the TourHouse class. Here is my error, it's driving me nuts, I've tried everything I am capable of understanding. Thank you in advance.
HouseTour.java:15: error: constructor Room in class Room cannot be applied to given
types;
{
^
required: String, String
found: no arguments
reason: actual and formal arguments differ in length
Here is the Room class, will have 7 rooms total once I can figure this out
// Room.java
import java.util.*;
public class Room
{
// Define Instance Variables
private String name;
private String description;
// Define Constructor
public Room(String theName, String theDescription)
{
name = theName;
description = theDescription;
}
public String toString( )
{
return "The " + name + "\n" + description + "\n";
}
}
Here is the HouseTour class
import java.util.*;
public class HouseTour extends Room
{
// Define Variables
public Room[ ] rooms = new Room[7];
//Define Constructor
public HouseTour( )
{
rooms[0] = new Room("Living Room", "Mayonnaise and Brill Grates, Michaelsoft");
rooms[1] = new Room("Basement", "Hopefully no dead bodies down here...");
}
// this is horrible and not right
public String rooms( )
{
for (int i = 0; i <=7; i++)
{
String output = "House Rooms included in tour\n";
String output2 = output + rooms.toString() + "\n";
return output2;
}
}
}
EDIT: Solved but still need help here because I am complete n00b, :(
// this is horrible and not right
public String rooms( )
{
output = "House Rooms included in tour\n";
for (int i = 0; i <=7; i++)
{
output += rooms[i]; // I can't do this but how do i?
}
return output.toString(); // do I do this?
}
}
What I am doing is trying to learn java by converting the ruby projects I have created. So in ruby you say:
def rooms
output = "House Rooms included in tour\n"
#rooms.each do |r|
output += r.to_s + "\n"
end
return output
end
Edit: Still trying, any ideas?
added public String s; and public String output; to declarations
// this is horrible and not right
public String rooms( )
{
s = ""
output = "House Rooms included in tour\n";
for (int i = 0; i <=7; i++)
{
s += rooms[i];
}
s.toString() // I don't know
return output + s; // do I do this?
}
}
Edit: Solved thanks to Hovercraft Full Of Eels
Ah, I see your problem: HouseTour extends Room. Don't do this! HouseTour is not a more specific case of a Room type and so should not extend this class. It does not fulfill the "is-a" rule, and would be similar to trying to define Bus as a child class of SchoolKid. Just like a Bus isn't a type of SchoolKid but rather contains SchoolKids, a HouseTour isn't a Room but rather contains Rooms. It fulfills the has-a relationship, not the is-a relationship.
If the inheritance were proper in this situation, your HouseTour constructor would need to call the Room super constructor and pass in two String parameters:
// Don't do this!!!
public class HouseTour extends Room {
public HouseTour() {
super("foo", "bar");
....
}
But having said that, again inheritance is not proper here -- just get rid of extends Room, and you're home free.
e.g.,
public class HouseTour { // no extends!
private Room[] rooms; // has-a not is-a
public HouseTour() {
// don't call super here
}
Also, as per my comment, this will give you ugly output: rooms.toString()
Instead iterate through the Array and get the toString() result from each Room item in the array.
Edit
Suggestions on your rooms() method:
Create a String or StringBuilder before the loop.
Build up the String or StringBuilder inside the loop.
Return the String or StringBuilder#toString after the loop.
Inside of the loop get the toString() from the current Room item in the list.
You will need to check that the rooms[i] item isn't null before calling a method on it.
Edit 2
You state that this:
public String rooms( )
{
output = "House Rooms included in tour\n";
for (int i = 0; i <=7; i++)
{
output += rooms[i]; // I can't do this but how do i?
}
return output.toString(); // do I do this?
}
is causing problems, but you don't specify the problem.
Myself, I'd do something like:
public String rooms( ) {
// declare your String locally, not globally in the class
String output = "House Rooms included in tour\n";
// again, avoid using "magic" numbers like 7
for (int i = 0; i < rooms.length; i++) {
output += rooms[i].toString(); // **** you must extract Room's String
}
return output; // no need to call toString() on a String
}

For Each Loops and For Loops Java

I want to be able to create a for loop like this
For(each booking)
sounds simple for all you experts out there, but ive tried researching how to do this,
and its left me a little confused,
I assume id need a for each loop, which would be something like this
for (type var : coll) {
body-of-loop
}
This program creates a new booking and then allows the user to enter the details into the program of that booking, I have named this B1. IS it that value you enter into the for loop?
I know ill get rated down on this, but i dont understand how i get it to loop for each booking.
Thanks for the quick answers, Ive written some code which ill provide now. Hopefully it will make it easier to see.
Booking Class
public class Booking
{
private int bookingId;
private String route;
private double startTime;
private String bookingDate;
public Booking()
{
bookingId = 0000;
route = "No Route Entered";
startTime = 0.00;
bookingDate = "No Date entered";
}
public int getBookingId()
{
return bookingId;
}
public String getRoute()
{
return route;
}
public double getStartTime()
{
return startTime;
}
public String getBookingDate()
{
return bookingDate;
}
public void setBookingId(int bookingId)
{
this.bookingId = bookingId;
}
public void setRoute(String route)
{
this.route = route;
}
public void setStartTime(double startTime)
{
this.startTime = startTime;
}
public void setBookingDate(String bookingDate)
{
this.bookingDate = bookingDate;
}
public Booking(int bookingId, String route, double startTime, String bookingDate)
{
setBookingId(bookingId);
setRoute(route);
setStartTime(startTime);
setBookingDate(bookingDate);
}
public String toString()
{
return "BookingId: " + getBookingId() + "\nRoute: " + getRoute() + "\nStart Time: " + getStartTime() +
"\nBooking Date: " + getBookingDate();
}
}
Main Class
import java.util.*;
public class Main {
public static void main(String[] args) {
//<editor-fold defaultstate="collapsed" desc="Creates new Student and booking">
Student s1 = new Student();
Booking b1 = new Booking();
s1.setStudentId(Integer.parseInt(JOptionPane.showInputDialog("Enter ID for Student: [0001]")));
s1.setFname(JOptionPane.showInputDialog("Enter first name of Student: "));
s1.setLname(JOptionPane.showInputDialog("Enter last name of Student: "));
s1.setAddress(JOptionPane.showInputDialog("Enter address for Student: "));
s1.setPhoneNo(JOptionPane.showInputDialog("Enter phone number for Student: "));
s1.setOtherDetails(JOptionPane.showInputDialog("Enter other details for Student: [Glasses?]"));
b1.setBookingId(0002);
b1.setStartTime(Double.parseDouble(JOptionPane.showInputDialog("Enter Start time for Booking: [1200]")));
b1.setBookingDate(JOptionPane.showInputDialog("Enter Date for Booking: [01-JAN-12]"));
//</editor-fold>
//For Each Booking
}
}
}
List <Booking> allBookings = new ArrayList<Booking>();
//fill your AllBookings with data
for(Booking b:allBookings){
body of loop // b is your actual Booking Object
}
Something like this would do your work.
You will need an Booking Class, and some data stored in your AllBookings Array List. With you ensure that only Booking Objects can be placed within that Array List.
But back to the For each loop.
The first part (Booking) defines which Object-type is placed in
the list,array or what you want to compute through. Note: You could also place Object instead of Booking since everything is an Object, but I would not recommend you to do that.
The second one (b) is the name of the variable which stands for
the actual element in your list, when iterating over it.
And the third and final part (AllBookings) is your Collection or Array where all your Objects are placed in.
Java Documentation for For-Each Loops:
http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
You got the syntax right, you just need to pass a collection (or an array) of the objects to the loop:
// bookings is Booking[] or a collection of Booking objects, like List<Booking>
for (Booking b : bookings)
{
// do whatever you need to do with b
}
Type is the name of the type of your object: the thing you'd use to declare it. E.G. Booking.
var is the name of the placeholder variable, which will assume the value of each element that you loop over in the collection. This can be whatever you want.
coll is the name of the collection you want to loop over. It sounds like maybe you called this B1.
So you would use
for (Booking booking : B1){
//body
}
What is booking? foreach loops are used for Array Iteration
I'm assuming this is what you're trying to do, lets say booking is an array of type String[] (i can edit my answer if it's something else)
String[] booking = new String[]{"Hello", "How are You", "Goodbye"};
for (String s: booking)
{
System.out.println(s);
}
for (int i=0; i < booking.length; i++)
{
System.out.println(booking[i]);
}
Produces the following output:
Hello
How are You
Goodbye
Hello
How are You
Goodbye
If you have a collection of type Foo like this:
List<Foo> someList = getSomeList();
Then to loop you can do:
for(Foo myFoo : someList){
System.out.println("I have a foo : "+myFoo);
}
I don't fully understand what you're asking in the paragraph where you mention B1, as what you're describing doesn't seem to require looping at all.
But in general, the for-each loop works the way you've described. Note that the right hand variable is called coll - this is because it needs to be some sort of collection of elements (strictly something that implements Iterable). So if you have e.g. a List<Booking>, you could loop over all of the bookings in this list in turn as follows:
List<Booking> bookings = ...; // populated somehow, or passed in, whatever
for (Booking b : bookings) {
// Do what you want to b, it will be done in turn to each booking in the list
// For example, let's set the hypothetical last updated date to now
b.setLastUpdated(new Date());
}
// At this point all bookings in the list have had their lastUpdated set to now
Going back to what you described:
This program creates a new booking and then allows the user to enter the details into the program of that booking, I have named this B1.
It sounds like you have a booking. Are you sure you need a loop for just one booking? A loop involves performing the same actions on a bunch of different objects; what is it you want to loop over?

Categories

Resources