Trying to compare and print only members with Inactive status [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Trying to compare and print only members with Inactive status. The problem is that it will not search the array and check the status of each element. If the first element has an "Active" status, it prints the error message and doesnt continue to check the other elements.
If the status of the first element is "Inactive" it will print but throws an exception before the output which looks like this:
Exception in thread "main" java.lang.NullPointerException at
GymAss.MemberTest.AllInactive(MemberTest.java:293) at
GymAss.MemberTest.main(MemberTest.java:58)
Account Number: 1 Name: 1 Date: 1 Status: INACTIVE Type: 1 Any
help would be greatly appreciated! Code below:
....
public static void AllInactive()
{
int check=0;
do
{
if ( accounts[check] instanceof Student && accounts[check].getStatus().equals("INACTIVE") )
{
System.out.printf("\nAccount Number: %d \nName: %s \nDate: %d \nStatus: %s \nType: %s \n" , accounts[check].getIdNumber(),accounts[check].getName(),accounts[check].getDateJoined(),accounts[check].getStatus(),accounts[check].getMemberType());
check++;
}
else if ( accounts[check] instanceof Adult && accounts[check].getStatus().equals("INACTIVE"))
{
System.out.printf("\nAccount Number: %d \nName: %s \nDate: %s \nStatus: %s \nType: %s \n" , accounts[check].getIdNumber(),accounts[check].getName(),accounts[check].getDateJoined(),accounts[check].getStatus(),accounts[check].getMemberType());
System.out.print("\n");
check++;
}
else
{
System.out.println("**Account Does Not Exist**");
}
} while ( accounts[check].getStatus().equals("INACTIVE"));
}

Just to make sure we are talking about the same thing: As far as I understood you have an Array containing accounts of persons. What you want to do is get all the accounts which currently are inactive and nothing else.
Why do you stop your loop if you find an active account? If you have an inactive account followed by an active followed by an inactive again, your loop will stop at the active one, because the condition of while(accounts[check].getStatus().equals("INACTIVE")) is false. You want to check the whole array so you have to loop through the whole array. This can be done with
for(int check=0; check<accounts.length; check++)
This checks every account and stops if you reach the end of the array. There is even an easier way. I recommend looking up "java foreach".
The cause of your NullPointerException propably is not checking if you reached the end of your array. Let's assume you have only one inactive Student account in your array and nothing else, your code will do this:
check = 0;
is accounts[0] a Student and is it inactive? - yes
print stuff
check = 1
skip else if
skip else
is accounts[1] active? wait, there's no accounts[1] -> NullPointerException
I don't want to give you the complete code because trial and error is a great way of learning so try to fix it with those hints. If you encounter any problems you still can't solve after a while of thinking, come back.

Related

How can I read an array/object of a hocon file from java

I am trying to change my project configuration files from YAML to HOCON.
Everything went fine except when I ran into a file that uses array/object.
This is the YAML file:
interactions:
example1:
questions:
- 'How do i get money?'
- 'Does anyone know how to get money?'
- 'I need money'
answers:
- '{player} you have to sell in the store'
- '{player} sell items'
options:
response_chance: 30
required_real_players: 5
wait_per_letter: 0.3
example2:
questions:
- 'I want to buy a block in the store'
- 'I want to go to the store'
- 'where do I get blocks'
answers:
- '{player} type /shop'
- '{player} to buy items type /shop'
options:
response_chance: 30
required_real_players: 5
wait_per_letter: 0.3
This is how I read this file in java:
Object[] fields = main.getConfig().getConfigurationSection("interactions").getKeys(false).toArray();
for (Object key : fields){
for(String question : main.getConfig().getStringList("interactions."+key+".questions")) {
List<String> answers = main.getConfig().getStringList("interactions."+key+".answers");
I have tried to adapt it to HOCON and this is how it turned out:
interactions {
example1=[
{
questions=[
"How do i get money?"
"Does anyone know how to get money?"
"I need money"
]
answers=[
"{player} you have to sell in the store"
"{player} sell items"
]
options= {
response chance = 30
requiered real players = 0
wait per letter = 0.3
}
}
]
example2=[
{
questions=[
"I want to buy a block in the store"
"I want to go to the store"
"where do I get blocks"
]
answers=[
"{player} type /shop"
"{player} to buy items type /shop"
]
options= {
response chance = 30
requiered real players = 0
wait per letter = 0.3
}
}
]
}
Now how can I read this file using a java class?

How to work with time intervall in java [duplicate]

This question already has answers here:
How to check a timeperiod is overlapping another time period in java
(5 answers)
Closed 2 years ago.
i have this situation :
I am trying to do an excercise about the prenotation of a user for a cinema.
A user can be only in one film at the moment, (but he can buy another ticket for the next show if he want).
Every show has a start time and an end time ( so i can rapresent them with timestamp ).
My question is: how can i add a controll that the user that is partecipating at one show cannot buy another ticket for another show at the same time?
We can immagine a user with an unique id, and a cinema room with an Id.
And a third object ( Show with an Id, startTime,EndTime).
My question is not a lot about code implementation but much more about the logic.
A person can partecipate only one for a certain interval to a show.( he cannot partecipate at the same time in two different shows, cause he need to respect the startTime and the EndTime of the show). For some reason if the user try to buy another ticket for another show at the same place he cannot do it because he is suposed to follow a show at this interval.
Implement something like a hook into your booking function. Before the booking will be done, a check if the user is allowed to book this specific show will be done. Only if this check if positive, the actual booking progress can be triggered. What ever this includes in your system.
Cause I haven't any idea how your project looks like (which database your using for example) the implementation of the hook could be very variable. It would be an advantage, if you could get the list of shows for the executing user ordered by time. This would allow a fix check if any already booked show overlaps with the new one.
A possible pseudocode implementation of this check could be:
if (usersShowList.stream().filter(show -> (show.startTime < newShow.startTime && show.endTime > newShow.startTime)).count() <= 0) {
...
}
It would be really usefull if you could specifiy your problem in more detail, in case you need further comments.
I give u a simple example here for and old movie and a new one.For your purpose you need to go higher and iterate over all movies.
Calendar cal=Calendar.getInstance();
//I just add some comments to be clear about the logic.
//E_new dateEndStartMovie
//E_old date dataEndOldMovie
//S_new dateStartMovie
//S_old dataStartOldMovie
Date dateStartMovie=new Date();
cal.setTime(dateStartMovie);
cal.add(Calendar.HOUR_OF_DAY, 2);
Date dataEndMovie=cal.getTime();
cal.add(Calendar.HOUR_OF_DAY, -3);
Date dataStartOldMovie=cal.getTime();
cal.add(Calendar.HOUR_OF_DAY, 2);
Date dataEndOldMovie=cal.getTime();
System.out.println("data start movie"+dateStartMovie);
System.out.println("data end movie"+dataEndMovie);
System.out.println("data start old movie"+dataStartOldMovie);
System.out.println("data end old movie "+dataEndOldMovie);
if (
dateStartMovie.getTime() > dataStartOldMovie.getTime() //S_new > S_old
&& dateStartMovie.getTime() < dataEndOldMovie.getTime() //S_new < E_old
||
(dataEndMovie.getTime() > dataStartOldMovie.getTime() //E_new > S_old
&& dataEndMovie.getTime() < dataEndOldMovie.getTime()) //E_new < E_old
||
(dataEndMovie.getTime() > dataEndOldMovie.getTime() //E_new > E_old
&& dateStartMovie.getTime()<dataStartOldMovie.getTime())//S_new < S_old
// i think that we are missing even S_new < S_old and F_new > F_old ( i can have more film in a bigger interval so i could not send another ticket if in the big interval the person buy a ticket
)
{
System.out.println("Error.Cannot buy ticket at this time. ");
}

How to escape %s on the first string.format so it can be used in the second one? [duplicate]

This question already has answers here:
How to escape % in String.Format?
(3 answers)
Closed 8 years ago.
I have a Java project in which I am working in our "query module". It is responsible for building queries from string we call "snippets".
To do that,
I am using things like this
myQueryOuter{
%s
}
myInnerQuery{
QUERY TEXT
}
Using String.Format will work, but now one of my queries accepts values, which are coded as "%s", so an exception is thrown when I call the String.format method.
Is there anyway to escape the %s? That way I would create the whole query and then apply a String.Format to replace the %s for the values.
Or is there any nicer way to do something like this?
Thanks!
Edit:
Let me clarify:
I have the following
myQueryOuter{
%s
}
myInnerQuery{
The next blank space should be filled by a parameter: %s
}
I want to make
String output = String.Format(myOuterQuery, myInnerQuery) //this throws an exception
So I have this output
myQueryOuter{
myInnerQuery{
The next blank space should be filled by a parameter: %s
}
}
So I can call
String realOutput = String.format(output, "ThisIsMyParameter")
So I have
myQueryOuter{
myInnerQuery{
The next blank space should be filled by a parameter: this is my output
}
}
The exception is:
org.springframework.web.util.NestedServletException: Request
processing failed; nested exception is
java.util.MissingFormatArgumentException: Format specifier '%s'
Because I have %s twice, but I want my output to HAVE the %s
Before you format you need to replace % with %%
Then to format %%s with your parameter.. This will do the work
Hope that helps

How to return arraylist using restful webservices in java? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to return values in the json format. I am using (MediaType.APPLICATION_JSON) for to return the values. How to return the ArrayList using this?
Example:
[
{
"node_title": "Ambivalence About Government Will Be Topic at next Lecture ",
"nid": "Topic - Get the Government Off of Our Backs – There Ought to Be a Law: Reconciling Our National Ambivalence About Government."
},
{
"node_title": "Recycling initiative gains steam under new director",
"nid": "University administrators listened and hired a sustainability coordinator whose main focus has been to heighten recycling efforts and awareness."
},
{
"node_title": "Special Week to Combat Hate and Discrimination",
"nid": "For the seventh year, University students will observe “Why Do You Hate Me?” Week, which will run from March 28th through April 2nd."
},
{
"node_title": "AUSP joins Nursing School on mission trip to Caribbean",
"nid": "The School of Audiology and Speech-Language Pathology during spring break went to Dominican Republic to provide much-needed assistance to a school for deaf and impoverished children."
}
]
Please guide me.
If you want to parse this into java code, you can do something like this:
First, get Gson, a google library to work with JSON.
Next, define a class like:
class Node {
String node_title;
String nid;
}
Then you can do
Type collectionType = new TypeToken<List<Node>>(){}.getType();
List<Node> details = gson.fromJson(myJsonString, collectionType);

Jsoup Java doc.select Yahoo Finance [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I understand the Jsoup code to retrieve "Stock Name" and "Current Stock Price" from a Yahoo Finance page (e.g. http://finance.yahoo.com/q?s=goog):
String price = doc.select(".time_rtq_ticker").first().text();
String name = doc.select(".title h2").first().text();
But I am not sure how to select other data, for example the Open: or Volume: values.
This is what I have tried so far:
Elements open = doc.getElementsByTag("Open");
Elements volume = doc.getElementsByTag("Volume");
You could get all of the data from the table and then get the correct indexes as separate Elements:
Elements e = doc.select("td.yfnc_tabledata1");
Element open = e.get(1); // index for open is 1
Element volume = e.get(9); // index for volume is 9
System.out.println("Open: " + open.text());
System.out.println("Volume: " + volume.text());
Will output:
Open: 1,037.16
Volume: 1,613,009
You can't use getElementsByTag("Open") or getElementsByTag("Volume") because those tags don't exist.
I don't sure it return right result but data will contain in :
doc.select("span.time_rtq_ticker");

Categories