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.
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.
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
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.
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!