How would I link together methods from different classes in java? - java

This is the code for one of the methods I wrote:
public void createReservation (String guestName, String roomType) {
Reservation roomReservation;
Room roomAvailability;
roomAvailability = findAvailableRoom(hotelRooms, roomType);
if(roomAvailability != null) {
roomReservation = new Reservation(roomAvailability, guestName);
}
else {
System.out.println("A room of this type is not available.");
}
}
The error is coming from line 4. The error says that the symbol cannot be found. Although I think I know why, I am not entirely sure how to fix the problem.
findAvailableRoom is a method from a different class and I am trying to transfer it into this class. I thought that writing it like that would suffice but it doesn't seem to have worked.
This is the method that I am referring to. It is in a different class.
public Room findAvailableRoom (Room [] roomList, String desiredType) {
for (int i = 0; i < roomList.length; i++) {
if (roomList[i].getAvailability() == true && roomList[i].getType() == desiredType) {
return roomList[i];
}
}
return null;
}
Any help?

To achieve what you're asking, you need an instance of the object of which field is needed. Another possibility is to make that field static.

Related

GSON - Serialize ArrayList into a JSON array containing JSON objects without duplicates

I'm currently making a novel reader/editor in java using JSON. I've made the reader part with no problem, but the JSON serialization in the editor is giving me problems.
The idea is to add or set an object to an ArrayList like this:
ArrayList<Chapters> allChapters = new ArrayList<>();
private void TAContentKeyTyped(java.awt.event.KeyEvent evt) {
Chapters newChapter = new Chapters(LSChapters.getSelectedValue(), TAContent.getText());
if (allChapters.contains(newChapter)) {
allChapters.set(0, newChapter);
}
else {
allChapters.add(newChapter);
}
String json = gson.toJson(allChapters);
Iterator allChaptersIterator = allChapters.iterator();
while (allChaptersIterator.hasNext()) {
System.out.println(allChaptersIterator.next().toString());
}
System.out.println(json);
}
which outputs this when I press backspace 3 times:
Chapter: Test Content:
Chapter: Test Content:
Chapter: Test Content:
[{"chapter":"Test","content":""},{"chapter":"Test","content":""},{"chapter":"Test","content":""}]
As you can see, instead of putting all inputs with the same chapter name into a single element, the code uses the .add() method instead of the .set() method every time despite putting a .contains() method on the if. Admittedly I didn't expect this approach to work, but I have no idea how to approach this at all.
The desired output should look like this:
Chapter: Test Content: This is content 1
Chapter: Test 2 Content: This is content 2
[{"chapter":"Test","content":"This is content 1"},{"chapter":"Test 2","content":"This is content 2"}]
Where every chapter with the same name is stored in a single element no matter how many keys were pressed.
Thank you in advance.
The Chapters class look like this:
public class Chapters {
private String chapter;
private String content;
public Chapters(String chapter_name, String chapter_content) {
chapter = chapter_name;
content = chapter_content;
}
#Override
public String toString() {
return "Chapter: " + chapter + " Content: " + content;
}
}
Notes:
Please ignore that the .set() method uses index 0, that's just for testing. The real function would use the chapter name's index.
Maybe you should use Set instead of a List? Change your
ArrayList<Chapters> allChapters = new ArrayList<>();
to - for example :
Set<Chapters> chapters = new HashSet<>();
To Set function correctly you should also implement equals(..) and hashCode() in your Chapters, for example, if you can rely only chapter
#Override
public int hashCode() {
return chapter.hashCode();
}
#Override
public boolean equals(Object obj) {
if (obj != null) {
if (obj instanceof Chapters) {
return chapter.contentEquals(((Chapters) obj).getChapter());
}
}
return false;
}
NOTE: above though working are just examples that use only chapter string as 'id' and not fully tested. See more What issues should be considered when overriding equals and hashCode in Java?.
There is no more need to check duplicates explicitly. You can just add chapters to your set and above changes will ensure no duplicates.
Turns out the main problem is the keyboard event. No matter which listener I use (KeyPressed, KeyReleased, KeyTyped) some kind of indexing error always pops up. I finally relented and gave the function its own button. It works perfectly now. This is the new code:
try {
String contentString = TAContent.getText();
int contentStringLen = contentString.length();
int selectedIndex = LSChapters.getSelectedIndex();
int ArrayIndexLength = sessionContent.size();
if (contentStringLen > 1) {
if (ArrayIndexLength < selectedIndex) {
for (int i = 0; i < selectedIndex; i++) {
sessionContent.add(0, "");
}
}
if (selectedIndex >= ArrayIndexLength) {
sessionContent.add(selectedIndex, contentString);
}
else {
sessionContent.set(selectedIndex, contentString);
}
}
else {
JOptionPane.showMessageDialog(null, "Please write chapter content first!");
}
}
catch (Exception e) {
System.err.println(e);
}

Working of this non-static method (being supposedly called without an object?)

