Java list of string don't display all elements [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 days ago.
Improve this question
i'm trying to add elements in a list inside a method and after get it from another method.
Here is the code :
public class ChatMessageRepository {
List<String> msgs = new ArrayList<String>();
ChatMessageRepository addChatMessage(String message) {
msgs.add(message);
System.out.println(msgs);
return null;
}
List<String> getLastTenMessages() {
List<String> firstNElementsList = msgs.stream()
.limit(10)
.collect(Collectors.toList());
return firstNElementsList;
}
}
The problem is when I try to display the firstNElementsList it's alaway empty and also when i print the list from ChatMessageRepository Method it's display me only the last element
Any one have an idea guys ?

Related

Is something wrong with the method? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
So that's my method and i got Main class from my teacher that uses this method and it should return only 1 Suspect but it returns the same one for 8 times or something i am really close on my deadline please help
public ArrayList<Suspect> getCommonPartners(Suspect aSuspect) {
ArrayList<Suspect> commonpartners = new ArrayList<>() ;
for(Suspect s: partners) {
for(Suspect sus: aSuspect.getPartners()) {
if(s.getCodename().equals(sus.getCodename())) {
commonpartners.add(s);
}
}
}
return (commonpartners);
}
Where is 'partners' coming from? You're running a for loop on it. Did you mean aSuspect?
If you are getting multiple of the same value. Do a check on the arraylist before adding it.
public ArrayList<Suspect> getCommonPartners(Suspect aSuspect) {
ArrayList<Suspect> commonpartners = new ArrayList<>() ;
for(Suspect s: partners) {
for(Suspect sus: aSuspect.getPartners()) {
if(s.getCodename().equals(sus.getCodename())) {
if(!commonpartners.contains(s)) {
commonpartners.add(s);
}
}
}
}
return (commonpartners);
}

I need to initialize a List of Maps in java, but every way I've tried inits it to null [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 3 years ago.
Improve this question
So I'm trying to initialize a List of Maps, but every way I initialize it, it inits to null.
So I've tried googling and stack overflowing this, and there are some similar posts, but nothing explicitly like this. Just curious how I can init this so it isn't null, so I can add to it later in the code.
List<Map<String, Response>> listOfResponses = new ArrayList<Map<String, Response>>();
Then how I'm trying to add to list:
HashMap<String, Response> thisResponse = new HashMap<>();
int i = 1;
for (Question q : questions)
{
if( q == null)
{
return;
}
else {
q.DisplayQuestion();
mo.displayString("Please enter your response for the previous question: ");
Response r = Response.CreateResponse(mi.getNextString());
q.setResponse(r);
thisResponse.put(Integer.toString(i), r);
//q.setResponse(Response.CreateResponse(mi.getNextString()));
i++;
}
}
listOfResponses.add(thisResponse);
Save(this);
Error message is a nullpointer, because the list is initing to null, meaning it can't be added to.
Real Error message stack trace:
in thread "main" java.lang.NullPointerException
at com.company.Survey.TakeSurvey(Survey.java:304)
at com.company.Menu.SurveyMenu(Menu.java:129)
at com.company.Menu.SurveyMenu(Menu.java:78)
at com.company.Menu.StartMenu(Menu.java:24)
at com.company.Main.main(Main.java:21)
Your problem is you are reusing the same map, and only adding that single map to the responses, and only if there are no null questions, which aborts the method without using/saving thisResponse at all.
Your code should look more like:
for (Question q : questions) {
if (q == null) {
continue; // ignore nulls
}
HashMap<String, Response> thisResponse = new HashMap<>();
listOfResponses.add(thisResponse);
// populate thisResponse
}

