My program reads question details from a QuestionBank.sql file. Everything is right but instead of getting 12 questions the output contains 10 questions.
The Output is:
GK Simple
GK Simple
GK Medium
GK Complex
Science Complex
History Medium
History Medium
History Simple
History Simple
Geography Medium
**DataManagerImpl.java**
#Override
public Set<Question> generateQuestionPaper(List<Question> list,
List<Criteria> template) {
// TODO Auto-generated method stub
Set<Question> questionSet = new HashSet<Question>();
int count;
int index = 0;
for(Criteria c: template){
count = 0;
while(c.getNoOfQuestion() > count){
index = (int)(Math.random()*list.size());
//System.out.println(index);
Question q = list.get(index);
if(c.getCategory().equals(q.getCategory()) && c.getComplexity().equals(q.getComplexity()) ){
if(!questionSet.contains(q)){
count++;
questionSet.add(q);
System.out.println(q.getCategory()+" "+q.getComplexity());
}
}
}
}
return questionSet;
}
Criteria.java
public class Criteria {
private Category category;
private Complexity complexity;
private int noOfQuestion;
public Criteria() {
}
public Criteria(Category category, Complexity complexity,int noOfQuestion) {
super();
this.noOfQuestion = noOfQuestion;
this.category = category;
this.complexity = complexity;
}
public int getNoOfQuestion() {
return noOfQuestion;
}
public void setNoOfQuestion(int noOfQuestion) {
this.noOfQuestion = noOfQuestion;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public Complexity getComplexity() {
return complexity;
}
public void setComplexity(Complexity complexity) {
this.complexity = complexity;
}
}
List template contains: (Passed as parameter to generateQuestionpaper()
Please help me!!
Problem is with the definition of Math.random() method.
Try after modifying your code as below -
Random random = new Random();
for(Criteria c: template){
count = 0;
while(c.getNoOfQuestion() > count){
index = random.nextInt(list.size());
As, list index is also zero based this should work fine.
Related
I am creating a lobby application which will show all groups on a java tableview. Users are able to join groups that have space in them, else they will not be able to join.
I have been able to create this but I would like to be able to colour the row of the groups that have space in them in green and groups that are full will be coloured in red.
I will provide my code for this below. I am getting NullPointerException, which i dont know why. Thanks.
private void visualGroupAvailability() {
boolean isThereSpace;
for (currentGroupsModel o : groupsTable.getItems()) {
TableRow<currentGroupsModel> currentRow = getTableRow(o.getGroupID());
int limit = o.getNumberOfUsers();
isThereSpace = checkSpaceInGroup(o);
if(isThereSpace) {
currentRow.setStyle("-fx-background-color: #" + "388e3c ");
} else {
currentRow.setStyle("-fx-background-color: #" + "ffcdd2 ");
}
}
}
private TableRow<currentGroupsModel> getTableRow(int rowIndex) {
Set<Node> tableRowCell = groupsTable.lookupAll(".table-row-cell");
TableRow<currentGroupsModel> row = null;
for (Node tableRow : tableRowCell) {
TableRow<currentGroupsModel> r = (TableRow<currentGroupsModel>) tableRow;
row = r;
}
return row;
}
public class currentGroupsModel {
String groupName, groupDescription, hostName, groupType;
Integer numberOfUsers, groupID;
public currentGroupsModel(String gName, String gDesc, String hostName, String groupType, Integer numberOfUsers, Integer groupID){
this.groupName = gName;
this.groupDescription = gDesc;
this.hostName = hostName;
this.groupType = groupType;
this.numberOfUsers = numberOfUsers;
this.groupID = groupID;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getGroupDescription() {
return groupDescription;
}
public void setGroupDescription(String groupDescription) {
this.groupDescription = groupDescription;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public String getGroupType() {
return groupType;
}
public void setGroupType(String groupType) {
this.groupType = groupType;
}
public Integer getNumberOfUsers() {
return numberOfUsers;
}
public void setNumberOfUsers(int numberOfUsers) {
this.numberOfUsers = numberOfUsers;
}
public Integer getGroupID(){
return this.groupID;
}
public void setGroupID(Integer newID){
this.groupID = newID;
}
}
This question cannot really be answered with what you have given us. It is hard looking for a NullPointerException if there is a currentGroupModel we know nothing about and there are constant red hairings. For example why do you store something in limit, you never use it! Why do you pass getTableRow a rowIndex, that you are never using? As far as I get it your getTableRow returns the last TableRow in the table, not a specific one. Please consider fixing those problems first, before eventually providing some code to understand the inner workings of your currentGroupModel.
well, I have List<HighscoreEntry> In which your class is this:
public class HighscoreEntry {
private List<String> users;
private int score;
HighscoreEntry(List<String> users, int score) {
this.users = users;
this.score = score;
}
public List<String> getUsers() {
return users;
}
public void setUsers(List<String> users) {
this.users = users;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
Well, what happens, is because in the other class I have this:
public class ScoreboardItemData {
private final static HighscoreComparator comparator = new HighscoreComparator();
private final List<HighscoreEntry> entries;
private final Map<String, Integer> points;
private int scoreType;
private int clearType;
public ScoreboardItemData(int scoreType, int clearType, List<HighscoreEntry> entries, Map<String, Integer> points) {
this.scoreType = scoreType;
this.clearType = clearType;
this.entries = entries;
this.points = points;
}
public List<HighscoreEntry> getEntries() {
return this.entries;
}
public Map<String, Integer> getPoints() {
return this.points;
}
public void addEntry(List<String> users, int score) {
synchronized (this.entries) {
this.entries.add(new HighscoreEntry(users, score));
this.entries.sort(comparator);
}
} }
Well, I already can add new entries, but I want to change ONLY THE SCORE and increase it, to existing data.
And I tried some things, but without success:
Example 1:
synchronized (this.entries) {
for (int i = 0;i < this.entries.size(); i++) {
if (this.entries.get(i).getUsers() == users) {
this.entries.get(i).increaseScore(score);
this.entries.sort(comparator);
} else {
this.entries.add(new HighscoreEntry(users, score));
this.entries.sort(comparator);
}
}
}
This example update the score, but with the loop, he will add more entries and update others, so will always do this loop.
Example 2:
HighscoreEntry entry = (HighscoreEntry) this.entries.stream().filter((x) -> {
return x.getUsers().equals(users);
});
if (entry.getUsers() != null) {
entry.increaseScore(score);
} else {
entry.setUsers(users);
entry.setScore(score);
}
And this one, return this error:
java.lang.ClassCastException: java.util.stream.ReferencePipeline$2 cannot be cast to com.heraproject.wired.data.ScoreboardItemData$HighscoreEntry
at com.heraproject.wired.data.ScoreboardItemData.addEntry(ScoreboardItemData.java:45)
You need to find the right item in the list based on the identifier and looking at HighscoreEntry that identifier is users. This code will update the score for a HighscoreEntry in the list entries if one exists
public void addScore(List<String> users, int score) {
HighscoreEntry entry = entries.filter( e -> (e.getUsers().equals(users))).findFirst().orElse(null);
if (entry != null) {
entry.setScore(score);
}
}
If I understand correctly, all you need is something like this
// int index, someInt;
this.entries.get(index).setScore(someInt);
However, looking at your model, I would think "high score" would be calculated by iterating over a list of potential User objects, each having their own unique scores. Then you set the score on the user, not the entity holding a list of users.
Well,
Use this method
public void updateEntry(List<String> users, int index) {
synchronized (this.entries) {
HighscoreEntry highScoreEntry = this.entries.get(index);
highscoreEntry.setScore(//Update score);
entries.add(index, highscoreEntry);
}
}
So i am trying to make a deal or no deal game the game is not finished yet but the biggest issue i am having is that when i am trying to assign an array list to a array of type cases it seems like it isn't getting assigned.
I tried to debug and after shuffle the output is correct but i am unable to assign the result to the case array so that i can use it in game
Below are my 3 classes upon assigning the outcome i am getting is
The line i am talking about is the method available cases
public class Case {
private int value = 0;
private String face;
/*
* Constructor for type Case
*/
public Case(int value)
{
this.value = value;
}
/*
* Getter and setter methods for instance data
*/
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getFace() {
return face;
}
public void setFace(String face) {
this.face = face;
}
}
public class Player {
private String name;
private int age;
private boolean canPlay = false;
private int money = 0;
/*
* Constructor for type Player
*/
public Player(String name, int age) {
super();
this.name = name;
this.age = age;
}
/*
* Getter and Setter methods for all instance Data
*/
public Player(boolean canPlay)
{
this.canPlay = canPlay;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public boolean isCanPlay() {
return canPlay;
}
public void setCanPlay(boolean canPlay) {
this.canPlay = canPlay;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
/*
* This method will check if the person playing is at least 18 years old or not
*/
public void checkAge()
{
if(age >= 18)
{
canPlay = true;
System.out.println("Seems like you are old enough to play!");
System.out.println("Let's get started");
}
else
{
canPlay = false;
System.out.println("OH NO! you aren't old enough sadly we won't be able to continue");
}
}
public String toString() {
return "Today's player is "+name+" who is "+age+" old";
}
public static void setupPlayer()throws InputMismatchException
{
String playerName;
int playerAge;
System.out.println("Welcome to the Deal or No Deal game!");
System.out.println("Please state your name:");
Scanner name = new Scanner(System.in);
playerName = name.nextLine();
System.out.println("Welcome "+playerName+" how old are you?");
Scanner age = new Scanner(System.in);
playerAge = age.nextInt();
Player gamePlayer = new Player(playerName, playerAge);
}
public static void Rules()
{
System.out.println("Below listed are the Game Rules\n");
System.out.println("-There are 12 Cases in the game");
System.out.println("-Each case contains a amount of money and you will be "
+ "offered these Cases 1 at a time");
System.out.println("-Upon picking a Case the game will end and you will have a "
+ "chance to walk away with that case");
System.out.println("-If No cases are picked you will get 2 option, to walk away"
+ " with the last Case or take the bankers offer");
System.out.println("-To accept the case type \"Y\" ,to decline it type \"N\"");
}
}
public class SetUpCases {
private Case[] cases = new Case[12];
/*
* This method initializes each object type with an amount which will be the Money in each Case
*/
public void settingUpCases()
{
ArrayList<Integer> myCase= new ArrayList<Integer>();
myCase.add(new Integer(1));
myCase.add(new Integer(50));
myCase.add(new Integer(100));
myCase.add(new Integer(250));
myCase.add(new Integer(500));
myCase.add(new Integer(1000));
myCase.add(new Integer(2500));
myCase.add(new Integer(5000));
myCase.add(new Integer(10000));
myCase.add(new Integer(25000));
myCase.add(new Integer(50000));
myCase.add(new Integer(100000));
/*
* The Shuffle changes which index has what value so game results are different each time played!
*/
Collections.shuffle(myCase);
for(int i = 0; i < cases.length; i++)
{
int value = myCase.get(i);
cases[i] = new Case (value);
System.out.println(cases[i]);
}
}
/*
* Shows which Cases are still available
*/
public void availableCases()
{
for (int k = 0; k < cases.length; k++)
{
System.out.println(cases[k]);
}
}
public void startGame()
{
settingUpCases();
}
}
You are printing case object instead of its value.. use getValue (or getFace) method to print the value (or face). For example
for (int k = 0; k < cases.length; k++)
{
System.out.println(cases[k].getValue());
}
If you want to print both value and face, the best way will be to override the toString method and print these variables there.
The reason you are getting those weird values is not because the assignments aren't working but because you aren't printing the string value of your values. Try the following.
for(int i = 0; i < cases.length; i++){
int value = myCase.get(i);
cases[i] = new Case (value);
System.out.println(Arrays.toString(cases[i]));
}
i have for loop where i get data to send to other method in different class
UserManagerImpl.java
for (User user: userList) {
surveyModel survey = new SurveyModel();
survey.setSurveyData(Id, comment, serveyScore, grade);
}
In other class i have set and get to create list of datas and then want to fetch it by get method.
surveyModel.java
public class SurveySentimentModel {
public static String delimiter = "|||";
private List scores = new ArrayList();
private List negativeData = new ArrayList();
private List PositiveData = new ArrayList();
public void setSurveyData(String Id, String comment, double Score, String grade) {
//want to add score to scores list
//if grade positive add to positive list or else negative after delimiting
}
public double getTotalScore() {
//calculate the sum of scores
return totalScore;
}
public String getTotalSentimentgrade() {
if (totalScore> 0) {
return "Positive";
}
return "Negative";
}
public List getSurveyData() {
//Want to merge list - first negative and then positive
return new ArrayList();
}
}
SurveyModel.java
private String grade;
private Number Score;
private String Id;
private String comment;
public SurveyModel(String Id, String comment, double Score, String grade) {
this.grade= grade;
this.Score= Score;
this.comment = comment;
this.Id = Id;
}
public SurveyModel() {
// TODO Auto-generated constructor stub
}
// getters and setters
IN here i want to
1.) Add score to scores list
2.) want to add graddes to list by negative first with delimiter then positive.
3.) want to get total score.
How could i achive my requirement. I am new to java please help me on this.
Here's a suggestion:
This is the Model class:
public class SurveySentimentModel {
public static String delimiter = "|||";
private List<SurveyModel> scores = new ArrayList();
private List<SurveyModel> negativeData = new ArrayList();
private List<SurveyModel> positiveData = new ArrayList();
public void setSurveyData(String Id, String comment, double score, String grade) {
SurveyModel survey = new SurveyModel(id, comment, score, grade );
scores.add(survey)
if(score >= 0){
positiveData.add(survey);
}else{
negativeData.add(survey);
}
}
public double getTotalScore() {
double sum = 0;
for(SurveyModel s: scores){
sum += s.getScore();
}
return sum;
}
public List getSurveyData() {
List<SurveyModel> joined = new ArrayList(negativeData);
joined.addAll(positiveData)
return joined;
}
}
This is the loop:
SurveySentimentModel sentiments = new SurveySentimentModel();
for (User user: userList) {
sentiments.setSurveyData(user.getId(), user.getComment(), user.getSurveryScore(), user.getGrade());
}
I am trying to write a program where I ask to the user how many persons he wants to implement in this world. Afterwards, I would like as many person objects as the user answered. I defined a person class with a person constructor containing all person variables ( + getters/setters). After this, I tried to create a loop to assign values to my variables (most of them happen random). Currently, I set the number of instances I want to create to 20 (arbitrary).
This is my person class
public class Person implements Item {
public static final int MAX_AGE = 70;
public static final int MAX_SEX_APPEAL = 10;
public static final int MAX_AGRESSION_LEVEL = 10;
public static final int MAX_STRENGTH = 10;
private int id;
private int age;
private boolean gender;
private int sexAppeal;
private int agressionLevel;
private int strength;
private boolean isAlive;
public Person (int id, int age, boolean gender, int sexAppeal, int agressionLevel, int strength, boolean isAlive){
this.setId(id);
this.setAge(age);
this.setGender(gender);
this.setSexAppeal(sexAppeal);
this.setAgressionLevel(agressionLevel);
this.setStrength(strength);
this.setAlive(isAlive);
}
void getBorn () {
isAlive = true;
age = 0;
// a new people is born
// age = 0
// other variables: random
}
void die () {
isAlive = false;
// people die when they reach the max age
// people die when being on the same cell as vulcanos
// people can be murdered
// setAlive = false
}
void murder () {
// when 2 people with min agression level on the same land ==> weakest one dies
}
void move () {
// method to make people move
// random (only to adjucant fields)
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isGender() {
return gender;
}
public void setGender(boolean gender) {
this.gender = gender;
}
public int getSexAppeal() {
return sexAppeal;
}
public void setSexAppeal(int sexAppeal) {
this.sexAppeal = sexAppeal;
}
public int getAgressionLevel() {
return agressionLevel;
}
public void setAgressionLevel(int agressionLevel) {
this.agressionLevel = agressionLevel;
}
public int getStrength() {
return strength;
}
public void setStrength(int strength) {
this.strength = strength;
}
public boolean isAlive() {
return isAlive;
}
public void setAlive(boolean isAlive) {
this.isAlive = isAlive;
}
}
And this is my "test class" where I try to create 20 instances :
import java.util.concurrent.ThreadLocalRandom;
public class test {
public static void main(String[] args) {
for (int i = 0; i < 20; i ++) {
Person person(i) = new Person();
person.setId(i);
person.setAge(ThreadLocalRandom.current().nextInt(0, Person.MAX_AGE + 1));
person.setGender((Math.random() < 0.5));
person.setSexAppeal(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAgressionLevel(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setStrength(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAlive(true);
}
}
}
However, I am getting the following error at this line
Person person(i) = new Person();
The constructor Person () is undefined
Type mismatch: cannot convert from Person to int
I understand those errors but I don't know another way to become to the result I want to achieve
You should make a list and just add the created persons to it.
public class test {
public static void main(String[] args) {
List<Person> persons = new ArrayList<>(); // create a list to store the generated persons
for (int i = 0; i < 20; i++) {
Person person = new Person(); // generate a person
person.setId(i);
person.setAge(ThreadLocalRandom.current().nextInt(0, Person.MAX_AGE + 1));
person.setGender((Math.random() < 0.5));
person.setSexAppeal(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAgressionLevel(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setStrength(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAlive(true);
persons.add(person); /// add the generated person to the list
}
}
}
Also if you want to call the Person constructor without parameters the class must have a constructor that takes no parameters.
public Person() {}