Retrieving a random item from ArrayList [duplicate] - java

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());
}
}
}

Related

How to Perform Percentage on item list Enum? [closed]

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 4 years ago.
Improve this question
I'm looking for some tip on how to do a percentage thing for my game I want all flowers in a range of 1-98 and white/black flowers 99-100 to make it more rarerity thanks for the help :)
public enum FlowerSuit {
WHITE_FLOWERS("white", ":white:", "470419377456414720", 1),
YELLOW_FLOWERS("yellow", ":yellow:", "470419561267855360", 1 ),
RED_FLOWERS("red", ":red:", "470419583250202644", 1),
RAINBOW_FLOWERS("rainbow", ":rainbow:", "470419602841665536", 1),
PASTEL_FLOWERS("pastel", ":pastel:", "470419629450199040", 1),
ORANGE_FLOWERS("orange", ":orange:", "470419647900942366", 1),
BLUE_FLOWERS("blue", ":blue:", "470419688753594368", 1),
BLACK_FLOWERS("black", ":black:", "470419706751352842", 1);
private final String displayName;
private final String emoticon;
private int value;
private final String id;
FlowerSuit(String displayName, String emoticon, String id, int value ) {
this.displayName = displayName;
this.emoticon = emoticon;
this.value = value;
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public String getEmoticon() {
return emoticon;
}
public String getId() {
return id;
}
public int getValue() {
// TODO Auto-generated method stub
return value;
}
}
This is how I'd do it, but it can probably be improved, for starters by using Java 8 streams etc.
public enum FlowerSuit {
WHITE_FLOWERS("white", ":white:", "470419377456414720", 1,3),
YELLOW_FLOWERS("yellow", ":yellow:", "470419561267855360", 1,2),
RED_FLOWERS("red", ":red:", "470419583250202644", 1,2),
RAINBOW_FLOWERS("rainbow", ":rainbow:", "470419602841665536", 1,2),
PASTEL_FLOWERS("pastel", ":pastel:", "470419629450199040", 1,2),
ORANGE_FLOWERS("orange", ":orange:", "470419647900942366", 1,2),
BLUE_FLOWERS("blue", ":blue:", "470419688753594368", 1,2),
BLACK_FLOWERS("black", ":black:", "470419706751352842", 1,1);
private static Random random = new Random();
private final String displayName;
private final String emoticon;
private int value;
private final String id;
private final int freq;
private FlowerSuit(String displayName, String emoticon, String id, int value, int freq ) {
this.displayName = displayName;
this.emoticon = emoticon;
this.value = value;
this.id = id;
this.freq = freq;
}
public String getDisplayName() {return displayName;}
public String getEmoticon() {return emoticon;}
public String getId() {return id;}
public int getValue() {return value;}
/**
* Choose a flower
* white has a 3 in 16 (about a 5:1) chance of being picked
* Black has a 1 in 16 chance, everything else 2/16
* #return
*/
public static FlowerSuit pick() {
//first sum all the chances (currently it's 16)
int sum = 0;
for (FlowerSuit f:FlowerSuit.values()) sum+= f.freq;
//now choose a random number
int r = FlowerSuit.random.nextInt(sum) + 1;
//now find out which flower to pick
sum = 0;
for (FlowerSuit f:FlowerSuit.values()) {
sum += f.freq;
if (r<=sum) return f;
}
//code will never get here
return FlowerSuit.WHITE_FLOWERS;
}
public static void main(final String[] args) throws Exception {
//Test it
Map<FlowerSuit,Integer>count = new HashMap<FlowerSuit,Integer>();
for (int a=0;a<1000000;a++) {
FlowerSuit f = FlowerSuit.pick();
Integer i = (count.get(f)!=null)?count.get(f):new Integer(0);
i = new Integer(i+1);
count.put(f,i);
}
int sum = 0;
for (Map.Entry<FlowerSuit,Integer>e:count.entrySet()) sum+=e.getValue();
float f = Float.valueOf(sum);
for (Map.Entry<FlowerSuit,Integer>e:count.entrySet()) {
System.out.println(e.getKey() + " was chosen " + ((e.getValue() / f) * 100f) + "% of the time");
}
}
}
gives
BLUE_FLOWERS was chosen 12.4986% of the time
PASTEL_FLOWERS was chosen 12.4707% of the time
WHITE_FLOWERS was chosen 18.7365% of the time
BLACK_FLOWERS was chosen 6.2632003% of the time
ORANGE_FLOWERS was chosen 12.4986% of the time
RED_FLOWERS was chosen 12.5241995% of the time
YELLOW_FLOWERS was chosen 12.501401% of the time
RAINBOW_FLOWERS was chosen 12.5068% of the time
You can use a TreeMap to map all of the integers from 0 to 99 to a particular FlowerSuit. Take advantage of the floorEntry method to choose a FlowerSuit for each number. It might look something like this.
public class FlowerChooser {
private static final NavigableMap<Integer, FlowerSuit> FLOWER_SUITS;
private static final Random RANDOMS = new Random();
public FlowerChooser() {
FLOWER_SUITS = new TreeMap<>();
FLOWER_SUITS.put(0, FlowerSuit.RED_FLOWERS);
FLOWER_SUITS.put(14, FlowerSuit.ORANGE_FLOWERS);
FLOWER_SUITS.put(28, FlowerSuit.YELLOW_FLOWERS);
FLOWER_SUITS.put(42, FlowerSuit.GREEN_FLOWERS);
FLOWER_SUITS.put(56, FlowerSuit.BLUE_FLOWERS);
FLOWER_SUITS.put(70, FlowerSuit.INDIGO_FLOWERS);
FLOWER_SUITS.put(84, FlowerSuit.VIOLET_FLOWERS);
FLOWER_SUITS.put(98, FlowerSuit.WHITE_FLOWERS);
FLOWER_SUITS.put(99, FlowerSuit.BLACK_FLOWERS);
}
public FlowerSuit randomFlowerSuit() {
int index = RANDOMS.nextInt(100);
return FLOWER_SUITS.floorEntry(index).getValue();
}
}
Create just one object of this class, then whenever you want a FlowerSuit, call the randomFlowerSuit method.
The randomFlowerSuit method picks a random number from 0 to 99, then finds an appropriate entry in the map. The floorEntry method chooses an entry whose key is less than or equal to the chosen number. This means that numbers from 0 to 13 get mapped to red, 14 to 27 get mapped to orange, and so on. The only number that gets mapped to white is 98, and the only number that gets mapped to black is 99.
No matter what solution you implement, you want to include a frequency measure in your enum. As an example, you can do something like this:
public enum FlowerSuit {
WHITE_FLOWERS("white", ":white:", "470419377456414720", 1, 1),
YELLOW_FLOWERS("yellow", ":yellow:", "470419561267855360", 1, 20),
// More declarations here
// Add this variable
private final int frequency;
// Do just as you did before in the constructor, but with the frequency
FlowerSuit(String displayName, String emoticon, String id, int value, int frequency){
this.frequency = frequency;
// More assignments here
}
public int getFrequency(){
return frequency;
}
// More getters here
}
This addition is critical, and no matter what method you use to weight flower selection, you will want this addition to your FlowerSuit enum.
Now, we can explore a few different ways to perform this selection.
Note 1: I use ThreadLocalRandom for random numbers in a range, which is from java.util.concurrent.ThreadLocalRandom.
Note 2: For each of these, make a single instance of FlowerPicker, and use the pickFlower() method to pick the next flower. This avoid running costly setup code over and over.
Method 1: Bag of Flowers
This method is probably the easiest to implement. It entails creating a list of enums where each is represented frequency times, and then selecting a random entry from this list. It is similar to throwing a bunch of flowers in a bag, shaking it, and then reaching your hand in and grabbing the first flower you touch. Here's the implementation:
public class FlowerPicker(){
private ArrayList<FlowerSuit> bag;
public FlowerPicker(){
// Get all possible FlowerSuits
FlowerSuit[] options = FlowerSuit.values();
// You can use an array here or an array list with a defined length if you know the total of the frequencies
bag = new ArrayList<FlowerSuit>();
// Add each flower from options frequency times
for (FlowerSuit flower : options)
for (int i=0; i<flower.getFrequency(); i++)
bag.add(flower);
}
public FlowerBag pickFlower(){
// Now, select a random flower from this list
int randomIndex = ThreadLocalRandom.current().nextInt(0, bag.size());
return bag.get(randomIndex);
}
}
This method has the advantage of being simple enough to understand very easily. However, it can be inefficient if your frequencies are extremely specific (like if you want a rainbow flower to be returned 499,999,999 times out of 1,000,000,000). Let's move on to the next method.
Note 1: You could make this better by reducing the fractions representing the frequency of being chosen, but I'll leave this to you.
Note 2: You could also make this slightly better by storing identification numbers, not FlowerSuit objects in the bag list.
Method 2: Navigable Map
This method is a little bit more difficult. It uses a [NavigableMap][1], which is an implementation of [TreeMap][2]. This method is fairly similar to the Bag of Flowers method, but it is a little bit more efficient. Put simply, it uses the TreeMap to give each FlowerSuit a range of numbers that can be selected to return that FlowerSuit. Here's a full example:
public class FlowerPicker(){
private NavigableMap<Double, FlowerSuit> map;
public FlowerPicker(){
// Get all possible FlowerSuits
FlowerSuit[] options = FlowerSuit.values();
map = new TreeMap<Double, FlowerSuit>();
int runningTotal = 0;
// Add each flower with the proper range
for (FlowerSuit flower : options){
runningTotal += flower.getFrequency();
map.put(runningTotal, flower);
}
}
public FlowerBag pickFlower(){
// Now, select a random number and get the flower with this number in its range
int randomRange = ThreadLocalRandom.current().nextInt(0, bag.size());
return map.higherEntry(randomRange).getValue();
}
}
This is a solid method, and it scales well for very specific frequencies. If you have a bunch of different types of flowers, it will be slightly worse, but this method is still a good option at large scales. There's one more option though.
Method 3: Enumerated Distribution
This method is really nice because you barely have to do anything. However, it uses [EnumeratedDistribution][3] from Apache Commons. Enumerated Distribution requires a list of pairs of objects and weights. Anyway, lets jump into it:
public class FlowerPicker(){
private EnumeratedDistribution distribution;
public FlowerPicker(){
// Get all possible FlowerSuits
FlowerSuit[] options = FlowerSuit.values();
List<Pair<FlowerSuit, Double>> weights = new List<Pair<FlowerSuit, Double>>();
// Add each flower and weight to the list
for (FlowerSuit flower : options){
weights.add(new Pair(flower, flower.getFrequency()));
// Construct the actual distribution
distribution = new EnumeratedDistribution(weights);
}
public FlowerBag pickFlower(){
// Now, sample the distribution
return distribution.sample();
}
}
This is my favorite method, simply because so much of it is done for you. Many problems like this have been solved, so why not use solutions that always exist? However, there is some value to writing the solution yourself.
In conclusion, each of these methods are perfectly fine to use at your scale, but I would recommend the second or third method.

Exiting a method with switch case in a class to the method that called it in another class

I have a class with a method that calls a method located in another class, and that method has switch cases. Th e problem is that I am not able to exit from the method with switch cases and get back to the next line after the method that called it. I have searched StackOverFlow for similar questions. I also tried to use the suggested solutions in those answers to questions related to exit from a switch case (using a conditional, using return, etc). Unfortunately, when I use these solutions, I don't go back to the next line in the method that called the switch case method. Rather, I am exiting the whole program with "Build Succeeded message".
Rather than being too abstract, I hope I am not flamed for posting some classes simulating the real problem I am facing. Sorry if the code is too long.
public class TestClass {
ClassWithriginalMethod test;
public static void main(String[] args) {
ClassWithriginalMethod g = new ClassWithriginalMethod();
g.presentMenuOptions();
}
}
This class contains the main method.
The next class is the one which have a method that calls the method with switch cases:
import java.util.ArrayList;
import java.util.Scanner;
public class ClassWithriginalMethod {
private final ArrayList<ClassWithSwitchCases> arr;
Scanner s = new Scanner(System.in);
public void presentMenuOptions() {
System.out.println(
"_____________________________________________________________________________\n"
+ "This Menu contains the following options:\n"
+ "Please choose a number corresponding to your option\n"
+ "1: to get create submenu\n"
+ "2: to get edit sub menu\n"
+ "3: to get view sub menu\n"
+ "4: to get delete sub\n"
+ "5: to exit this operation\n"
+ "_____________________________________________________________________________\n");
String str= s.nextLine();
switch (str) {
case "1":
System.out.println("Entering creation...");
this.createMenu();//This method is working properly and user is moved to nextline, i.e shown the presentMenuOptions().
break;
case "2":
System.out.println("Entering editing...");
/* The below method is the damn method that calls the other class methods with swith cases.*/
this.editMenu();
/*
** What I want is to reach the next methos below this comment when I get back from the switch case.
*/
System.out.println("We've exited from the othe class method with switch cases...");
this.presentMenuOptions();
break;
case "3":
System.out.println("Entering viewing...");
this.viewMenu();
this.presentMenuOptions();
break;
case "4":
System.out.println("Entering deletion...");
this.deleteMenu();
this.presentMenuOptions();
break;
default:
System.exit(0);
}
}
public ClassWithriginalMethod() {
this.arr = new ArrayList<>(0);
}
private void createMenu() {
ClassWithSwitchCases toBeCreated = new ClassWithSwitchCases();
this.arr.add(toBeCreated);
this.checkingArraySize();
this.presentMenuOptions();
}
private void editMenu() {
this.checkingArraySize();
System.out.println("The following objects are available. Please select the object with the corresponding index\n");
this.arr.forEach(p -> System.out.printf("%-15d\t%-15s\t%-15s\n", arr.indexOf(p), p.getfName(),p.getsName())); // we print the array to see the indices and object main elems.
int i = s.nextInt();
ClassWithSwitchCases toBeEdited = this.arr.get(i); //supposedly I am checking through another function if the object of index i is in the array.
toBeEdited.edit(toBeEdited); // it is here where we are calling the switch method in the other class
//this.presentMenuOptions();
}
private void viewMenu() {
this.checkingArraySize();
System.out.println("The following objects are available. Please select the object with the corresponding index");
this.arr.forEach(p -> System.out.printf("%-15d\t%-15s\t%-15s\n", arr.indexOf(p), p.getfName(),p.getsName())); // we print the array to see the indices and object main elems.
int i = s.nextInt();
ClassWithSwitchCases toBeViewed = this.arr.get(i); //supposedly I am checking through another function if the provided number id less than size of List.
toBeViewed.view(toBeViewed); // making this class calling the function in the other class
//this.presentMenuOptions();
}
private void deleteMenu() {
this.checkingArraySize();
System.out.println("The following objects are available. Please select the object with the corresponding index");
int i = s.nextInt();
ClassWithSwitchCases deleted = this.arr.get(i); //supposedly I am checking through another function if the provided number id less than size of List.
deleted.view(deleted); // making this class calling the function in the other class
//this.presentMenuOptions();
}
private void checkingArraySize () {
if (this.arr.size() <= 0) {System.out.println("There are no objects in the aray");}
else {
arr.stream().map((p) -> {
System.out.println("The following objects are available.");
return p;
}).forEachOrdered((p) -> {
System.out.printf("%-15s\t%-15s\t%-15s\n", "index", "fName", "sName");
System.out.printf("_____________________________________________________________________________\n");
System.out.printf("%-15d\t%-15s\t%-15s\n", arr.indexOf(p), p.getfName(),p.getsName());
});
}
}
}
The last class is the one with switch cases:
public class ClassWithSwitchCases {
private String fName;
private String sName;
Scanner s = new Scanner(System.in);
public ClassWithSwitchCases() {
System.out.println("Please enter first name");
this.fName = s.nextLine();
System.out.println("Please enter sur name");
this.sName = s.nextLine();
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
System.out.println("Please enter first name");
this.fName = fName;
}
public String getsName() {
return sName;
}
public void setsName(String sName) {
System.out.println("Please enter sur name");
this.sName = sName;
}
public void edit(ClassWithSwitchCases o) {
System.out.println(
"_____________________________________________________________________________\n"
+ "The Edit Menu contains the following options:\n"
+ "Please choose a number corresponding to your option\n"
+ "1: to edit the object's first name\n"
+ "2: to edit the object's sur name\n"
+ "3: to exit this menu\n"
+ "_____________________________________________________________________________\n");
do {
switch (s.nextLine()) {
case "1":
o.setfName(s.nextLine());
System.out.println(o.toString());// just to check if editing took place
this.edit(o); // put so that we can make other edits.
break;
case "2":
o.setsName(s.nextLine());
System.out.println(o.toString());// just to check if editing took place
this.edit(o);
break;
case "3":
System.out.println("We are leaving the method with switch cases...");
break;
default:
System.out.println("We are also leaving the method with switch cases...");
break;
}
} while ((Integer.getInteger(s.nextLine()) <= 3) && (Integer.getInteger(s.nextLine()) > 0));
}
public void view(ClassWithSwitchCases o) {
System.out.println(o.toString());
}
#Override
public String toString() {
return "_____________________________________________________________________________\n"
+ "First Name:" + this.getfName() + "\n"
+ "Middle Name:" + this.getsName() + "\n"
+ "_____________________________________________________________________________\n";
}
}
If you try to work these classes, you will notice:
I am able to execute the createMenu() method, and then I get the presentMenuOptions() method, as supposed to be.
The viewMenu() and deleteMenu() methods do their work, but they exit from the whole program.
The editMenu() method is giving me nullPointerExeption, but I have no idea which pointer is that.
I have indicated in the comments in the code what I was thinking of.
I added extra System.out.println() messages, as a way to debug my code. Since I am only a beginner, this is as far as I can go at this stage.
If there is any general value from my question it is: How to exit from a method with switch cases and go back to another method, not necessarily the main method.
Many thanks for you help and patience :)
You can use the return statement anywhere in the switch. Most likely, you want to change your break statements to return statements.
It seems to me that while my question is valid, it is not the core problem. The core problem is how do I envision my classes (Objects) and how they are related to each other. In other words, I faced this problem because of the way I orchestrated my solution. If I chose another orchestration (i.e, more proper design patterns), most probably I was not going to face this issue.
It also seems to me that beginners (I am one of them) who are serious to build a big solution will face this "problem pattern" (asking either silly questions, or evading questions like "Why you are doing this? What were you aiming to achieve?" because they run quickly into implementing certain classes while they have not figured out the overall structural, behavioral, and creational aspects of the solution.
Interestingly, though, is that by making these mistakes, they learn.
Thanks for those who answered me and those who will answer or comment.

Adding a string to an arraylist through another arraylist's object's method

I am in the process of updating my game to Java, but the only minor bug I have left is this:
Every time a dead player's name is "added" to the dead player name list, it adds the Player object's hashcode instead.
EDIT: Here is a link to a zip folder with the source code:
https://dl.dropboxusercontent.com/u/98444970/KarmaSource.zip
The code in question is the two places where the line gets the player object and gets the object's name. When it is used in println, it works fine and prints the player's name. However, in the second part where it does the same thing, but it prints the hashcode of the player object instead of calling its get_name method and returning the String. I'm not sure if it has to do with the third part, where it adds the "name" to dead player list pdead.
If you'd like a link to the compiled version, let me know. It's compiled under JDK 7 Update 51 64-bit.
EDIT: I got it working, I was originally referencing the players list instead of the pdead list. Thanks to all who contributed to helping. If you still want the game, let me know and I'll put a download link :D
Answering your question:
This code is wrong:
if (karma.pdead.isEmpty())
{System.out.println("None");}
else
for (int index = 0;index < karma.pdead.size();index++)
System.out.println(pdead.get(index));
What is karma? Whatever that is, looks like you're referring to 2 different things there.
Try this:
if (pdead.isEmpty()) {
System.out.println("None");
} else {
for (String deadPlayer : pdead) {
System.out.println(deadPlayer);
}
}
Pretty sure this will work :)
Some further, constructive advice:
Your code is breaking pretty much all conventions/good-practices I know in Java. But I am here to help, not to criticize, so let's try to improve this code.
Never keep state in static fields. This is a recipe for causing memory leaks.
your main function won't even compile. Should look like this:
public static void main(String[] args)
Always wrap the body of for loops with braces.
Be consistent: if you open braces in a new line, then do it every time. NEVER write code on the same line as the opening bracket.
GOOD:
public void doSomething()
{
// body
}
GOOD:
public void doSomething() {
// body
}
BAD:
public void doSomething() {
// body
}
public void somethingOther()
{
// inconsistent!
}
public void terribleCode()
{ System.out.println("Never do this"); }
Do not use underscores to separate words. In Java, the favoured convention is to use camelCase. getName(), not get_name().
class names ALWAYS start with a capital letter, whereas variable names generally start with a lower-case letter.
if you're iterating over all items of a list, just use the forEach construct (shown above) not index navigation.
I wanted to check to see if there was some subtle syntax error, so I cut/paste your code into an editor and tried to massage it to get it running. After my massaging, I ran it and it ran fine. Here is the code I ran and the results I got:
Code:
import java.util.ArrayList;
public class Game {
private static ArrayList<Player> players = new ArrayList<Player>();
private static ArrayList<String> pdead = new ArrayList<String>();
public static void main(String[] args) {
// Some Test Data
Player p1 = new Player("George");
p1.setHp(10);
players.add(p1);
Player p2 = new Player("Bob");
p2.setHp(10);
players.add(p2);
// Print Current State of data
System.out.println("Current Players");
for(Player p: players) {
System.out.println(p.getName() + ": " + p.getHp());
}
System.out.println("Dead Players");
if (pdead.isEmpty()) {
System.out.println("None");
} else {
for (int index=0; index < pdead.size(); index++) {
System.out.println(pdead.get(index));
}
}
// Kill Bob
p2.setHp(0);
// Do work to add names to dead players data structure
for (int index2=0; index2 < players.size(); index2++) {
if ((players.get(index2).getHp() <= 0) && !(pdead.contains(players.get(index2).getName()))) {
pdead.add(players.get(index2).getName());
}
}
// Print Current State of data
System.out.println("Current Players");
for(Player p: players) {
System.out.println(p.getName() + ": " + p.getHp());
}
System.out.println("Dead Players");
if (pdead.isEmpty()) {
System.out.println("None");
} else {
for (int index=0; index < pdead.size(); index++) {
System.out.println(pdead.get(index));
}
}
}
}
class Player {
private String name = "";
private int hp = 0;
public Player(String n) {
name = n;
}
public String getName() {
return name;
}
public int getHp() {
return hp;
}
public void setHp(int h) {
hp = h;
}
}
Here are the results that code gives me:
javac Game.java
java Game
Current Players
George: 10
Bob: 10
Dead Players
None
Current Players
George: 10
Bob: 0
Dead Players
Bob

JAVA. Searching a value and displays the data [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
'm currently making a purchase program. I'm almost halfway done on it, the only thing i need is. when i Press 1 for purchase it will give me an option to input the Item Code that i stored in my inventory. And then it respectively displays the datas or values corresponds on my inputted code based on my stored products on my inventory.
PS: im new in java and i know my codes are still basic cus im still learning java on my own. And my variables are not yet changed into Arraylist cus i just found out that Arraylist is much better than a plain Array in storing collection of data.
Any suggestions is highly appreciated and welcome. Would stick on using Arraylist or Array. not Hashset or etc.. Thank you Guys!
Hope you guys could help me. Thanks!
class Item {
public final int sku;
public final String desc;
public final type other_fields;
public Item(int s, String d, type fields...) {
// set fields
}
}
or if you really want to be clever
abstract class Item {
public final int sku
// ....
}
class PinkCurtains extends Item {
public PinkCurtains() {
sku = 129534;
desc = "Adorable Pink Indoor Curtains";
}
}
class FuzzyTowel extends Item {
public FuzzyTowel() {
sku = 874164;
desc = "Machine Washable Fuzzy Towel";
}
}
then populate your list and search away
ArrayList<Item> catalog = new ArrayList<Item>(0);
for (int i = 0; i < numItems; i++) {
catalog.add(new Item(arg, arg, arg...));
}
// or
catalog.add(new PinkCurtains());
catalog.add(new FuzzyTowel());
for (Item item : catalog) {
if (chosenItem == item.sku) {
// do all your stuff
}
}
They are called Iterables for a reason. You don't have to make classes if you don't want to. ArrayList also has searching methods, contains() and indexOf() for example:
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
If you want to fill in the fields as you go you can make a class that lets you do that:
class Item {
public int id;
public float price;
}
ArrayList<Item> cart = new ArrayList<Item>(0);
do {
Item item = new Item();
item.id = userInput;
item.price = userInput;
cart.add(item);
} while (userInputting);
float total = 0;
for (Item i : cart) {
total += i.price;
}
// using a regular for loop instead of for-each
for (int i = 0; i < cart.size(); i++) {
Item item = cart.get(i);
// or search for something particular
if (item.id == searchID) {
System.out.println("found item " + item.id + " with price $" + item.price);
}
// equivalent to
if (ids[i] == searchID) {
System.out.println("found item " + ids[i] + " with price $" + prices[i]);
}
}
Each time the user wants to add an item, you just make a new one, fill in the fields and add it to the list.

Am i even doing this remotely right? Java Methods

Task at hand:Consider a class ratingScore that represents a numeric rating for some thing such as a move. Attributes: A description of what is being rated, The maximum possible rating, rating.
It will have methods to: get rating from ta user, Return the maximum rating posisble, return the rating, return a string showing the rating in a format suitable for display.
a. write a method heading for each method
b. write pre and post conditions for each method
c. write some java statements to test the class
d. implement the class.
I think i did what i was supposed to do, but it is a method and i am not sure that i put enough room for it to be changed much, this is what i have so far.
import java.util.*;
public class MovieRating
{
// instance variables
private String description = " A movie that shows how racism affect our lives and choices";
private int maxRating = 10;
private int rating;
// methods
//precondition: Must have maxRating, rating and description before you post it back to the user.
//rating between 1 and 10, maxRating is set to 10, description of a movie
public void writeOutput()
{
System.out.println("The max rating is: " + maxRating );
System.out.println("Your rating is: " + rating );
System.out.println("The rating for" + description + " is " + rating);
System.out.println("while the max rating was " + maxRating);
}
// PostCondition: Will write maxRating, rating and description to the user.
//Precondition: description, enter the rating
public void readInput()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("What would you rate the movie \"American History x\" out of ten");
System.out.println(description);
rating = keyboard.nextInt();
}
//postcondition: rating will be set to user's input for the movie American History x.
}
This is my Tester program.. not much so far
public class MovieRatingTester
{
public static void main(String[] args)
{
//object of the class MovieRating
MovieRating rating1 = new MovieRating();
rating1.readInput();
rating1.writeOutput();
}
}
SO did i cover what was told to cover? i think i did but i think i did it the wrong way, let me know please.
Ok, my point of view is:
Your class, MovieRating is missing some basic elements of OOP, and that is what I think you suppose to learn in this homework.
The first element missing is a constructor method, what you did is automatically assigning each new MovieRating the same description. The job of the constructor function is giving a unique values to the Object when it first built in the system.
The constructor method is special, it is public and has the exact same name is the class, as we said, in this method you suppose to assign values to your object variables.
the second thing will be to put getters/setters, these are methods who has access to your private values and will be used to assign/get the values from them. Note the use of them in the code:
import java.util.*;
public class MovieRating
{
// instance variables
private String description;
private int maxRating;
private int rating;
/*This is the constructor
Note the use of .this - the expression is used to call the class form withing
itself*/
public MovieRating(String description, int maxRating, int rating) {
this.setDescription(description);
this.setMaxRating(maxRating);
this.setRating(rating);
}
/*These are the getters and setters - get is used for getting the value
and set is used for assigning a value to it*/
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getMaxRating() {
return maxRating;
}
public void setMaxRating(int maxRating) {
this.maxRating = maxRating;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
//This is a method for the printing commands - notice the use of the get methods//
public void printRatings()
{
System.out.println("The max rating is: " + this.getMaxRating() );
System.out.println("Your rating is: " + this.getRating() );
System.out.println("The rating for" + this.getDescription() + " is " +
this.getRating());
System.out.println("while the max rating was " + this.getMaxRating();
}
// PostCondition: Will write maxRating, rating and description to the user.
/*Precondition: description, enter the rating
Note the use of this.setRating()*/
public void readInput()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("What would you rate the movie \"American History x\" out of ten");
System.out.println(description);
this.setRating(keyboard.nextInt());
}
//postcondition: rating will be set to user's input for the movie American History x.
}
Using the constructor, you can create a different rating from your tester program
MovieRating rating1 = new MovieRating("description 1", 10, 5);
MovieRating rating2 = new MovieRating("description 2", 9, 7);
You should not ask / print the data from the Ratings class. These ratings can come from user input, but also from database, web, etc.
1 Add getters and setters for properties of MovieRating
2 Pass the read and write methods to the main. Something like
System.out.println("The rating for the movie |" + rating1.getTitle() + "| is " + rating1.getRating());
3 You are not aggregating ratings to a movie. You can't have two rating to the same movie (v.g., by different users) together. Convert the rating attribute into a Vector to solve it. Change setRating for addRating
There are many other things, but obviously this is a starters exercise and I do not want you to get confused. Work on these issues and check with your teacher.
Java (and OO in general) is all about abstractions. You want to keep your objects as general as possible so that you extend your programs functionality without modifying existing code. This may be beyond what your professor was looking for but here are my suggestions:
1) Rating - separate this into its own class
Again, the rating is totally separate from the movie - songs can have ratings, tv shows can have ratings. Today ratings can be 1-10, tomorrow ratings can up thumbs up or thumbs down, etc. A Movie "has a" rating. Let Rating decide how to prompt the user and how to display itself.
2) Now that you have a separate Movie class, I would take away the hard-coded title, description in my Movie class (this will let me create many movies and rate them).
Then I would eliminate System.out.println in writeOutput method (you can pass in the OutputStream to the function)
By hard-coding in System.in you are forcing implementation. What if tomorrow your professor says "now, instead of printing to the console, print to a file or a database"? You have to modify the code. Actually, instead of writeOutput, I would override the toString method that all Objects have and then just call System.in(movie.toString()) in main.
3) Your test method doesn't "test" anything - it is just executing a statement. Typically a test method will simulate input, execute the statements, and check for the proper state at the end. A good way to signal that the state is improper (if your test fails, like maybe your Movie Rating is -1), then you throw an exception.
4) This is un-OO related and just a preference, but I would put both Pre and Post conditions before the methods. This just makes it easier to find in my opinion.
The idea of OO is that you separate responsibilities/concerns into separate classes. Each class is responsible for itself. This helps to keep your code more flexible and maintainable. Good luck on the assignment!

Categories