How to debug an if statement that is not working? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
import java.util.*;
public class ass {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[]c={"sid","is","cool"};
List<String>list1=new ArrayList<String>();
for(String w:c){
list1.add(w);
}
String[]q={"is"};
List<String>list2=new ArrayList<String>();
for(String t:q){
list2.add(t);
}
EditList(list1,list2);
for(int i=0;i<list1.size();i++){
System.out.printf("%s ", list1.get(i));
}
}
public static void EditList(Collection<String>l1, Collection<String>l2){
Iterator<String>it=l1.iterator();
while(it.hasNext()){
if(l2.contains(it.next()));
it.remove();
}
}
}
In this programme I have two lists. I wanted to remove the items that are common in the first and second list from the first list and print it. I don't want a workaround or any other code suggestions. Can someone please explain why my code is not working?
I am following New Boston's tutorials.
Here:
if(l2.contains(it.next()));
it.remove();
That semicolon after if is a real statement.
Thus it.remove() happens always; like if ... that if not there!
Thus the real answer: always always always use
if (){
stuff
}
... even for single statements! Same for loops!
try
public static void EditList(Collection<String>l1, Collection<String>l2){
Iterator<String>it=l1.iterator();
while(it.hasNext()){
String current=it.next();
if(l2.contains(current)){
i1.remove(current); // assuming u wish to remove from l1
}
}
}

What does mean, lines.next.toInt in Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What does mean this line in java:
m = lines.next.toInt
Thanks.
You can get this done in java using any reader. e.g- BufferedReader, FileReader anything like this.
public class InJava
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
//
//in main()
public static void main(String [] args)
{
Object obj= br.readLine();
}
}
If you are using a list use Iterator.
public class InJava
{
List<double> lst= new ArrayList<double>();
//fill the list.
Iterator it= lst.iterator();
//in main()
while(it.hasNext())
{
Object obj= it.next();
//Continue
}
}
lines is perhaps an iterable collection of Double objects. The code that you've posted accesses the next element in sequence and converts it to an integer.
If you can post the surrounding code as well, we could get more context on the same.

Testing Java class using JUnit [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 8 years ago.
Improve this question
public void printSummaryForPatient(String name){
Patient p = findPatient(name);
p.printPatientSummary();
p.computeBMI();
}
My method to test:
#Test
public void testPrintSummaryForPatient() {
Patient patient_adult=new Patient("Ted",24,1.90,70.0,"Leicester");
//Patient Patient_child=new Patient("Kate",4,1.90,70.0,"Leicester");
// Patient Patient_elderly=new Patient("Bill",124,1.90,70.0,"Leicester");
surgery_N.findPatient("Ted");
patient_adult.printPatientSummary();
assertEquals("Ted", patient_adult.getName());
assertEquals("-----------PATIENT SUMMARY: ---------"+"\n"+"NAME: "+patient_adult.name+"\n"+"Age: "+patient_adult.getAge()+"\n"+"Address: "+patient_adult.getAddress()+"\n"+"Height: "+patient_adult.getHeight()+"\n"+"Weight: "+patient_adult.getWeight()+"\n"+"------------------------------"+separator,ans.toString());
patient_adult.computeBMI();
assertEquals(19.390581717451525, patient_adult.computeBMI(), 0.0);
}`
The problem is that the way I use to test doesn't cover the original file at all. Hope I can get some help from you guys.
You could assign a different writer to System.out (assuming that's where your output goes) and inspect what gets written there. In general, you probably want to make the writer a parameter of printSummary or inject it into the class somehow.
So basically you want to do this:
#Test
public void testPrintSummaryForPatient() {
Patient patient_adult=new Patient("Ted",24,1.90,70.0,"Leicester");
surgery_N.printSummaryForPatient("Ted");
}
But can't do any asserts, because the Patient is not returned.
Do you want to return the patient?:
public Patient printSummaryForPatient(String name){
Patient p = findPatient(name);
p.printPatientSummary();
p.computeBMI();
return p;
}
After that you could use your assertions. It seems more like a conceptual problem of how you organize your methods.
You have methods in printSummaryForPatient, that don't seem to do anything. Their return value is not returned or saved.

Categories

Resources