I am a few weeks into my java class and one of my homework assignment I can't seem to figure out. Here is the assignment
"Display a menu of three kinds of cookie. Prompt the user for what kind of cookie they want using the GetGoodInt(public static int GetGoodInt(int tLow, int tHigh) if the input is too high say to high, if its too low, say to low, if not a int display error) jar.
Create a cookie, give it to the Oven to cook it, then give it to a Person to eat it.
!text bolded like This and then followed by declarations is a class that is both required and unchangeable!
Cookie
boolean mCooked
String mFlavor
Cookie( String tFlavor ) // This is a constructor. Note that when you have this, it won’t let you use the lazy default constructor.
String toString() // This lets you output a cookie to the console. Never call it manually.
Oven
void Cook( Cookie tCookie ) // Just sets mCooked to true
Person
void EatCookie( Cookie tCookie ) // If it is cooked, output the type and how good it is. If it isn’t, print one sentence about the symptoms of salmonella.
Sample Output:
What type of cookie would you like?
1) Chocolate chip
2) Peanut butter
3) Oatmeal raisin
4
Not a choice.
r
Not a number
3
That was a great Oatmeal raisin cookie."
This is what I have coded so far but I am having trouble with what i assume isconstructor, so far everything I have tried gives me a Run time error.
Here is all my code
package mainpackage;
public class Cookie
{
public Boolean mCooked;
public String mFlavor;
public Cookie(String tFlavor)
{
tFlavor=mFlavor.toString();
}
public String toString()
{
int i = Week9Jar.Input.GetGoodInt(1, 3);
String tFlavor= Integer.toString(i);
if(tFlavor=="1")
mFlavor="Chocolate Chip";
else if(tFlavor=="2")
mFlavor="Peanut Butter";
else if(tFlavor=="3")
mFlavor="Oatmeal Raisin";
return mFlavor;
}
}
package mainpackage;
public class Oven
{
void Cook(Cookie tCookie)
{
tCookie.mCooked=true;
}
}
package mainpackage;
public class main {
public static void main(String[] args) {
// Week 9 Homework part I
Cookie tCookie=null;
Oven tOven= new Oven();
Person tPerson = new Person();
System.out.println("What type of Cookie would you like?");
System.out.println("1) Chocolate Chip");
System.out.println("2) Peanut Butter");
System.out.println("3) Oatmeal Raisin");
//get Type from user
tCookie=new Cookie(Week9Jar.Input.GetGoodInt(1, 3));
tOven.Cook(tCookie);
tPerson.EatCookie(tCookie);
}
}
Your constructor for Cookie is wrong: you take in tFlavor as an argument and assign a value to it, and after execution of the constructor, that value is lost. What you probably want is:
public Cookie(String tFlavor) {
mFlavor = tFlavor;
}
You don't need to call toString on String objects: they're already strings!
Also, it's not good practice to access data members of a class from another class, even if it's from the same package:
public void Cook(Cookie cookie) {
cookie.setCooked(true);
}
And add a setCooked method inside your class Cookie:
public void setCooked(boolean b) {
mCooked = b;
}
Related
I'm not sure why, but I'm having a problem launching the code that I put together. For some reason, the code shows fatal errors when I enter a parameter within the methods. I have checked it several times but could not figure out what I did wrong.
Any advice would be appreciated.
public class songcode
{
/**
* #param args the command line arguments
*/
public class Songwriter{
private int song;
//variable for the amount of songs played
private int royalty;
//variable for the amount of payments
private int identification_number;
//id number of the song writer
public String first_name;
//string for the first name of songwriter
public String last_name;
//string for the last name of the songwriter
public int Adding_song(){
song = song + 1;
if(song > 100){
System.out.println("You are a big star!");
}
return(song);
}
public int Requesting_check(){
royalty = royalty + 10;
System.out.println("You just got payed");
return royalty;
}
public static void main(String[] args){
}
}
}
See the comments for some quick help :)
public class SongWriter {
private int song;
//variable for the number of songs played
private int royalty;
//variable for the number of payments
private int identification_number;
//id number of the song writer
public String first_name;
//string for the first name of songwriter
public String last_name;
//string for the last name of the songwriter
public SongWriter(int myFavSong){
//define default values for vars above
this.song = myFavSong;
//'This' references the Songwriter object not required but useful practice.
}
// Lower case first word upcase second : camelCase
public int addingSong(int numSongs){
song = song + numSongs;
if(song > 100){
System.out.println("You are a big star!");
}
return(song);
}
public int requestingCheck(){
royalty = royalty + 10;
System.out.println("You just got payed");
return royalty;
}
// The main method shouldn't be nested another class
public static void main(String[] args){
//In java because our variables and functions are not static
//you need a reference to your SongWrite object
SongWriter songWriter = new SongWriter();
// Notice I modified your function to take in an int as a param
songWriter.song = addingSong(5);
System.out.println(songWriter.song);
}
}
because of lack information it is a little hard for us to solve your problem. Please provide us exacly what steps did you take and what errors did you get.
From what i see now, since your are using inner class (class inside of another class), you should make it static:
static class Songwriter{/*your code here*/ }
When you got that you can create an object of that class in your main() by calling your outer class, so in your case it would be:
songcode.Songwriter name = new songcode.Songwriter();
Now you can use your methods that are within your inner class by using name.method() like:
name.Requesting_check();
for(int i = 0; i<200; i++){
name.Adding_song();
}
Personally i would create a new java file called Songwriter.java, add a constructor and work with that, but maybe that's not what you were testing here ;-)
Hope it did help you and please next time provide more detailed informations, so we can give you an exact answer without guessing what's wrong and what exacly do you want to achieve with your code.
so I am currently taking an online coding class. and it has us make two different codes. one called SpaService. and one called CreateSpaService.
From my understanding, these are supposed to work together, to call variable (etc.) but it is not working and I am being hit with syntax errors saying that variables are not declared, but I declared them in the other code.
Am I supposed to put them in the same doc or something? I tried that and it still wouldn't work. Is there some way I have to link the two codes so they work together?
Here are the two codes.
also, do you see any syntax errors?
Thank you so much
import java.util.Scanner;
public class CreateSpaServices
{
public static void main(String[] args)
{
SpaService firstService = new SpaService();
SpaService secondService = new SpaService();
firstService = getData(firstService);
secondService = getData(secondService);
System.out.println("First service details:");
System.out.println(firstService.getServiceDescription() + " $" + firstService.getPrice());
System.out.println("Second service details:");
System.out.println(secondService.getServiceDescrption() + " $" + secondService.getPrice());
}
public static SpaService getData(SpaService service)
{
String service;
double price;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter service >> ");
service = keyboard.nextLine();
System.out.print("Enter price >> ");
price = keyboard.nextDouble();
keyboard.nextLine();
service.setServiceDescription(Service);
service.setPrice(price);
return service;
}
}
//here is other code, im not sure if where I put this, or if I keep it in its own document or in this doc.
public class SpaService
{
private String serviceDescription;
private double price;
public SpaService()
{
serviceDescription = "XXX";
price = 0;
}
public void setServiceDescription(String service)
{
serviceDescription = service;
}
public void setPrice(double servicePrice)
{
price = servicePrice;
}
public String getServiceDescription;
{
return serviceDescription;
}
public double getPrice()
{
return price;
}
}
You want to have the two classes in respective files in the same folder location:
SpaService.java
CreateSpaServices.java
Are you using some kind of IDE or using command prompt to manually compile and execute? IDE make things very simple but they take away some finer learning details for beginners.
Anyway a text file can have one Public class and any number of non-public class. As your both classes are public it should be in different file. Classes are linked to each other via import statement , which must be first line in java class if any.
You should get some compile issues also as I can see this method
public static SpaService getData(SpaService service)
As you are returning service variable which is of type String, but your method signature is expecting SpaService
The other answers are useful for understanding the class structure, but you have an issue with your code issue that is likely causing the majority of your problem.
In the getData method you have two items named service, the SpaService service and String service;, you need to change one of them.
This line is not valid service.setServiceDescription(Service);, you can't refer to Service with a capital S, you need to reference to a valid string.
Here is an example that takes the above into account:
public static SpaService getData(SpaService service)
{
//Create a scanner
Scanner keyboard = new Scanner(System.in);
//Get scanner input
System.out.print("Enter service >> ");
String description = keyboard.nextLine();
//Add input to SpaService object
service.setServiceDescription(description);
//Get scanner input
System.out.print("Enter price >> ");
double price = keyboard.nextDouble();
//Add input to SpaService object
service.setPrice(price);
//Return SpaService object
return service;
}
For better help please edit your question to include the full error.
I am attempting to write a program which asks users what their pet name is, species, finds out thirst level and gives a response accordingly.
I would appreciate if someone could help me with a problem im having, in each of the 2 methods askpetname and thirstlevel there are 2 strings i want accessible throughout the entire class without using global variables.
Can someone tell me what it is i am doing incorrectly or point me in the right direction.
Also, i understand that my excess use of methods for tedious tasks is bad practice but it helps with memorising syntax.
Thanks.
class dinoo
{
public static void main(String[] p)
{
explain();
output();
System.exit(0);
}
public static void explain()
{
print("The following program demonstrates use of user input by asking for pet name.");
return;
}
public static String askpetname()
{
Scanner scanner = new Scanner(System.in);
print("Name your dinosaur pet!");
String petname = scanner.nextLine();
print("Awesome, cool dinosaur name, what species is " + petname+ " ?");
String petspecies = scanner.nextLine();
return petname, petspecies;
}
public static int thirstlevel()
{
Random ran = new Random();
int thirst = ran.nextInt(11);
int hunger = ran.nextInt(11);
return thirst,hunger;
}
public static String anger(int thirst, int hunger)
{
double angerscore = (thirst+hunger)/2;
String temper;
if(angerscore<=2)
{
temper = "Serene";
}
else if(3<=angerscore<=6)
{
temper= "Grouchy";
}
else if(6<angerscore)
{
temper = "DANGEROUS";
}
return temper;
}
public static String warning()
{
if (temper.equals("Serene"))
{
print("He's looking happy!");
}
else if(temper.equals("Grouchy"))
{
print("Ahhh hes a bit "+temper+", you better start feeding him before he gets mad!");
}
else if(temper.equals("DANGEROUS"))
{
print("GET OUT OF THERE, HES " + temper+"!!!. He will have to be put down for everyones safety.");
}
}
public static void output()
{
print(askpetname() + "'s, thirst level is "+thirstlevel()+"/10");
return;
}
public static String print(String message)
{
System.out.println(message);
return message;
}
}
That code won't compile since you can't have:
return string1, string2;
or
else if(3<=angerscore<=6)
Instead of trying to return multiple Strings, your best bet is to create a class, say called Pet, one that holds String fields for the pet's name, a Species field for its species, as well as any other fields for hunger, thirst ... that would best encapsulate all the data that makes up one logical "pet" as well as a methods such as getAnger() that returns a value for anger depending on the Pet's state. Then you can create and return a viable Pet object from your creational method.
Also, your code has lots of compilation errors, suggesting that you could improve the way that you create your code. Never try to add new code to "bad" code, to code that won't compile. If possible, use an IDE such as NetBeans, Eclipse, or IntelliJ to help you create your programs. The IDE's will flag you if any of your code contains compilation errors, and then the key is: don't add new code until you've first fixed the existing compilation error. If you can't use an IDE, then you must compile early and often, and do the same thing -- fix all errors before adding new.
First, I would recommend shooting through a tutorial first before attempting this, do all the hello worlds covering scope, objects, arrays and functions. Get familiar with Object Oriented Style, although thats not even procedural programming ... nothing returns 2 objects ... always 1 (it could be an array containing many objects, but an array is a single object)
Moving on,although this is terrible coding practice, but its ok for a beginner,since your functions are all static, create a private static variable inside each function and create getter functions
//convert
String petname = scanner.nextLine();
// To this
private static String petname = scanner.nextLine();
// Then add this below it
public static String getPetName()
{
return petname;
}
and same for every piece of data you need.
Now remove the return statement from all of your functions and declare return type as void
Then call all functions from Main,
askpetname();
thirstlevel();
then print final output (after you have called the functions) as such
System.out.println("Petname: " + getPetname + " ThirstLevel: " + getThirstLevel() + " HungerLevel: " + getHungerLevel);
I have Arraylist of objects ArrayList<Product> productDatabase. The object contains a String and a double and then these objects will be added to the productDatabase by addProductToDatabase(); as follows:
public void addProductToDatabase(String productName, double dimensions); {
Product newProduct = new Product(ProductName, dimensions);
productDatabase.add(newProduct);
}
I also want to make an Arraylist<ProductCount> productInventory which counts how many Product are accounted for. Before it can add to ArrayList<ProductCount> productInventory however, it should first check if the object details exist in the productDatabase while running addProductToInventory()
public Product getProduct(String name) {
for(i = 0; i < productDatabase.size(); i++)
if(productDatabase.get(i).contains(name) //Error: cannot find symbol- method contains.(java.lang.String)
return productDatabase.get(i)
}
public void addProductToInventory(String productName, double quantity)
{
Product p = getProduct(name);
productCount.add(new ProductCount(o, quantity));
}
Assume that you always have different objects (so nothing will have the same name), but you're always unsure of the dimensions (so when you input the same producttName + dimensions you edit the dimensions in it).
At the end of the day, you have to put all the items in it a large box and report what you've inventoried, so you also have a getProductQuantityTotal() and you have to getProductDimensionTotal()-- as the name suggests, get the total of number of objects you've counted, and the sum of the dimensions.
What do I have to add/change/remove about this code? Don't consider syntax first (because BlueJ checks for common syntax errors and I just typed this by hand). I'm sure that I'm missing a for statement somewhere, and I'm probably misusing contains() because it won't recognise it (I have import java.util.*; and import java.util.ArrayList;)
To answer the question in your post title: How to find a string in an object, for a list of those objects, here is some sample code that does this:
First, I created a trivial object that has a string field:
class ObjectWithStringField {
private final String s;
public ObjectWithStringField(String s) {
this.s = s;
}
public String getString() {
return s;
}
}
And then a code that populates a list of it, and then searches each for the string. There's no magic here, it just iterates through the list until a match is found.
import java.util.List;
import java.util.Arrays;
/**
<P>{#code java StringInObjectInList}</P>
**/
public class StringInObjectInList {
public static final void main(String[] ignored) {
ObjectWithStringField[] owStrArr = new ObjectWithStringField[] {
new ObjectWithStringField("abc"),
new ObjectWithStringField("def"),
new ObjectWithStringField("ghi")};
//Yes this is a List instead of an ArrayList, but you can easily
//change this to work with an ArrayList. I'll leave that to you :)
List<ObjectWithStringField> objWStrList = Arrays.asList(owStrArr);
System.out.println("abc? " + doesStringInObjExistInList("abc", objWStrList));
System.out.println("abcd? " + doesStringInObjExistInList("abcd", objWStrList));
}
private static final boolean doesStringInObjExistInList(String str_toFind, List<ObjectWithStringField> owStrList_toSearch) {
for(ObjectWithStringField owStr : owStrList_toSearch) {
if(owStr.getString().equals(str_toFind)) {
return true;
}
}
return false;
}
}
Output:
[C:\java_code\]java StringInObjectInList
abc? true
abcd? false
In the real world, instead of a List, I'd use a Map<String,ObjectWithStringField>, where the key is that field. Then it'd be as simple as themap.containsKey("abc");. But here it is implemented as you require. You'll still have quite a bit of work to do, to get this working as specifically required by your assignment, but it should get you off to a good start. Good luck!
I am writing a program that will generate a geometry Logic Word Problem, and I am having trouble with it. My goal is to have the program randomly create a word problem that is pre-designed. So far, the program takes input from the user, and then uses that information in the Story methods, somewhat like a game of Mad Libs. Anyways, I want to randomly chose a Story method to run each time the user starts the program. So far this is what I have:
import cs1.Keyboard;
public class LogicProof {
//Main method
public void main () {
System.out.println ("Enter 1. to start.");
System.out.println ("Enter 2. to exit.");
int choice = Keyboard.readInt();
if (choice == 1) { //Take info in and send to createStory
//Randomly run methods
}
if (choice == 2) {
System.out.println ("\nGoodbye.");
}
//Create the first story using inputs from main
private void createStory(String adj,String adj2,String adj3,String action) {
//Use values from main() to create a problem
}
There are two other createStory methods as well. Also, I am going to display the proofs of each problem, and each method has its own proof, so would I be able to then display the proof for the same method, basically just link together the proof method, and story method?
I'm fairly new to Java, and appreciate the help.
Thanks in advance.
To only answer your title, you could use random generation with reflection, but that is in no way how you should solve your current problem.
Don't try and randomly invoke methods. Take a look at java.util.Random's nextInt() and use that to do unique operations based on the value it returns.
This seems like Homework which is why I'm not giving you a full solution here.
public class MadLibs {
public static final String[] STARTERS = { /* ... */ };
public static final String[] ENDINGS = { /* ... */ };
public static String generate(String ... adjectives) {
final Random random = new Random();
final StringBuilder string = new StringBuilder(STARTERS[random.nextInt(STARTERS.length-1)]);
for (String adjective : adjectives) {
string.append(adjective);
string.append(TRANSITIONS[random.nextInt(TRANSITIONS.length - 1)]);
}
return string.toString();
}
}
That's an extremely simple and rough implementation to get you started.
Or maybe, if you have only a few concrete variations:
public class MadLibs {
public static String generate(String ... adjectives) {
int result = new Random().nextInt(MAX);
String madLib = null;
switch (result) {
case 0:
// ...
break;
case 1:
// ...
break;
default:
// ...
break;
}
return madLib;
}
}
Like said above, use random number generation to yourself a 1,2,3,4 ect... Then pass that number into your method as a parameter and then use "if, if else" statements to choose the correct operation to perform. Again, like stated above I will not give any code in case this is indeed a homework problem.
You could generate a Word or Phrase object, populate them into a List.
From there us something like Random or Math.random to pull a word or phrase from the list