I am trying to get to work getters and setters with arrays, I have created 2 objects Question and Answer with their get and setters. I have also created 2 arrays one called Question and one called Answer.
class Question {
private String[] questions;
public void setQuestion(String questions[]) {
this.questions = questions;
}
public String[] getQuestion() {
return questions;
}
}
class Answer {
private String[] answers;
public void setAnswer(String answers[]) {
this.answers = answers;
}
public String[] getAnswer() {
return answers;
}
}
But when trying to print the questions it does not recognise `getQuestion'
for (int n = 0; n<getQuestion.length; n++) {
System.out.println("Question" + (n+1));
System.out.println(getQuestion(Question[n]);
}
getQuestion is a method of your Question class and should be called like that, like questions.getQuestion(). Probably, you want to return a single question for getQuestion too?
You need to create an instance of the Question class then call the getQuestion() method.
Depending on what you are trying to do you may also need to make the Question class public using the public modifier
Note
You could also as Pavneet_Singh pointed out make the getQuestion() method static thus removing the need to create a new instance of the Question class.
Updated code
Question question = new Question();
for (int n = 0; n<question.getQuestion().length; n++) {
System.out.println("Question" + (n+1));
//note that this wont work, you dont pass any parameters to the getQuestion() method
System.out.println(getQuestion(Question[n]);
}
Some improvements to your code;
public class Question {
private String question;
//Use Question constructor to populate the question string
public Question( String question ){
this.question = question;
}
//get the question
public String getQuestion(){
return question;
}
}
//follow same pattern here
public class Answer {
private String answer;
public Answer( String answer ){
this.answer = answer;
}
public String getAnswer(){
return answer;
}
}
Main Method
//Create array of type Question
Question[] questions = new Question[3];
//create new questions and use constructor to set string question
Question question1 = new Question('What is your name?');
Question question2 = new Question('What is your age?');
Question question3 = new Question('What is your favourite color?');
//add questions to array
questions.add(question1);
questions.add(question2);
questions.add(question3);
int counter = 0;
//loop through the array
for (Question question : questions) {
System.out.println("Question " + (counter+1));
System.out.println(question.getQuestion();
counter++;
}
Ill let you figure out how to map questions to answers
Related
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 2 years ago.
Improve this question
I want to create a class outside the public class but in the same file, and in that class I wanna create a private array which can only be accessed by creating object through the previous public class. I also wanna store data to that array through the public class.
I suggest you to start learning java, this will save you from asking this kind of question next time. For the moment you can find how to achieve what you are asking for in the example bellow :
public class Learning {
public static void main(String[] args) {
Course course = new Course();
List<String> materials = new ArrayList<>();
materials.add("java basic courses");
materials.add("OOP courses");
// here we use setters to set course materials and notes
course.setMaterials(materials);
course.setNotes(new int[] {19,20});
System.out.println("Display course materials");
for (String material : course.getMaterials()) {
System.out.println("Material : " + material);
}
System.out.println("Display Notes");
for (int note : course.getNotes()) {
System.out.println("Note : " + note);
}
}
}
class Course {
private List<String> materials;
private int[] notes;
public List<String> getMaterials() {
return materials;
}
public void setMaterials(List<String> materials) {
this.materials = materials;
}
public int[] getNotes() {
return notes;
}
public void setNotes(int[] notes) {
this.notes = notes;
}
}
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 2 years ago.
Improve this question
In test cases
adding this 3 doctor data into Doctors
Ghouse Cardiology 25, Manzoor Cardiology 15, Sunil Cardiology 15
using
List doctors ......;
doctors.add(new Doctor("Ghouse", "Cardiology", 25) );
after adding remaining both
while running code there is error at some line which I mentioned in code as error generated.
Doctor Class
class Doctor implements Comparable<Doctor> {
private String name;
private String speciality;
private int experience;
Doctor(String name, String speciality, int experience){
this.name=name;
this.speciality=speciality;
this.experience=experience;
}
//getters and setters methods
public int compareTo(Doctor d2) {
//comparing objects for sorting
}
}
Class for get specific doctor data
class DoctorService {
private List<Doctor> doctorsRepository;
public DoctorService(List<Doctor> doctorsRepository) {
this.doctorsRepository = doctorsRepository;
}
public List<Doctor> getExperiencedDoctors(int expr){
List<Doctor> expDoc = new ArrayList<Doctor>();
for (int j=0; j<doctorsRepository.size(); j++){
if (doctorsRepository.get(j).getExp()>=expr){
String strnm = (doctorsRepository.get(j)).getName();
String strspc = (doctorsRepository.get(j)).getSpeciality();
int dxp = (doctorsRepository.get(j)).getExp();
expDoc.add(new Doctor(strnm, strspc, dxp));
}
}
Collections.sort(expDoc);
return expDoc; //THIS LINE GENERATES ERROR
}
public Set<Doctor> getSpecialityDoctor(String spc){
Set<Doctor> spcDoc = new HashSet<Doctor>();
//same for loop as above in list<Doctor>
return spcDoc; //THIS LINE GENERATES ERROR
}
}
Main Class
public class Source {
private static String doctorsData;
static {
StringBuilder doctors = new StringBuilder();
doctors.append("Amy-Pediatrics-16;");
doctors.append("John-Dermatology-10;"
doctorsData = doctors.toString();
}
public static void main(String[] args) {
String[] docStr = doctorsData.split(";");
ArrayList<Doctor> Doctors=new ArrayList<Doctor>();
for(int i=0; i<docStr.length; i++){
String dd= docStr[i];
Doctors.add(new Doctor(docStr[i].split("-")[0], docStr[i].split("-")[1], Integer.parseInt(docStr[i].split("-")[2])));
}
DoctorService ds = new DoctorService(Doctors);
Scanner sc = new Scanner(System.in);
int ch = sc.nextInt();
if(ch==1){
int lmt = sc.nextInt();
List<Doctor> filtDoc=new ArrayList<Doctor>();
filtDoc = ds.getExperiencedDoctors(lmt);
for (int k=0; k<filtDoc.size(); k++){
System.out.println(filtDoc.get(k).getName() + " " +filtDoc.get(k).getSpeciality()+ " " + filtDoc.get(k).getExp() );
}
}else if(ch==2){
//printing from set as above part in if
}else{
System.out.println("Invalid Choice");
}
}
}
You need to override toString() method in your Doctor class:
class Doctor{
...
#Override
public String toString() {
return name+speciality+experience;
}
}
Right now I am working on a programming project in school, I am using Java Eclipse. I am still learning the basics, as I am a Sophomore in high school.
My project relates to the old game called "20 Questions".
My main trouble right now is making the user's answer result with a different question. I have tried and "if else" statement, which took me far, but not far enough. Example:
print ("Is your animal furry?");
if (answer is "True") print("Does this animal wag its tail when excited?")
//This can only be a dog
else print("Is it known to lick itself clean?")
//Else meaning if it doesn't wag its tail, go to cat questions
//only cat in this program
So my predicament is getting the user's answer to change the programs next answer.
Then if the answer they give to the furry animal is false, how do I make it go to the non hairy animal questions?
When you create a Java game, or any Java application with a GUI, using the model / view / controller pattern helps separate your concerns and makes it a lot easier to code.
What you're missing is a model. Here's one way you could model the 20 questions game.
Question.java
Here's a class that holds the question string and two pointers. One pointer for the true answer, and one pointer for the false answer.
package com.ggl.twenty.questions;
public class Question {
private int falseQuestion;
private int trueQuestion;
private String question;
public Question(String question) {
this.question = question;
}
public int getFalseQuestion() {
return falseQuestion;
}
public void setFalseQuestion(int falseQuestion) {
this.falseQuestion = falseQuestion;
}
public int getTrueQuestion() {
return trueQuestion;
}
public void setTrueQuestion(int trueQuestion) {
this.trueQuestion = trueQuestion;
}
public String getQuestion() {
return question;
}
}
TwentyQuestionsModel.java
Next, we create a model class for the game. This class creates and uses a List of questions. From any question, you can get the next question by performing the getTrueQuestion or getFalseQuestion method.
package com.ggl.twenty.questions;
import java.util.ArrayList;
import java.util.List;
public class TwentyQuestionsModel {
private int questionIndex;
private List<Question> questions;
public TwentyQuestionsModel() {
this.questions = new ArrayList<Question>();
this.questionIndex = 0;
loadQuestions();
}
private void loadQuestions() {
Question q0 = new Question("Is it a vegetable?");
this.questions.add(q0);
Question q1 = new Question("Is it a mineral?");
this.questions.add(q1);
Question q2 = new Question("Is it a mammal?");
this.questions.add(q2);
// ...
q0.setFalseQuestion(1);
q0.setTrueQuestion(3);
// ...
}
public String getTrueQuestion() {
Question q = questions.get(questionIndex);
this.questionIndex = q.getTrueQuestion();
return questions.get(questionIndex).getQuestion();
}
public String getFalseQuestion() {
Question q = questions.get(questionIndex);
this.questionIndex = q.getFalseQuestion();
return questions.get(questionIndex).getQuestion();
}
public String getFirstQuestion() {
return questions.get(questionIndex).getQuestion();
}
}
You still have to code a view and a controller. The right model makes it much easier, as you can separate your concerns.
Here my solution just with a question class:
import java.util.Scanner;
public class Question {
private String message = null;
private boolean answered = false;
private Question yes = null;
private Question no = null;
public Question(String message)
{
this.message = message;
}
public void setAnswered(boolean answered)
{
this.answered = answered;
}
public boolean getAnswered()
{
return this.answered;
}
public void setYes(Question yes)
{
this.yes = yes;
}
public void setNo(Question no)
{
this.no = no;
}
public Question getYes()
{
return this.yes;
}
public Question getNo()
{
return this.no;
}
public String getMessage()
{
return this.message;
}
public static void runQuestionnaire(Question startQuestion)
{
String yes = "y";
System.out.println("Some questions. Type 'y' for yes and 'n' for no\nand press enter.");
Scanner sc = new Scanner(System.in);
String answer = null;
Question current = startQuestion;
boolean answered = false;
do
{
System.out.println(current.getMessage());
answer = sc.next();
if(answer.equals(yes))
{
current = current.getYes();
}
else
{
current = current.getNo();
}
answered = current.getAnswered();
}
while(!answered);
System.out.println(current.getMessage());
sc.close();
}
public static void main(String[] args) {
// creating the question tree
Question startQuestion = new Question("Is it fury?");
Question yes1 = new Question("Has it 4 legs?");
Question no1 = new Question("It is a human beeing.");
no1.setAnswered(true);
startQuestion.setYes(yes1);
startQuestion.setNo(no1);
Question yes11 = new Question("Is it blue?");
Question yes111 = new Question("It is a whale.");
yes111.setAnswered(true);
Question no111 = new Question("It is a bear.");
no111.setAnswered(true);
yes1.setYes(yes11);
Question no11 = new Question("It is a bird.");
no11.setAnswered(true);
yes1.setNo(no11);
yes11.setYes(yes111);
yes11.setNo(no111);
Question.runQuestionnaire(startQuestion);
}
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 have a variable that contains a return value.
Value:
Team ID:
111111
Founded:
Feb 13, 2014 By USER
Dispute Percentage:" 0%
Reputation: -
What I am looking to keep is stickly (11111) and save it back to the value teamID. How can I manipulate the return string to only store that value and delete the rest.
If I understand what you want, you can do something like this
String value = "Team ID:\n" + "19288568\n"
+ "Founded:\n" + "Feb 13, 2014 By MLGQA\n"
+ "\n" + "Dispute Percentage: 0%\n"
+ "Reputation: -\n";
System.out.println(value.split("\n")[1]);
Outputs
19288568
Since your returned String seems somewhat complex to me, I would suggest returning a custom object (a bean) containing the information you want, each with its own field.
By doing that, you will have a quick access to any of the fields you want, by simply calling the appropriate getter method on the returned object.
For example:
public class MyContainer {
private int teamID;
private String foundationDate;
private String foundator;
private int disputePercentage;
private int reputation;
public MyContainer() {
// Constructor code.
}
public int getTeamID() {
return teamID;
}
public void setTeamID(int teamID) {
this.teamID = teamID;
}
public String getFoundationDate() {
return foundationDate;
}
public void setFoundationDate(String foundationDate) {
this.foundationDate = foundationDate;
}
public String getFoundator() {
return foundator;
}
public void setFoundator(String foundator) {
this.foundator = foundator;
}
public int getDisputePercentage() {
return disputePercentage;
}
public void setDisputePercentage(int disputePercentage) {
this.disputePercentage = disputePercentage;
}
public int getReputation() {
return reputation;
}
public void setReputation(int reputation) {
this.reputation = reputation;
}
}
And your original returning method would look to something like this:
public MyContainer returningMethod(Object args) {
// Your code.
MyContainer bean = new MyContainer();
// Fill the container.
return bean;
}
I do not know the exact types of data you use, so feel free to adjust this example for your needs!
So, just as an example, let's say we have an abstract class called Question, that question contains a lot of strings, one for the question itself, one for the answer and two responses posted to the user, if he got the question right / wrong.
public abstract class Question {
private final String question;
private final String answer;
private final String answerCorrect;
private final String answerWrong;
}
My question basically is, what would be a common way to initialize all of the strings? So far I've made up 2 versions on how to do it, they have their up- and downsides and I wanted to know, if there was some kind of "best coding practice" for this.
Version A
Initialize everything in the constructor.
public abstract class Question {
//...
public Question(String question, String answer, String answerCorrect, String answerWrong) {
this.question = question;
this.answer = answer;
this.answerCorrect = answerCorrect;
this.answerWrong = answerWrong;
}
}
This seems pretty convenient, the only problem I have with this is that users will not be sure, in which order the strings have to be.
public class ExampleClass extends Question {
public ExampleClass() {
super("I think, that's the answer", "and that's the question", "answer wrong?", "answer right?");
}
}
Version B
Don't initialize instantly and wait for the user to do it.
public abstract class Question {
//...
public Question() {
this.question = "";
this.answer = "";
this.answerCorrect = "";
this.answerWrong = "";
}
public void setQuestion(String question) {
this.question = question;
}
//...
}
This makes it easier to initialize variables, but the Strings can't be final anymore and it's not guaranteed that the user will initialize all of them.
I've also thought about letting the child-class implement abstract methods that are called in the constructor of Question to initialize all the strings and to keep them final, but that version seemed a little too strange to me.
Are there other / better ways to do it? What version should I prefer?
Thanks in advance for your support.
Version A is the way to go. You're right, though, if you do not tell your users (the other developers I'm assuming) which parameter is which, there is no way for them to know where to type what.
This is where Javadoc comes in handy.
Here's an example:
/**
* Create a new instance of Question given the following parameters:
*
* #param question This is the question
* #param answer This is the answer
* #param answerCorrect Whenever someone guesses correct, print this
* #param answerWrong Whenever someone guesses wrong, print this
*/
public Question(String question, String answer, String answerCorrect, String answerWrong) {
this.question = question;
this.answer = answer;
this.answerCorrect = answerCorrect;
this.answerWrong = answerWrong;
}
This might be overkill, but I believe you could use a builder here...
public class Question
{
private final String question;
private final String answer;
private final String answerCorrect;
private final String answerWrong;
Question(QuestionBuilder builder) {
this.question = builder.question;
this.answer = builder.answer;
this.answerCorrect = builder.answerCorrect;
this.answerWrong = builder.answerWrong;
}
// public getters omitted to shorten answer
#Override
public String toString(){
return String.format("question: '%s', answer: '%s', answerCorrect: '%s', answerWrong: '%s'", question, answer, answerCorrect, answerWrong);
}
public static void main(String[] args) {
QuestionBuilder qb = new QuestionBuilder();
qb = qb.question("This is the question").answer("This is the answer").answerCorrect("Correct answer").answerWrong("Wrong Answer");
Question question = new Question(qb);
System.out.println(question);
}
public static class QuestionBuilder{
private String question;
private String answer;
private String answerCorrect;
private String answerWrong;
public QuestionBuilder question(String question) {
this.question = question;
return this;
}
public QuestionBuilder answer(String answer) {
this.answer = answer;
return this;
}
public QuestionBuilder answerCorrect(String answerCorrect) {
this.answerCorrect = answerCorrect;
return this;
}
public QuestionBuilder answerWrong(String answerWrong) {
this.answerWrong = answerWrong;
return this;
}
}
}
Gives the output
question: 'This is the question', answer: 'This is the answer', answerCorrect: 'Correct answer', answerWrong: 'Wrong Answer'
Note: I realize the original question was in reference to an abstract class. I used a concrete class so I could give a working example, although the solution can be adapted for use with an abstract class.
Instead of thinking of the attributes (such as question) as just variables, think of the restrictions on their values that must be obeyed for the classes to behave correctly. Can they be null? Can they be empty? Now design your methods and the constructor so it is impossible for those restrictions to be broken. You might find that the only way you can do this is to set initial values in the constructor (your version A). You might have to add pre-condition checks to your constructor and setter methods, which check the values given a throw a suitable exception (NullPointerException or IllegalArgumentException) if the values passed to them would result in the restrictions being broken.
Also, consider whether it really makes sense to change the value of an attribute after the object is constructed. If not, then the attribute should not a setter, making your version B impossible.