Harry Potter Which Character Are You Quiz.
So I want to take each option, and the character(s) associated with each option (below the options is each character(s) separated by a comma ex. 1.Acid Pops Neville Longbottom, 3. Bertie Bott's Every Flavour Beans Luna Lovegood Nymphadora Tonks....I want to send the option, character(s) in the main method and send it as a String to the Question class and store it in an Arraylist of type Answer not String. And in the Answer class will be passed only what the user selects so for ex. 2. Sherbert Lemons and Albus Dumbledore.
String[] questions =
{
"Favourite sweet",
};
String [][] options =
{
{"1.Acid Pops","2.Sherbert Lemons","3.Bertie Bott's Every Flavour Beans",
"4.Cake","5.Hagrid's Rock Cakes","6.Chocolate Frogs","7.Ginger Newt",
"8.I hate sweets\n"},
{"Neville Longbottom","Albus Dumbledore", "Luna Lovegood, Nymphadora
Tonks", "Dobby, Arthur Weasley", "Rubeus Hagrid",
"Harry Potter, Ron Weasley", "Minerva McGonagall, Hermione Granger,
Dolores Umbridge, Sybill Trelawney",
"Severus Snape, Tom Riddle, Sirius Black, Bellatrix Lestrange, Draco
Malfoy, Lucius Malfoy"}
};
Here is my for loop in my main method:
for (int i =0; i < questions.length; i ++){
String aQuestion = questions[i];
Question q = new Question(aQuestion);
System.out.println(aQuestion);
for(int j=0; j < options[i].length; j++){
q.setAnswers(options[i][j], options[i+1][j]);
System.out.println(options[i][j]);
}
}
Here's my Question class:
private String question;
public ArrayList<Answer> answers = new ArrayList<Answer>();
public Question(String q){
question = q;
}
public void setAnswers(String options, String options2){
answers.add(options);
answers.add(options2);
}
Sorry if this doesn't make sense.
I also don't understand why you have an arraylist of type: Answer that matches a class name you have in your program. If that also makes sense.
Here is the problem, You cannot add anything(any other object) to your List<Answer> except for Answer objects.
See the following lines Line 1 and Line 2
public void setAnswers(String options, String options2){
answers.add(options); //LINE 1
answers.add(options2); //LINE 2
}
Now, I am not really sure how your Answer really looks like. But if it has got something to do with the options. It can have the following constructor in Answer class
Answer(String option){
this.option = option;
}
And you can modify your code to look something like this
public void setAnswers(String options, String options2){
answers.add(new Answer(options)); //LINE 1
answers.add(new Answer(options)); //LINE 2
}
I also don't understand why you have an arraylist of type
Collections in java were made typed to avoid accidental addition of wrong object to it. You can very well omit the type from the declaration but that is not recommended.
As an alternative solution you can either:
Change the type of ArrayList<Answer> answers to more generic one like Serializable or,
Wrap String options1 and options2 and convert them into Answer type and then add them to list.
I'll prefer second option.
Convert: Create a method in Answer class which return Answer object, you can make it static
public static Answer getAnswerFromString(String answer) {
// Logic to create Answer object from string
}
Then modify this method as below to add answer to the list:
public void setAnswers(String options, String options2){
answers.add(Answer.getAnswerFromString(options));
answers.add(Answer.getAnswerFromString(options2));
}
Or you can add a constructer with String parameter if it make sense as pointed in other answer.
Related
This question already has answers here:
To use a string value as a variable name [duplicate]
(5 answers)
Closed 2 years ago.
I was just simplifying my code and I ran into a small problem which I can't solve.
So I have an activity which has a getter like so:
private String[][] Example001 ={{"String1","String2"},{"Light","Normal","Heavy"}};
public String getExerciseValue(String variableName ,int codeOrValue,int type){
switch (variableName){
case "Example001":
return Example001[codeOrValue][type];
case "Example999"
return Example999[codeOrValue][type];
}
return "default";
}
so instead of having numerous number of cases, I would rather simplify the code by something like this
public String getExerciseValue(String variableName ,int codeOrValue,int type){
return variableName[codeOrValue][type];
}
I ask for an example of working code work this case coz I have no idea how to figure this out. Thanks for any suggestions :)
This is not possible in Java. However, it is also not necessary.
Whenever you have series of numbered variable names, that's actually just a very cumbersome way of implementing an array:
private String[][][] examples = {
{
{ "String1", "String2" },
{ "Light", "Normal", "Heavy" }
}
};
public String getExerciseValue(int exampleNumber, int codeOrValue, int type) {
return examples[exampleNumber - 1][codeOrValue][type];
}
Suggest you to use HashMap, and put each array as a value with your preferred name in it. Something like it:
Map<String, String[][]> examples = new HashMap<>();
examples.put("Example001", Example001);
You can then easily retrieve your element with its names and indexes as you needed.
examples.get("Example001")[codeOrValue][type]
my professor gave me an exercise to find how many time the characters of string called "filter" are to be found in a second string called "query".
before I begin I am java noob and English isnt my native language.
example:
String filter="kjasd";
String query="kjg4t";
Output:2
getting how many times a char has been found in another string isnt my problem but the problem that the professor gave us some rules to stick with:
class filter. The class must be the following public
Provide interfaces:
public Filter (String letters) (→ Constructor of class)
The string representing the filter should be stored in the letters string
public boolean contains (char character)
Returns true if the passed character is contained in the query string, otherwise false
-public String toString ()
Returns an appropriate string representation of the class (just to be clear I have no clue about what does he means with this one!)
To actually determine the occurrences of the filter in the query, another class QueryResolver is to be created.
The class should be able to be used as follows:
QueryResolver resolver = new QueryResolver();
int count = resolver.where(query).matches(filter).count();
the filter and the query are given by the user.
(i couldnt understand this one! )The methods "where" and "matches" configure the "QueryResolver" to include a subsequent call of "count" the calculation based on the previously passed variables
"query" and "filter" performs.
The count method should use the filter's previously-created method.
The modifier static is not allowed to use!
I dunno if he means that we cant use static {} or we cant use public (static) boolean contains (char character){}
we are not allowed to use void
so the problems that encountered me
- I can not pass a char to the method contains as long as it is not static.
error "Non-static variable can not be referenced from a static context"
i did not understand what i should do with the method toStirng!
what I've done so far:
Approach Nr 1:
so I just wrote everything in the main method to check whether the principle of my code works or not and then I wanted to create that whole with constructor and other methods but unfortunately I did not succeed.
Approach Nr 2:
then I tried to write the code in small mthoden as in the exercise but I did not succeed !.
in both aprroaches i violated the exercise rules but i cant seem to be able to do it alone thats why i posted the question here.
FIRST APPROACH:
public class filter{
public filter(String letters) {
//constructor of the class
String filter;
int count;
}
public boolean contains (char character){
/*Subprogram without static!
*the problem that I can't pass any char to this method if it wasn't static
*and I will get the following error"Non-static variable cannot be referenced from a static context"
*I understand why I'm getting the error but I don't know how to get around it X( */
return true ;
}
public String toString (){
/*he told us to include it in the program but honestly, I don't know what shall I write in it -_-
*I make it to null because you have to return something and I don't know what to do yet
*so, for now, I let it null. */
return null;
}
public static void main(String[] args) {
Scanner in =new Scanner (System.in);
System.out.println("please enter the query string! ");
String query= in.next();
System.out.println("please enter the filter stirng!");
String filter= in.next();
System.out.println("the query string is : [" + query+ "]");
System.out.println("the filter string is : [" + filter+ "]");
int count=0;
// I initialized it temporarily because I wanted to print it!
//later I need to use it with the boolean contains as a public method
boolean contains=false;
//to convert each the query and the filter strings to chars
char [] tempArray=query.toCharArray();
char [] tempArray1=filter.toCharArray();
//to iterate for each char in the query string!
for (int i = 0; i < tempArray.length; i++) {
char cc = tempArray[i];
//to iterate for each char in the filter string!
for (int j = 0; j < tempArray1.length; j++) {
// if the value in the filter string matches the value in the temp array then increment the counter by one!
if(tempArray1[j] == cc){
count++;
contains=true;
}
}
}
System.out.println("the characters of the String ["+filter+"] has been found in the forworded string ["+query+"] exactly "+count+" times!" );
System.out.println("the boolean value : "+ contains);
in.close();
}
}
SECOND APPROACH
- But here too I violated the rules of the task quite brutally :(
- First, I used void and did not use the tostring method.
- Second, I did not use a constructor.
- I did not add comments because that's just the same principal as my first attempt.
public class filter2 {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("enter the filter string:");
String filterStr=in.next();
System.out.println("enter the query string:");
String querystr =in.next();
Filter(filterStr, querystr);
in.close();
}
public static void Filter(String filterstr , String querystr){
char [] tempArray1 = filterstr.toCharArray();
contains(tempArray1, querystr);
}
public static void contains(char[]tempArray1, String querystr){
boolean isThere= false ;
int counter=0;
char [] tempArray = querystr.toCharArray();
for (int i = 0; i < tempArray.length; i++) {
char cc = tempArray[i];
for (int j = 0; j < tempArray1.length; j++) {
if(tempArray1[j] == cc){
counter++;
isThere=true;
}
}
}
System.out.println("the letters of the filter string has been found in the query string exactly "+counter+" times!\nthus the boolean value is "+isThere);
}
/*
* sadly enough i still have no clue what is meant with this one nor whatshall i do
* public String toString (){
* return null;
* }
*
*/
}
Few hints and advice would be very useful to me but please demonstrate your suggestions in code because sometimes it can be difficult for me to understand what you mean by the given advice. ;)
Thank you in advance.
(sorry for the gramatical and the type mistakes; english is not my native language)
As already mentioned, it is important to learn to solve those problems yourself. The homework is not for punishment, but to teach you how to learn new stuff on your own, which is an important trait of a computer scientist.
Nonetheless, because it seems like you really made some effort to solve it yourself already, here is my solution, followed by some explanation.
General concepts
The first thing that I feel like you didn't understand is the concept of classes and objects. A class is like a 'blueprint' of an object, and the object is once you instanciated it.
Compared with something like a car, the class would be the description how to build a car, and the object would be a car.
You describe what a class is with public class Car { ... }, and instanciate an object of it with Car myCar = new Car();.
A class can have methods(=functions) and member variables(=data).
I just repeat those concepts because the code that you wrote looks like you didn't fully understand that concept yet. Please ask some other student who understood it to help you with that.
The Filter class
public class Filter{
String letters;
public Filter(String letters) {
this.letters = letters;
}
public boolean contains (char character){
for(int i = 0; i < letters.length(); i++) {
if(letters.charAt(i) == character)
return true;
}
return false;
}
public String toString (){
return "Filter(" + letters + ")";
}
}
Ok, let's brake that down.
public class Filter{
...
}
I guess you already got that part. This is where you describe your class structure.
String letters;
This is a class member variable. It is unique for every object that you create of that class. Again, for details, ask other students that understood it.
public Filter(String letters) {
this.letters = letters;
}
This is the constructor. When you create your object, this is the function that gets called.
In this case, all it does is to take an argument letters and stores it in the class-variable letters. Because they have the same name, you need to explicitely tell java that the left one is the class variable. You do this by adding this..
public boolean contains (char character){
for(int i = 0; i < letters.length(); i++) {
if(letters.charAt(i) == character)
return true;
}
return false;
}
This takes a character and looks whether it is contained in this.letters or not.
Because there is no name collision here, you can ommit the this..
If I understood right, the missing static here was one of your problems. If you have static, the function is class-bound and not object-bound, meaning you can call it without having an object. Again, it is important that you understand the difference, and if you don't, ask someone. (To be precise, ask the difference between class, object, static and non-static) It would take too long to explain that in detail here.
But in a nutshell, if the function is not static, it needs to be called on an object to work. Look further down in the other class for details how that looks like.
public String toString (){
return "Filter(" + letters + ")";
}
This function is also non-static. It is used whenever the object needs to be converted to a String, like in a System.out.println() call. Again, it is important here that you understand the difference between class and object.
The QueryResolver class
public class QueryResolver {
Filter filter;
String query;
public QueryResolver where(String queryStr) {
this.query = queryStr;
return this;
}
public QueryResolver matches(String filterStr) {
this.filter = new Filter(filterStr);
return this;
}
public int count() {
int result = 0;
for(int i = 0; i < query.length(); i++) {
if(filter.contains(query.charAt(i))){
result++;
}
}
return result;
}
}
Again, let's break that down.
public class QueryResolver {
...
}
Our class body.
Note that we don't have a constructor here. It is advisable to have one, but in this case it would be an empty function with no arguments that does nothing, so we can just leave it and the compiler will auto-generate it.
public QueryResolver where(String queryStr) {
this.query = queryStr;
return this;
}
This is an interesting function. It returns a this pointer. Therefore you can use the result of the function to do another call, allowing you to 'chain' multiple function calls together, like resolver.where(query).matches(filter).count().
To understand how that works requires you to understand both the class-object difference and what exactly the this pointer does.
The short version is that the this pointer is the pointer to the object that our function currently lives in.
public QueryResolver matches(String filterStr) {
this.filter = new Filter(filterStr);
return this;
}
This is almost the same as the where function.
The interesting part is the new Filter(...). This creates the previously discussed Filter-object from the class description and puts it in the QueryResolver object's this.filter variable.
public int count() {
int result = 0;
for(int i = 0; i < query.length(); i++) {
if(filter.contains(query.charAt(i))){
result++;
}
}
return result;
}
Iterates through the object's query variable and checks for every letter if it is contained in filter. It keeps count of how many times this happens and returns the count.
This function requires that filter and query are set. Therefore it is important that before someone calls count(), they previously call where(..) and matches(..).
In our case, all of that happens in one line, resolver.where(query).matches(filter).count().
The main function
I wrote two different main functions. You want to test your code as much as possible during development, therefore the first one I wrote was a fixed one, where you don't have to enter something manually, just click run and it works:
public static void main(String[] args) {
String filter="kjasd";
String query="kjg4t";
QueryResolver resolver = new QueryResolver();
int count = resolver.where(query).matches(filter).count();
System.out.println(count);
}
Once you understand the class-object difference, this should be straight forward.
But to repeat:
QueryResolver resolver = new QueryResolver();
This creates your QueryResolver object and stores it in the variable resolver.
int count = resolver.where(query).matches(filter).count();
Then, this line uses the resolver object to first call where, matches, and finally count. Again, this chaining only works because we return this in the where and matches functions.
Now finally the interactive version that you created:
public static void main(String[] args) {
Scanner in =new Scanner(System.in);
System.out.println("please enter the query string! ");
String query= in.next();
System.out.println("please enter the filter stirng!");
String filter= in.next();
System.out.println("the query string is : [" + query+ "]");
System.out.println("the filter string is : [" + filter+ "]");
QueryResolver resolver = new QueryResolver();
int count = resolver.where(query).matches(filter).count();
System.out.println("the characters of the String ["+filter+"] has been found in the forworded string ["+query+"] exactly "+count+" times!" );
in.close();
}
I have a long piece of code that looks like this
Kwas a1 = new Kwas("Kwas Azotowy(V)", "HNO3");
// etc..
Kwas a17 = new Kwas("Kwas FluorkoWodorowy", "HF");
How can I write it as an Array? I tried something like
Kwas[] a = new Kwas[17]
But it didn`t work.
My "Kwas" class looks like the following:
public class Kwas {
String name;
String formula;
public Kwas( String nazwa, String wzor)
{
name = nazwa;
formula = wzor;
}
void setName(String c)
{
name = c;
}
void setFormula(String c)
{
formula = c;
}
public String getName()
{
return name;
}
public String getFormula() {return formula;}
}
You can do this:
List<Kwas> list = new ArrayList<Kwas>();
list.add(a2);
Just implement an ArrayList like this:
ArrayList<Kwas> newArray= new ArrayList<>();
And then:
newArray.add(a2);
newArray.add(a3);
newArray.add(a4);
newArray.add(a5);
newArray.add(a6);
newArray.add(a7);
...
...
Then if you want to get an specific item just write something like this:
newArray.get(1).getName(); //for example
I can't comment yet, so I have to provide it as an answer. Everyone is answering here how OP can construct a List, but no one is actually answering how he can create an array, which is probably very confusing for OP who might now think you can't create arrays of self-defined objects. You definitely can. But I don't know what the problem is.
Kwas[] a1 = new Kwas[17];
is definitely the right syntax. Are you sure you include the class? Can you post the exact code and error?
My guess is that you didn't import your class. In Android Studio, try placing your cursor after Kwas and pressing Ctrl+Space. This should show a dropdown list. Select the first line and press enter. Now it should have added an import to your class.
ArrayList<yourObjectName> arrayName = new ArrayList<yourObjectName>();
Then .add(object) on every object
You can simply type:
ArrayList<ObjectType> arrayName = new ArrayList<ObjectType>();
Adding Elements:
arrayName.add(someObject);
Removing Elements:
arrayName.remove(arrayName.get(someInteger));
Getting Elements:
arrayName.get(someInteger);
PS: Don't forget to import:
import java.util.ArrayList;
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Creating a quiz for a school project, and it would make the code a lot easier if there was a way to have a question and 4 possible answers in one element of an array, with the question and the 4 possible answers being on their own line.
If you create a String[] (an array of String objects) then each element within that array can contain any valid Java String, which includes a String containing newline \n characters. So you could have make each array element a multi-line string, each line separated by the \n character, so that the question is found before the first \n, the correct answer is found before the second \n, and the incorrect answers are found in subsequent "lines".
However, I'd say this actually makes the code more cryptic and thus difficult to follow. A better, object-oriented approach is to create a new class which represents a quiz question and its answers. The outline of this class might look something like this:
class QuizQuestion {
String questionText;
String correctAnswer;
List<String> incorrectAnswers;
}
You could leave this class exactly like this, and simply refer to its class fields (from within the same code package), thus creating a new object type which bundles the question text and answers together nicely. Or, if needed, you could add methods to this class, to control/protect the way the class field data is accessed/modified.
Now instead of working with your original String[] you could work with a List<QuizQuestion> or a QuizQuestion[]. This should make the code easier to read, and easier to enhance in future.
Although all the answers above are valid implementations to your question, I'd rather go with an object-oriented approach as JB Nizet stated in the comments above. Here is a sample program that implements a quiz and shows an object-oriented implementation. Please don't copy it 1:1 as a solution to your homework. It should rather provide with some examples of what you can do with Java or any other object oriented language...
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* Quiz is a "wrapper class" for your whole project.
* It contains a set of questions and some helper methods
* to create the questions and proper answers.
*/
public class Quiz {
/**
* We use a list to store our questions.
* Each question is an object of type "Question"
*/
List<Question> questions = new ArrayList<>();
/**
* The entry point for our program.
* Java will run this method, if our code is "started".
*
* All it does is
*
* 1. Create a new quiz
* 2. Start the quiz with the 'play' method
*/
public static void main(String[] args) {
Quiz quiz = Quiz.create();
quiz.play();
}
/**
* Helper method to create a quiz.
* You can add as many questions as you like with as many answers
* as you like.
* The second parameter indicates the index of the answer
* that is the expected answer (starting with 1, not with 0).
*/
public static Quiz create() {
Quiz quiz = new Quiz();
quiz.addQuestion(
"What is the heaviest animal on earth?",
3,
"Elephant",
"Cow",
"Whale",
"Crocodile"
);
quiz.addQuestion(
"What is the biggest planet in the solar system?",
2,
"Mars",
"Jupiter",
"Earth",
"Saturn"
);
return quiz;
}
/**
* Helper method that actually starts our quiz.
*
* There is a lot of room for improvement here - I just wanted
* to give you a brief example
* of how you can use the code here to play the quiz. Feel free to change :)
*/
public void play() {
for (Question q : questions) {
System.out.println(q.getQuestion());
int i = 1;
for (Answer a : q.getAnswers()) {
System.out.println(i++ + ". " + a.getAnswer());
}
System.out.printf("Please tell me the correct answer: ");
Scanner in = new Scanner(System.in);
String givenAnswer = in.next();
if (q.getExpectedAnswer() == Integer.parseInt(givenAnswer)) {
System.out.printf("Brilliant - your answer was correct!");
} else {
System.out.println("Ooops - that was wrong. The expected answer was: " + q.getProperAnswer());
}
}
}
/**
* Helper method that adds a question to the quiz.
*
* First parameter is the question itself.
* Second parameter is the index of the correct answer
* in the answers given in the third parameter.
* Mind that the index starts with 1 not with 0 as arrays do in Java.
* Third parameter is a variable length parameter:
* this enables you to add as many answers as you want.
*/
private void addQuestion(String questionText, int expectedAnswer, String... answers) {
Question question = new Question(questionText);
for (String answerText : answers) {
question.addAnswer(new Answer(answerText));
}
question.setExpectedAnswer(expectedAnswer);
this.questions.add(question);
}
/**
* Class that implements a question.
*
* A question consists of the text for the question itself,
* the index of the expected answer (starting with 1!) and
* an ordered list of answers.
*/
public class Question {
private String question;
private int expectedAnswer;
private List<Answer> answers = new ArrayList<>();
public Question(String question) {
this.question = question;
}
public void addAnswer(Answer answer) {
answers.add(answer);
}
public void setExpectedAnswer(int expectedAnswer) {
this.expectedAnswer = expectedAnswer;
}
public int getExpectedAnswer() {
return expectedAnswer;
}
public String getQuestion() {
return question;
}
public List<Answer> getAnswers() {
return answers;
}
public String getProperAnswer() {
return answers.get(expectedAnswer - 1).getAnswer();
}
}
/**
* The answer itself is again a class.
*
* This is a little over-engineered, it might as well be a string.
* Implementing it as a separate class enables you to add further
* information - e.g. a scoring for the wrong / right answer...
*/
private class Answer {
private String answer;
public Answer(String answer) {
this.answer = answer;
}
public String getAnswer() {
return answer;
}
}
}
If you have any questions regarding the implementation feel free to ask me in the comments. Happy Coding!
You could just place a line separator inside your string. To make sure the program performs well on any platform, you should use the %n formatter and printf your string:
String[] questions = new String[] {
// Question #1 with its answers
"What is your name?%n" +
"%n" +
"1. Stack%n" +
"2. Overflow%n" +
"3. John%n" +
"4. Doe%n"
// More questions here..
};
for (String question : questions) {
System.out.printf(question);
}
Basically, all you need to do is adding a seperation character in your string and evaluate it on displaying the question.
String question = "Question\0First Answer\0Second Answer\n with Linebreak\0Third Answer";
To seperate use split():
String[] questionAndAnswers = question.split("\0");
But this is not how this is supposed to work. You should create a Question object that has properties for questions and possible answers. Then build an array of Question objects instead of String.
public class Question {
private String question;
private String[] answers;
private int correct;
// have getters and setters here
}
This question already has answers here:
Randomly select an item from a list
(5 answers)
Closed 4 years ago.
I'm learning Java and I'm having a problem with ArrayList and Random.
I have an object called catalogue which has an array list of objects created from another class called item.
I need a method in catalogue which returns all the information on one of the itemobjects in the list.
The item needs to be selected at random.
import java.util.ArrayList;
import java.util.Random;
public class Catalogue
{
private Random randomGenerator = new Random();
private ArrayList<Item> catalogue;
public Catalogue ()
{
catalogue = new ArrayList<Item>();
}
public Item anyItem()
{
int index = randomGenerator.nextInt(catalogue.size());
System.out.println("Managers choice this week" + catalogue.get(index) + "our recommendation to you");
return catalogue.get(index);
}
When I try to compile I get an error pointing at the System.out.println line saying..
'cannot find symbol variable anyItem'
anyItem is a method and the System.out.println call is after your return statement so that won't compile anyway since it is unreachable.
Might want to re-write it like:
import java.util.ArrayList;
import java.util.Random;
public class Catalogue
{
private Random randomGenerator;
private ArrayList<Item> catalogue;
public Catalogue()
{
catalogue = new ArrayList<Item>();
randomGenerator = new Random();
}
public Item anyItem()
{
int index = randomGenerator.nextInt(catalogue.size());
Item item = catalogue.get(index);
System.out.println("Managers choice this week" + item + "our recommendation to you");
return item;
}
}
public static Item getRandomChestItem(List<Item> items) {
return items.get(new Random().nextInt(items.size()));
}
your print comes after you return -- you can never reach that statement. Also, you never declared anyItem to be a variable. You might want
public Item anyItem()
{
int index = randomGenerator.nextInt(catalogue.size());
Item randomItem = catalogue.get(index);
System.out.println("Managers choice this week" + randomItem.toString() + "our recommendation to you");
return randomItem;
}
The toString part is just a quickie -- you might want to add a method 'getItemDescription' that returns a useful String for this purpose...
Here you go, using Generics:
private <T> T getRandomItem(List<T> list)
{
Random random = new Random();
int listSize = list.size();
int randomIndex = random.nextInt(listSize);
return list.get(randomIndex);
}
You must remove the system.out.println message from below the return, like this:
public Item anyItem()
{
randomGenerator = new Random();
int index = randomGenerator.nextInt(catalogue.size());
Item it = catalogue.get(index);
System.out.println("Managers choice this week" + it + "our recommendation to you");
return it;
}
the return statement basically says the function will now end. anything included beyond the return statement that is also in scope of it will result in the behavior you experienced
try this
public Item anyItem()
{
int index = randomGenerator.nextInt(catalogue.size());
System.out.println("Managers choice this week" + catalogue.get(index) + "our recommendation to you");
return catalogue.get(index);
}
And I strongly suggest you to get a book, such as Ivor Horton's Beginning Java 2
anyItem has never been declared as a variable, so it makes sense that it causes an error. But more importantly, you have code after a return statement and this will cause an unreachable code error.
System.out.println("Managers choice this week" + anyItem + "our recommendation to you");
You havent the variable anyItem initialized or even declared.
This code:
+ anyItem +
means get value of toString method of Object anyItem
The second thing why this wont work. You have System.out.print after return statement. Program could never reach tha line.
You probably want something like:
public Item anyItem() {
int index = randomGenerator.nextInt(catalogue.size());
System.out.println("Managers choice this week" + catalogue.get(index) + "our recommendation to you");
return catalogue.get(index);
}
btw: in Java its convetion to place the curly parenthesis on the same line as the declaration of the function.
As I can see the code
System.out.println("Managers choice this week" + anyItem + "our recommendation to you");
is unreachable.
See https://gist.github.com/nathanosoares/6234e9b06608595e018ca56c7b3d5a57
public static void main(String[] args) {
RandomList<String> set = new RandomList<>();
set.add("a", 10);
set.add("b", 10);
set.add("c", 30);
set.add("d", 300);
set.forEach((t) -> {
System.out.println(t.getChance());
});
HashMap<String, Integer> count = new HashMap<>();
IntStream.range(0, 100).forEach((value) -> {
String str = set.raffle();
count.put(str, count.getOrDefault(str, 0) + 1);
});
count.entrySet().stream().forEach(entry -> {
System.out.println(String.format("%s: %s", entry.getKey(), entry.getValue()));
});
}
Output:
2.857142857142857
2.857142857142857
8.571428571428571
85.71428571428571
a: 2
b: 1
c: 9
d: 88
The solution is not good, even you fixed your naming and unreachable statement of that print out.
things you should pay attention also
1. randomness seed, and large data, will num of item is so big returned num of that random < itemlist.size().
you didn't handle multithread, you might get index out of bound exception
Here's a better way of doing things:
import java.util.ArrayList;
import java.util.Random;
public class facultyquotes
{
private ArrayList<String> quotes;
private String quote1;
private String quote2;
private String quote3;
private String quote4;
private String quote5;
private String quote6;
private String quote7;
private String quote8;
private String quote9;
private String quote10;
private String quote11;
private String quote12;
private String quote13;
private String quote14;
private String quote15;
private String quote16;
private String quote17;
private String quote18;
private String quote19;
private String quote20;
private String quote21;
private String quote22;
private String quote23;
private String quote24;
private String quote25;
private String quote26;
private String quote27;
private String quote28;
private String quote29;
private String quote30;
private int n;
Random random;
String teacher;
facultyquotes()
{
quotes=new ArrayList<>();
random=new Random();
n=random.nextInt(3) + 0;
quote1="life is hard";
quote2="trouble shall come to an end";
quote3="never give lose and never get lose";
quote4="gamble with the devil and win";
quote5="If you don’t build your dream, someone else will hire you to help them build theirs.";
quote6="The first step toward success is taken when you refuse to be a captive of the environment in which you first find yourself.";
quote7="When I dare to be powerful – to use my strength in the service of my vision, then it becomes less and less important whether I am afraid.";
quote8="Whenever you find yourself on the side of the majority, it is time to pause and reflect";
quote9="Great minds discuss ideas; average minds discuss events; small minds discuss people.";
quote10="I have not failed. I’ve just found 10,000 ways that won’t work.";
quote11="If you don’t value your time, neither will others. Stop giving away your time and talents. Value what you know & start charging for it.";
quote12="A successful man is one who can lay a firm foundation with the bricks others have thrown at him.";
quote13="No one can make you feel inferior without your consent.";
quote14="Let him who would enjoy a good future waste none of his present.";
quote15="Live as if you were to die tomorrow. Learn as if you were to live forever.";
quote16="Twenty years from now you will be more disappointed by the things that you didn’t do than by the ones you did do.";
quote17="The difference between a successful person and others is not a lack of strength, not a lack of knowledge, but rather a lack of will.";
quote18="Success is about creating benefit for all and enjoying the process. If you focus on this & adopt this definition, success is yours.";
quote19="I used to want the words ‘She tried’ on my tombstone. Now I want ‘She did it.";
quote20="It is our choices, that show what we truly are, far more than our abilities.";
quote21="You have to learn the rules of the game. And then you have to play better than anyone else.";
quote22="The successful warrior is the average man, with laser-like focus.";
quote23="Develop success from failures. Discouragement and failure are two of the surest stepping stones to success.";
quote24="If you don’t design your own life plan, chances are you’ll fall into someone else’s plan. And guess what they have planned for you? Not much.";
quote25="The question isn’t who is going to let me; it’s who is going to stop me.";
quote26="If you genuinely want something, don’t wait for it – teach yourself to be impatient.";
quote27="Don’t let the fear of losing be greater than the excitement of winning.";
quote28="But man is not made for defeat. A man can be destroyed but not defeated.";
quote29="There is nothing permanent except change.";
quote30="You cannot shake hands with a clenched fist.";
quotes.add(quote1);
quotes.add(quote2);
quotes.add(quote3);
quotes.add(quote4);
quotes.add(quote5);
quotes.add(quote6);
quotes.add(quote7);
quotes.add(quote8);
quotes.add(quote9);
quotes.add(quote10);
quotes.add(quote11);
quotes.add(quote12);
quotes.add(quote13);
quotes.add(quote14);
quotes.add(quote15);
quotes.add(quote16);
quotes.add(quote17);
quotes.add(quote18);
quotes.add(quote19);
quotes.add(quote20);
quotes.add(quote21);
quotes.add(quote22);
quotes.add(quote23);
quotes.add(quote24);
quotes.add(quote25);
quotes.add(quote26);
quotes.add(quote27);
quotes.add(quote28);
quotes.add(quote29);
quotes.add(quote30);
}
public void setTeacherandQuote(String teacher)
{
this.teacher=teacher;
}
public void printRandomQuotes()
{
System.out.println(quotes.get(n++)+" ~ "+ teacher);
}
public void printAllQuotes()
{
for (String i : quotes)
{
System.out.println(i.toString());
}
}
}