Ok... I now this is a silly question, but I am struggling with this.
public class University {
private List<Student> students;
public University() {
this.student = new ArrayList();
}
public void loadFile(String fileStudents) throws IOException {
BufferedReader readStudents = new BufferedReader(new FileReader(fileStudents));
while(true){
String line = readStudents.readLine();
if( line == null)
break;
String fields[] = line.split(":");
Student e = new Student(Long.parseLong(fields[0]),fields[1], fields[2]);
//System.out.println(e);
students.add(e);
}
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
I want to create a new method passing as a paramenter the object "e".
I want to return e.getNome();
Related
Real title: How do I convert json to custom object using gson(custom object contains ArrayLists and HashMap)?
Problem:
I added an HashMap to my custom object and since then when im trying to convert JSON to my custom object I get this error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 59 path $[0].currentLesson.students.
What do I need to change? ask for any other info you might need from me and I shall give it to you. Thank you!
Code:
private void initializeDatabase() {
ArrayList<Group> groups = null;
SharedPreferences sharedPreferences = getSharedPreferences(Database.SHARED_PREFERENCES_STRING, MODE_PRIVATE);
Gson gson = new Gson();
String groupsJason = sharedPreferences.getString(Database.GROUPS_STRING, null);
Type typeGroup = new TypeToken<ArrayList<Group>>(){}.getType();
groups = gson.fromJson(groupsJason, typeGroup);
if(groups == null){
groups = new ArrayList<>();
}
Database.setGroups(groups);
}
public class Group {
private String groupName;
private ArrayList<Student> students;
private ArrayList<Lesson> lessons;
private Lesson currentLesson;
public Group(String groupName) {
this.groupName = groupName;
students = new ArrayList<>();
lessons = new ArrayList<>();
}
public Group(String groupName, ArrayList<Student> students) {
this.groupName = groupName;
this.students = students;
lessons = new ArrayList<>();
}
public void setCurrentLesson(String currentLesson) {
this.currentLesson = new Lesson(currentLesson, students);
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public ArrayList<Student> getStudents() {
return students;
}
public int getGroupSize() {
return students.size();
}
public Boolean getArrivedToLesson(Student student){
return currentLesson.getArrivedToLesson(student);
}
public Lesson getCurrentLesson() {
return currentLesson;
}
public void saveLesson() {
lessons.add(currentLesson);
}
}
public class Lesson {
private String lessonDate;
private HashMap<Student, Boolean> students;
public Lesson(String lessonDate, ArrayList<Student> students) {
this.lessonDate = lessonDate;
this.students = new HashMap<>();
for (Student student : students) {
this.students.put(student, false);
}
}
public String getLessonDate() {
return lessonDate;
}
public void arrivedToLesson(Student student) {
student.arrivedToLesson();
students.put(student, true);
}
public void didntArriveToLesson(Student student) {
student.didntArriveToLesson();
students.put(student, false);
}
public Boolean getArrivedToLesson(Student student) {
return students.get(student);
}
}
private void saveData(){
group.saveLesson();
SharedPreferences sharedPreferences = getSharedPreferences(Database.SHARED_PREFERENCES_STRING, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String groupsJason = gson.toJson(Database.getGroups());
editor.putString(Database.GROUPS_STRING, groupsJason);
editor.apply();
Toast.makeText(this, String.format(getResources().getString(R.string.saved_attendance), lessonDate), Toast.LENGTH_SHORT).show();
onButtonBackClick();
}
I've managed to solve the problem. The problem was that my map - I changed it to HashMap<String, Object>. The string represents my custom object's main attribute - in my case it's name, the object is a boolean and I casts it when needed.
So I have a Person class and a biostats.csv file that I want to import into a person[] array. How can I do this? I want to make it so that each line is one line, so one Person object array would be Alex and his details, the second Person object array would be Bert and his details etc etc...
Thank you in advance
public Person() {}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
This is what I have but I think it's completely wrong
public static void buildFromFile(String location) throws FileNotFoundException{
File file = new File(location);
Scanner input = new Scanner(file);
while(input.hasNextLine()) {
String data = input.nextLine();
for(int i = 0; i <= people.length; i++) {
people[i].setName(data);
}
}
for(int i = 0; i <= people.length; i++) {
System.out.println(people[i]);
}
The class Files provides line oriented functions.
The entire round cycle would look like:
Path path = Paths.get(location);
List<String> lines = Files.readAllLines(path); // Load all from file.
List<Person> persons = new ArrayList<>();
for (String line : lines) {
...
persons.add(person);
}
List<String> lines = new ArrayList<>();
for (Person person : persons) {
...
lines.add(line);
}
Files.write(path, lines); // Store all to file.
Using apache commons csv you could do something like this:
public static Person[] buildFromFile(File file) throws IOException {
List<Person> persons = new ArrayList<>();
try (InputStream stream = new FileInputStream(file);
Reader in = new InputStreamReader(stream, "UTF-8")) {
CSVFormat format = CSVFormat.EXCEL.withDelimiter(';');
Iterable<CSVRecord> records = format.parse(in);
for (CSVRecord record: records) {
persons.add(recordToPerson(record));
}
}
return persons.toArray(new Person[persons.size()]);
}
private static Person recordToPerson(CSVRecord record) {
Person person = new Person();
person.setName(record.get(0));
person.setGender(record.get(1));
person.setAge(Integer.parseInt(record.get(2)));
person.setHeight(Double.parseDouble(record.get(3)));
person.setWeight(Double.parseDouble(record.get(4)));
return person;
}
For some reasons i get null pointer errors in the code down. I'm working with a book of examples and trying to make smth mine, but seems like theres a change in java or mistake in book.
I'm making a Chatbot(sort of AI) and can't get it working in java. When i run the program it lets me only write Hi and then it replays.
When i try to give him another word like engi he acts like i always say hi.
If i restart and write first engi, then the error pops up, null pointer for some reason.
Can anyone help?
import java.io.IOException;
import java.util.Scanner;
import org.apache.http.client.ClientProtocolException;
import com.google.gson.*;
public class engibot
{
JsonObject context;
public static void main (String[] args) {
engibot c= new engibot();
Scanner scanner= new Scanner(System.in);
String userUtterance;
do {
System.out.print("User:");
userUtterance=scanner.nextLine();
//end conversation
if (userUtterance.equals("QUIT")) {break;}
JsonObject userInput=new JsonObject();
userInput.add("userUtterance", new JsonPrimitive(userUtterance));
JsonObject botOutput = c.process(userInput);
String botUtterance = "";
if(botOutput !=null && botOutput.has("botUtterance")) {
botUtterance = botOutput.get("botUtterance").getAsString();
}
System.out.println("Bot:" + botUtterance);
}while(true);
scanner.close();
}
public engibot() {
context =new JsonObject();
}
public JsonObject process(JsonObject userInput) {
//step 1: process user input
JsonObject userAction = processUserInput(userInput);
//step 2: update context
updateContext(userAction);
//step 3: identify bot intent
identifyBotIntent();
//step 4: structure output
JsonObject out = getBotOutput();
return out;
}
public JsonObject processUserInput(JsonObject userInput) {
String userUtterance = null;
JsonObject userAction = new JsonObject();
//default case
userAction.add("userIntent", new JsonPrimitive(""));
if(userInput.has("userUtterance")) {
userUtterance= userInput.get("userUtterance").getAsString();
userUtterance=userUtterance.replaceAll("%2C", ",");
}
if (userUtterance.matches("(hi)|(hi | hello)( there)?")) {
userAction.add("userIntent", new JsonPrimitive("greet"));
}
else if (userUtterance.matches("(thanks)|(thank you)")) {
userAction.add("userIntent", new JsonPrimitive("thank"));
}
else if(userUtterance.matches("(engi) | (engagment)")) {
userAction.add("userIntent", new JsonPrimitive("request_engi"));
}
else {
//contextual processing
String currentTask = context.get("currentTask").getAsString();
String botIntent = context.get("botIntent").getAsString();
if(currentTask.equals("requestEngi") && botIntent.equals("requestUserName")) {
userAction.add("userIntent", new JsonPrimitive("inform_name"));
userAction.add("userName", new JsonPrimitive(userUtterance));
}
}
return userAction;
}
public void updateContext(JsonObject userAction) {
//copy userIntent
context.add("userIntent", userAction.get("userIntent"));
String userIntent = context.get("userIntent").getAsString();
if(userIntent.equals("greet")) {
context.add("currentTask", new JsonPrimitive("greetUser"));
}else if (userIntent.equals("request_engi")) {
context.add("currentTask", new JsonPrimitive("requestEngi"));
}else if (userIntent.equals("infrom_city")) {
String userName = userAction.get("userName").getAsString();
Engi userInfo = DB.getUserInfo(userName);
if(!userInfo.get("userName").isJsonNull()) {
context.add("placeOfWeather", userInfo.get("cityCode"));
context.add("placeName", userInfo.get("cityName"));
}
}else if (userIntent.equals("thank")) {
context.add("currenTask", new JsonPrimitive("thankUser"));
}
}
public void identifyBotIntent() {
String currentTask = context.get("currentTask").getAsString();
if(currentTask.equals("greetUser")) {
context.add("botIntent", new JsonPrimitive("greetUser"));
}else if(currentTask.equals("thankUser")) {
context.add("botIntent", new JsonPrimitive("thankUser"));
}else if (currentTask.equals("requestEngi")) {
if (context.get("userName").getAsString().equals("unknown")) {
context.add("botIntent", new JsonPrimitive("requestUserName"));
}
else {
Integer time = -1;
if (context.get("").getAsString().equals("current")) {
time=0;
}
Engi userReport =null;
userReport = DB.getUserInfo(
context.get("userName").getAsString());
if(userReport !=null) {
context.add("userReport", new JsonPrimitive("userReport"));
context.add("botIntent", new JsonPrimitive("informUser"));
}
}
}else {
context.add("botIntent", null);
}
}
public JsonObject getBotOutput() {
JsonObject out=new JsonObject();
String botIntent = context.get("botIntent").getAsString();
String botUtterance="";
if(botIntent.equals("greetUser")) {
botUtterance= "Hi there! I am EngiMan, your engagement bot! " + "What would you like to do? Engage someone or something else?";
}else if(botIntent.equals("thankUser")) {
botUtterance="Thanks for talking to me! Have a great day!!";
}else if (botIntent.equals("requestName")) {
botUtterance="Ok. What's his name?";
}else if(botIntent.equals("informUser")) {
String userDescription= getUserDescription(context.get("userName").getAsString());
String engiIndex= getEngiIndex();
botUtterance = "Ok. "+"Engagment index of "+userDescription+" is"+engiIndex+".";
}
out.add("botIntent", context.get("botIntent"));
out.add("botUtterance", new JsonPrimitive(botUtterance));
return out;
}
private String getEngiIndex() {
return context.get("engiIndex").getAsString();
}
private String getUserDescription(String userName) {
if (userName.equals("current")) {
return "current";
}
return null;
}
}
import com.google.gson.JsonElement;
public class Engi {
private String Name;
private String LastName;
private int Age;
private double EngiIndex;
private String Firm;
private String Team;
public JsonElement get(String string) {
// TODO Auto-generated method stub
return null;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lasteName) {
LastName = lasteName;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
public double getEngiIndex() {
return EngiIndex;
}
public void setEngiIndex(double engiIndex) {
EngiIndex = engiIndex;
}
public String getFirm() {
return Firm;
}
public void setFirm(String firm) {
Firm = firm;
}
public String getTeam() {
return Team;
}
public void setTeam(String team) {
Team = team;
}
}
I am new to Java and I am starting to work with ArrayLists. What I am trying to do is create an ArrayList for students. Each student has different attribute associated with them (name, id). I am trying to figure out how to add a new student object with this attributes. Here is what I have:
ArrayList < Student > studentArray;
public Student(String name, int id) {
this.fname = name;
this.stId = id;
}
public Stromg getName() {
return fname;
}
public int getId() {
return stId;
}
public boolean setName(String name) {
this.fname = name;
return true;
}
public boolean setIdNum(int id) {
this.stId = id;
return true;
}
What you need is something like the following:
import java.util.*;
class TestStudent
{
public static void main(String args[])
{
List<Student> StudentList= new ArrayList<Student>();
Student tempStudent = new Student();
tempStudent.setName("Rey");
tempStudent.setIdNum(619);
StudentList.add(tempStudent);
System.out.println(StudentList.get(0).getName()+", "+StudentList.get(0).getId());
}
}
class Student
{
private String fname;
private int stId;
public String getName()
{
return this.fname;
}
public int getId()
{
return this.stId;
}
public boolean setName(String name)
{
this.fname = name;
return true;
}
public boolean setIdNum(int id)
{
this.stId = id;
return true;
}
}
You instantiate a Student object by passing the appropriate values to the constructor.
Student s = new Student("Mr. Big", 31);
You place elements into an ArrayList (or List) by using the .add() operator.*
List<Student> studentList = new ArrayList<Student>();
studentList.add(s);
You retrieve user input via the use of a Scanner bound to System.in.
Scanner scan = new Scanner(System.in);
System.out.println("What is the student's name?");
String name = scan.nextLine();
System.out.println("What is their ID?");
int id = scan.nextInt();
You repeat this with a loop. That portion shall be left as an exercise to the reader.
*: There are other options, but add() simply adds it to the end, which is typically what you want.
final List<Student> students = new ArrayList<Student>();
students.add(new Student("Somename", 1));
... and so on add more students
This is not supposed to be a client class. I'm just making a class for others to use. I'm using this for a Highschool. For example i have classes for the address, teacher, students, principal, roomnumber, etc..But its not compiling for some odd reason. I believe its because I'm not declaring a field but not sure.
import java.io.*;
public class HighSchool {
// Constructors
public HighSchool() { }
public HighSchool(String title, String teacher, int roomNumber, String period, String[] students, String address, String subjects ) {
this.title = title;
this.teacher = teacher;
this.roomNumber = roomNumber;
this.period = period;
this.String[] students = students;
this.String address =a ddress;
this.String subjects = subjects;
}
public class Classcourse (String title, String teacher, int roomNumber, String period, String[] students, String address, String subjects
private String period;) {
public String gettitle() {
return title;
}
public void settitle(String title) {
this.title = title;
}
public String getteacher() {
return teacher;
}
public void setteacher(String teacher) {
this.teacher = teacher;
}
public int getroomNumber() {
return roomNumber;
}
public void setroomNumber (int roomNumber) {
this.roomNumber = roomNumber;
}
public String getperiod() {
return getperiod();
}
public void setperiod (String period) {
this.period = period;
}
public String[] getstudents () {
return students[];
}
public void setstudents[] (String[] students
private String address;) {
this.students = students;
}
public String getaddress() {
return address;
}
public void setaddress (String address) {
this.address = address;
}
public String getsubjects() {
return subjects;
}
public void setsubjects (String subjects) {
this.subjects = subjects;
}
}
// modifier method
public void addstudents(String students) {
String[] newstudents = new String[students.length + 1];
for (int i = 0; i < students.length; i++) {
newstudents[i] = students[i];
}
newstudents[students.length] = student;
students = newstudents;
}
public boolean isInClass(String students) {
for (int i = 0; i < students.length; i++) {
if (students[i].equals(students)) {
return true;
}
}
return false;
}
// static creator method
public static HighSchool readFromInput() throws IOException {
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a HighSchool title: ");
HighSchool newHighSchool = new HighSchool(kb.readLine());
String students = null;
do {
System.out.print("Enter a student, or press Enter to finish: ");
students = kb.readLine();
if (students != null){
newHighSchool.addstudents(students);
}
} while (students != null);
return newHighSchool;
}
// Variables (Fields)
private String title;
private String[] students;
}
In addition, you wrote something that doesn't make sense from the point of view of Java Compiler:
private String period;) {
- probably remove ")".
The second thing:
Take a look on the declaration of class Classcourse.
It rather sounds wrong, although it can be an issue of this site's editor or something...
An "overall" hint - java has a very "intelligent" compiler in the most of the cases it can say what's wrong exactly with your code, so, assuming you're a newbie in Java, try to understand what compiler says to you.
Good luck!
Some things I noticed about the code:
public String getperiod() {
return getperiod();
}
This code will cause a endless loop when you call this function.
private String address;) {
this.students = students;
}
The compiler will give an error about the ";)". Change it to "()" to fix this.
Furthermore, you should really tell us more about the errors it's giving you. We can't help you if you don't give us the compiler errors.