i'm quite new to Java so let me know if I'm missing something basic here..
I came across this chunk of code referencing a method from the same class. (i.e. both methods exist with the same superclass)
//Method (Part of a bigger superclass)
private int hopDistance()
{//Implementation Not Shown}
//The Code in Question with the function call
public boolean simulate()
{
int position = 0;
for (int count = 0; count < maxHops; count++)
{
position += hopDistance();
if (position >= goalDistance)
{
return true;
}
else if (position < 0)
{
return false;
}
}
return false;
}
Why does it seem that line 7 in the code on the bottom is referencing the hopDistance() class without instantiating an object? I understand how static methods can have this property but didn't understand how non-static ones could...
In Java, one method within a class can call other methods within the same instance of that class without explicitly invoking the class name.
In other words, if simulate() and hopDistance() are both defined as methods in the same class, then
public boolean simulate() {
hopDistance();
}
and
public boolean simulate() {
this.hopDistance();
}
are identical.

Linking java functions/subroutines

I am developing a slots machine game as part of an assignment.
I have two functions that I need to link together, shown below:
public static void DisplayOnScreen(){
int LeftVal = GenerateNumber();
int MidVal = GenerateNumber();
int RightVal = GenerateNumber();
FruitVal1 = showFruit[LeftVal];
FruitVal2 = showFruit[MidVal];
FruitVal3 = showFruit[RightVal];
System.out.println(" |",FruitVal1, "|", FruitVal2, "|", FruitVal3, "| ");
--
public String showFruit(int inVal) {
String[] strFruitArr = new String[6];
strFruitArr[0] = "Orange";
strFruitArr[1] = "Pear";
strFruitArr[2] = "Banana";
strFruitArr[3] = "Cherry";
strFruitArr[4] = "Lemon";
strFruitArr[5] = "Apple";
strFruitArr[6] = "Bar";
while(inVal > 0){
if(inVal == 0){
return strFruitArr[0];
}
else if (inVal == 7){
return strFruitArr[6];
}
else{
return strFruitArr[inVal];
}
}
}
As you can see, each "FruitVal" is assigned by taking for example "LeftVal" which is a randomly generated number, and applying that to one of the fruits from the "showFruit" function. I'm aware this is done completely wrong however i do not understand the different java functions to do so.
Could someone explain the basic java functions e.g. 'public static void' and try and help implement them in to this code correctly.
If anyone wants to see the full program code then please do ask, I wasn't sure if the full code was necessary, however it is only short.
Learn Java coding standards. Your code will be more readable.
You link them by having one method return the data that the other needs to have passed to it.
public void displayFruitOnScreen(String [] fruit) {
// display here
}
public String [] getFruit() {
// populate the fruit array here
}
Neither of these is static; they are associated with some instance of a Java class.

need to store value after passing to method for latter check

I am passing few values to mail method for sending the details like below
private static String getTeam(String Team, List<String> prioritys1, String number,String description
) {
StringBuilder builder1 = new StringBuilder();
for (String v : prioritys1) {
if ( v == "1") {
Integer cnt1 = count1.get(new Team(Team, v,number,description));
if (cnt1 == null) {
cnt1 = 0;
}
else
if (cnt1 !=0){
cnt1 = 1;
mail1(Team,v,number,description);
}}
else
if ( v == "3") {
Integer cnt1 = count1.get(new Team(Team, v,number,description));
if (cnt1 == null) {
cnt1 = 0;
}
else
if (cnt1 !=0){
cnt1 = 1;
mail1(Team,v,number,description);
}}
}
return builder1.toString();
}
I tried to store in arrays but it didnt worked.
I after pass above parameters, i need to store the value of the number. i need to store the number so that next time while passing the parameters i need to check first whether the number is already passed or not if not then only i need to pass to mail.
can any one help on this
With this code very complicated understand what you are doing. But if you need check value that already been processed store it outside of the method. Create global class variable:
public class className {
private final List<String> ARRAY = new ArrayList<>(); // global variable
public void yourMethod(String value) {
if (!ARRAY.contains(value)) {
mail(value);
ARRAY.add(value);
}
}
}
I dont know your case and I can not get better example.
You need to store the value in a "class level" variable. Whether the variable type needs to be static or instance will depend on your implementation of the method.
If you can post a sample code, we can help further.
You need to compare with 2 equals and not 1
Instead of
if( Team = A )
you need this way
if( Team == A )
Using Team = A, your saying that every time your code reaches that line it will equal Team to A.

Using Array of Objects in Parameters, Inheritance in Parameters

I have the class Building and the sub-classes Barracks and House. Now I have an array of houses and barracks defined like this:
public House[] arrSHouse;
public Barracks[] arrBarr;
Now my code is designed such that I when I want to create a house, a house will follow my mouse in the applet. This way works:
for(int h = 0; h < arrSHouse.length; h ++)
{
if(arrSHouse[h].held == true)
{
arrSHouse[h].isAlive = true;
arrSHouse[h].xpos = e.getX()-8;
arrSHouse[h].ypos = e.getY()-20;
}
}
However, I want to make my code more efficient by making a method that will allow me to input an array, such as arrBarr, which is an array of Barracks, and do the same things as the method shown above. This is my attempt:
public void buildingFollowMouse(Building[]type, MouseEvent e)
{
for(int a = 0; a < type.length; a ++)
{
if(type[a].held == true)
{
type[a].isAlive = true;
type[a].xpos = e.getX()-8;
type[a].ypos = e.getY()-20;
}
}
}
However, this doesn't work. The only way that this works is if I say:
public void buildingFollowMouse(House[]type, MouseEvent e)
as the parameters and say:
buildingFollowMouse(arrSHouse, e);
This of course would mean writing another method for the barracks method.
I just want to know a way that I can input a sub-class of Building in my parameter and have it work the same way that it worked above with the House for-loop with any other Building I decide to make. How can I do this?

Categories