Input already created object via Scanner and do something with it - java

I want to know if it is possible to write an object name in an input(Scanner or maybe another way?) through the console and then do something with it.
package test;
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Person p1 = new Person(1, "pedro");
Person p2 = new Person(2, "juan");
Person p3 = new Person(3, "diego");
ArrayList personList = new ArrayList();
personList.add(p1);
personList.add(p2);
//Something like this doesn't work :S
Person personToAdd = input.nextPerson();
personList.add(personToAdd);
}
}
for example in this case I wanna input the object name "p3" and then add it to the ArrayList, is there any way to do something like this?

List<Person> personList = new ArrayList<Person>();
personList.add(p1);
personList.add(p2);
// you need to get each field you want to save with scanner
// nextLine/nextInt and so on to set other field
// e.q newPerson.setAge(<value from scanner>)
String personName = input.nexLine();
Person newPerson = new Person(personName);
personList.add(newPerson);

Related

How do I find a specific string from an array list using (.contains)

I need to find a specific string (letter) from an array list. I have used the .add function to add a list I have created previously into my array. How do I (using my array list) find a specific word with a particular letter that the user has typed in.
import java.util.*;
public class Library {
public static void main (String[] args)
{
ArrayList<Book> bookList = new ArrayList<Book>();
ArrayList<libraryMembers> memberList = new ArrayList<libraryMembers>();
String userChoice;
{
//Using previous class and assigning values to ID, Phone, Name, and Surname
libraryMembers lm1 = new libraryMembers (1111, 3234231, "Glock", "John");
libraryMembers lm2 = new libraryMembers (1112, 3234231, "Ackerman", "Mikasa");
libraryMembers lm3 = new libraryMembers (1113, 341231, "Crab", "Armin");
libraryMembers lm4 = new libraryMembers (1114, 3423431, "Bacony", "Conny");
libraryMembers lm5 = new libraryMembers (1115, 3423431, "Jaeger", "Erwin");
libraryMembers lm6 = new libraryMembers (1116, 3423431, "Jaeger", "Zeke");
//Printing member information
lm1.informationPrint();
lm2.informationPrint();
lm3.informationPrint();
lm4.informationPrint();
lm5.informationPrint();
lm6.informationPrint();
memberList.add(lm1);
memberList.add(lm2);
memberList.add(lm3);
memberList.add(lm4);
memberList.add(lm5);
memberList.add(lm6);
From this array that I have put the information in I want the user to input a letter and for the program to output all the names and surnames containing that specific letter.
List.contains() only tells you if the list contains a certain object based on equals. And contains would expect an argument of the List type (in your case LibraryMembers).
But you can achieve the desired result as follows. This presumes that you have getters and setters for first and last names. It works by streaming the memberlist and searching each name for the desired letter. The search is case significant but can be changed using toLowerCase on the names and always using lower case on the required character or substring to find.
boolean result = memberList.stream()
.anyMatch(lm->lm.getLastName().contains("G") ||
lm.getFirstName().contains("G"));
Then do your test on result.
If you want to recover all the entries that match, you can do this.
List<LibraryMembers> results = memberList.stream()
.filter(lm->lm.getLastName().contains("G") ||
lm.getFirstName().contains("G"))
.collect(Collectors.toList());
if (results.size() > 0) {
results.forEach(System.out::println); // requires toString override
// in LibraryMember class.
} else {
System.out.println("Request not found");
}
I want the program to look something like this:
System.out.println("The program will allow the user to search for a string by typing a
letter")
userAnswer = scan.next();
boolean userAnswer = memberList.contains("G");
if (userAnswer)
System.out.println("The list contains Glock,");
else
System.out.println("The list does not contain any words with that letter");
So that the information comes from:
import java.util.*;
public class Library {
public static void main (String[] args)
{
ArrayList<Book> bookList = new ArrayList<Book>();
ArrayList<libraryMembers> memberList = new ArrayList<libraryMembers>();
String userChoice;
{
//Using previous class and assigning values to ID, Phone, Name, and Surname
libraryMembers lm1 = new libraryMembers (1111, 3234231, "Glock", "John");
libraryMembers lm2 = new libraryMembers (1112, 3234231, "Ackerman", "Mikasa");
libraryMembers lm3 = new libraryMembers (1113, 341231, "Crab", "Armin");
libraryMembers lm4 = new libraryMembers (1114, 3423431, "Bacony", "Conny");
libraryMembers lm5 = new libraryMembers (1115, 3423431, "Jaeger", "Erwin");
libraryMembers lm6 = new libraryMembers (1116, 3423431, "Jaeger", "Zeke");
//Printing member information
lm1.informationPrint();
lm2.informationPrint();
lm3.informationPrint();
lm4.informationPrint();
lm5.informationPrint();
lm6.informationPrint();
// The line above just prints out the information
memberList.add(lm1);
memberList.add(lm2);
memberList.add(lm3);
memberList.add(lm4);
memberList.add(lm5);
memberList.add(lm6);
// Using this line I have added my lists to the array
It does not need to be case sensitive.
I've tried something like this:
public static void main (String[] args)
{
ArrayList<String> memberList = new ArrayList<String>();
memberList.add("Glock, John, Ackerman, Mikasa, Crab, Armin, Bacony, Conny,
Jaeger, Erwin, Jaeger, Zeke");
boolean userAnswer = memberList.contains("G");
if (userAnswer)
System.out.println("The list contains Glock");
else
System.out.println("The list does not containg string with letter g");
But the only way I can find something is by typing out the full string not the letter.

Stack in Java and object cannot be converted to java.lang.String

How can I reference to this piece of code?
class Example
{
public static void main (String[] args) throws java.lang.Exception
{
Person thePerson1 = new Person("Name1", "Surname1", 1901);
Person thePerson2 = new Person("Name2", "Surname2", 1901);
Person thePerson3 = new Person("Name3", "Surname3", 1901);
Person thePerson4 = new Person("Name4", "Surname4", 1901);
Person thePerson5 = new Person("Name5", "Surname5", 1901);
Stack<String> thestack = new Stack<String>();
thestack.push(thePerson1);
thestack.push(thePerson2);
thestack.push(thePerson3);
}
}
I have an issue:
incompatible types: Person cannot be converted to java. lang. String, line 56
Some messages have been simplified; recompile with -Xdiags: verbose to get full output, line -1
How to change the type of the Stack If I want to use thePerson1, thePerson2,etc?
You should define it as a Stack<Person>, not a Stack<String>:
Stack<Person> thestack = new Stack<Person>();

how to copy List from one Service to another (Spring Boot)

I have List in StudentService
private List<Student> students = new ArrayList<>(Arrays.asList( new Student("1", "Lukasz", "Nowak", "Cicha 3", "1a"), new Student("2", "Tomasz", "Tomczyk", "Krakowska 13a", "1a"), new Student("3", "Grzegorz", "Adamiak", "Podkarpacka 8", "2b"), new Student("4", "Klaudia", "Kurcz", "Warszawska 13", "2b")));
and i want copy some of elements to PresentService and add a present
I tried to do
List<Presents> presents = new ArrayList<Student>()
but I got only errors
List<Presents> presents = new ArrayList<Student>()
This statement will not compile.
You variable definition is expecting objects of type Presents but you gave it a list of Student.
The easiest solution would be
List<Presents> presents = students.stream().map((student) -> new Present(student)).collect(Collectors.toList());
And create a constructor in Presents class
public Presents(Student student) {
//Create your present object as you would want to here
//For example if you wanted name
this.name = student.getName();
}

Input a name and a role and get an output of that role with the names

I need to do this for school. Its supposed to be a JAVA project.
So for example, if we give an input:
thomas teacher
charlie student
abe janitor
jenny teacher
The output will be:
teachers,thomas,jenny
students,charlie,
janitor,abe.
I am just a beginner so, so far I have this code:
`Scanner in = new Scanner(System.in);
String line = in.nextLine();
String[] words = line.split(" ");
//TreeMap treemap = new TreeMap();
ArrayList<String> admin = new ArrayList<String>();
Scanner input = new Scanner(System.in);
while(true){
Boolean s = input.nextLine().equals("Done");
//treemap.put(line, "admin");
if(words[1].contentEquals("admin")){
admin.add(words[0]);
}
else if(s == true){
break;
}
}
System.out.println("admins," + "," + admin);`
I was originally using a treemap but I don't know how to make it work so I thought of using an ArrayList and eliminating the brackets at the end.
EDIT:
So I now have the code:
HashMap<String, String> teacher = new HashMap<String, String>();
HashMap<String, String> student = new HashMap<String, String>();
HashMap<String, String> janitor = new HashMap<String, String>();
System.out.println("Enter a name followed by a role.");
Scanner in = new Scanner(System.in);
String line = in.nextLine();
Scanner name = new Scanner(System.in);
String r = name.nextLine();
while(true){
if(line.equals(r + " " + "teacher")){
teacher.put(r, "teacher");
}
}
I'll give you the hint because you should do it yourself.
Use a HashMap<String, List<String>> map and insert your inputs like below:
if(map.containsKey(words[1]))
{
List<String> list = map.get(words[1]);
list.add(words[0]);
map.put(words[1],list);
}
else
{
map.put(words[1],Arrays.asList(words[0]))
}
This way you will get list of names corresponding to each types(student/teacher) etc.
After that iterate over the map and print the list.
I think for a small amount of occupations it's reasonable to accomplish this using just array lists. I think the part you are having trouble with is the input structure so I'll help you out with an example of how to do that part and let you handle the filtering on your own:
private List<String> teachers = new ArrayList<>();
private List<String> students = new ArrayList<>();
private List<String> janitors = new ArrayList<>();
public void seperatePeople(){
Scanner in = new Scanner(System.in);
while(true){
//Keep getting the next line in an infinite loop
String line = in.nextLine();
if(line.equals("Done")){
break; //end the loop
}else{
//Split on the spaces
String[] personArray = line.split(" ");
//Remember each line is structured like : name, occupation
//So when we split the line the array list we get from it
//will be in the same order
putInArray(personArray[0], personArray[1]);
}
}
//Do whatever printing you have to do down here
}
private void putInArray(String name, String occupation) {
//filter and add to the correct list in here
}
If you wanted to implement this using a hashmap the input method would be the same, but instead of putting names into 3 pre-made occupation arraylists you create arraylists and put them inside a hashmap as you go:
private HashMap<String, List<String>> peopleHashMap = new HashMap<>();
public void seperatePeople(){
Scanner in = new Scanner(System.in);
while(true){
//Keep getting the next line in an infinite loop
String line = in.nextLine();
if(line.equals("Done")){
break; //end the loop
}else{
//Split on the spaces
String[] personArray = line.split(" ");
//Remember each line is structured like : name, occupation
//So when we split the line the array list we get from it
//will be in the same order
putInArray(personArray[0], personArray[1]);
}
}
//You can get all the keys that you created like this
List<String> keys = new ArrayList<>(peopleHashMap.keySet());
}
private void putInArray(String name, String occupation) {
if(peopleHashMap.containsKey(occupation)){
//If the key (occupation in this case) is already in the hashmap, that means that we previously
//made a list for that occupation, so we can just the name to that list
//We pull out a reference to the list
List<String> listOfNames = peopleHashMap.get(occupation);
//And then put the new name into that list
listOfNames.add(name);
}else{
//If the key isn't in the hashmap, then we need to make a new
//list for this occupation we haven't seen yet
List<String> listOfNames = new ArrayList<>();
//We then put the name into the new list we made
listOfNames.add(name);
//And then we put that new list with the into the hashmap with the occupation as the key
peopleHashMap.put(occupation, listOfNames);
}
}

Passing arrays into testclass constructors

I need to pass a 1d array that isn't defined in a method.
I need to create a testclass then make the arrays myself.
I'm just not sure about the syntax.
Example, here's my company class:
public class Company
{
String name;
String address;
Employee employeeList[] = new Employee[3];
public Company (String name, String address ,
Employee employeeList, String jobTitle )
{
this.name = name;
this.address = address;
}
public void printDetails()
{
for(int i = 0; i>employeeList.length;i++)
{
System.out.println(" The companys name is " + name);
System.out.println(" The Companys Address is "+ address);
System.out.println("The List of employees are " + employeeList[i].name);
System.out.println("The Titles of These Employees are " + employeeList[i].jobTitle);
}
}
}
But my testclass is where the problem lies.
Where do I go from here? Do do I put arrays(employees) into it?
public class TestCompany
{
public static void main(String[] args)
{ employees?
Company hungryBear = new Company("hungryBear ", "Those weird apartments ",////// );
}
}
public Company (String name, String address ,
Employee employeeList, String jobTitle )
Should be:
public Company (String name, String address ,
Employee []employeeList, String jobTitle )
Right now, you're not passing an array to your method, your passing an instance. You need to tell Java that you're passing an array.
Editted with new knowledge of the employee class...
Also, you will need to build the array in your main function before you pass it. Something like this:
public static void main(String[] args){
Employee [] employeeList = {
new Employee("Samuel T. Anders", "Player, Caprica Buccaneers"),
new Employee("William Adama", "Commander, Battlestar Galactica")
};
Company hungryBear = new Company("hungryBear ", "Those weird apartments ", employeeList);
}
Not really sure this answers your question, but maybe this will help you with the syntax of array passing a little.
Another edit, another way to initialize an array:
Empolyee [] employeeList = new Employee[2];
employeeList[0] = new Employee("Samuel T. Anders", "Player, Caprica Buccaneers");
employeeList[1] = new Employee("William Adama", "Commander, Battlestar Galactica");
Empolyee [] employeeList = new Employee[2];
for(int i=0;i<2;i++){
Scanner input = new Scanner(System.in);
employeeList[i] = input.next();
}

Categories

Resources