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);
Related
Is setter method only use to assigning values? or can we perform operations in it. Here in this code the commented part is giving me correct output but while using set and get I am getting output as 0.
I want to avoid calling totalMarksOfStudent() method again and again because it have 5 parameters which I dont want to give again and again. So what is the way to return totalMarksStudent in another class without calling totalMarksOfStudent().
int totalMarksStudent = 0;
public void setMarks(int englishMarks, int mathsMarks, int physicsMarks, int chemistryMarks, int csMarks) {
totalMarksStudent = englishMarks + mathsMarks + physicsMarks + chemistryMarks + csMarks;
}
public int getMarks(){
return totalMarksStudent;
}
// public int totalMarksOfStudent(int englishMarks, int mathsMarks, int physicsMarks, int chemistryMarks, int csMarks) {
// totalMarksStudent = englishMarks + mathsMarks + physicsMarks + chemistryMarks + csMarks;
// return totalMarksStudent;
}
public String displayTotalMarks() {
String totalMarks1 = "Name " + name + "\tRoll No " + rollNo + "\tTotal Marks " + getMarks();//totalMarksOfStudent(englishMarks, mathsMarks, physicsMarks, chemistryMarks, csMarks);
return totalMarks1;
}
Better to avoid that...
I think it's better to have some fields like your parameters in setMarks (englishMarks , mathsMarks , ...) , and give value to them in constructor or setter methods. Also it's better to have a method named something like calculateTotalMarks , and call it without any parameters whenever you need it. Remember that there will be no problem to have operations in setter methods but usually and for better designed program we avoid that. Methods should do the thing their name says : for example , setter just for assigning , getter just for accessing values , calculateTotalMarks for calculating the total marks and so on ...
setter method is usually used to assigning values. It is promise.
You can reduce parameters by using Object
I recommend to make object of MarksStudent. because common attribute can bind to one class. It make understand easily code
for example
// Java is object-oriented language
class marksStudents {
private int english;
private int math;
private int physics;
private int chemistry;
private int cs;
//getMethods is Abbreviation
public int getTotal() {
return english+math+physics+chemistry+cs;
}
//setMethods
public void setEnglish(int english) {
this.english = english;
}
public void setMath(int math) {
this.math = math;
}
public void setPhysics(int physics) {
this.physics = physics;
}
public void setChemistry(int chemistry) {
this.chemistry = chemistry;
}
public void setCs(int cs) {
this.cs = cs;
}
}
To execute
public class Main{
public static void main(String[] args) {
// You can make object marksStudents of studentsA
marksStudents studentsA = new marksStudents();
studentsA.setChemistry(20);
studentsA.setEnglish(30);
studentsA.setMath(40);
studentsA.setCs(50);
studentsA.setPhysics(60);
//200
System.out.println(studentsA.getTotal());
// You can make object marksStudents of studentsB too
marksStudents studentsB = new marksStudents();
studentsB.setChemistry(10);
studentsB.setEnglish(10);
studentsB.setMath(10);
studentsB.setCs(10);
studentsB.setPhysics(10);
//50
System.out.println(studentsB.getTotal());
}
}
The getter/setter method is only a practice. Not bad practice - it just defines a class, whose instances for the external world are handled by a list of independent values. Using them makes your code better comprehensible and easy to understand, what is it doing.
So it is no problem to make other operations with it, in general.
Some frameworks like to use reflection to use getters/setters and also reach the variables directly in them. In these cases, doing any different in the getters/setters than reading/writing the private members is no wise idea. Sometimes you can use a little bit of api/impl interface trickery to handle this problem.
In Java, where should I aim (I enjoy figuring it out myself) to get, with sample data:
I am Sam I am a
the output:
I am Sam I am - letter to remove a
I m Sm I m
Basically, it is to "Remove all instances of the specified removal letter from the original sentence"
As this is for a class, I am limited with what I can do. For this assignment I am stuck with the given classes/constructors and am not allowed to make any more unless it is noted, which in my case, is to create another constructor class; Anyway, that has been the real challenge as it is hard to get help (No matter how many times I've googled!) with it being so specific and I new to the language.
Here is what I was given:
import static java.lang.System.*;
public class LetterRemover
{
private String sentence;
private char lookFor;
public LetterRemover()
{
//call set
}
//add in second constructor
public void setRemover(String s, char rem)
{
sentence = s;
lookFor = rem;
}
public String removeLetters()
{
String cleaned=sentence;
return cleaned;
}
public String toString()
{
return sentence + " - letter to remove " + lookFor;
}
}
This is what I've done so far:
import java.util.Scanner;
import static java.lang.System.*;
public class LetterRemover
{
private String sentence;
private String lookFor;
public LetterRemover()
{
//I am not sure what this means
}
//add in second constructor
public void setRemover(String s, String rem)
{
sentence = s;
lookFor = rem;
}
public String removeLetters()
{
sentence = sentence.replaceAll(lookFor,"");
String cleaned=sentence;
return cleaned;
}
public String toString()
{
return sentence + " - letter to remove " + lookFor;
}
}
I tried changing the char to a string for the "lookfor" to use the replace all method which seemed after a lot of research and the best way to get the letters out.
Is there any noticeable mistakes and where should I look to fix them? I do not really want the right code, or for anyone to "do" the work for me. I really want to try and figure it out. But I need a little help in pointing in the right direction to get my desired output :)
Let me know if there is any other details or whatnot, this is also , this is also my first time using the site. There were many similar questions to this, but as I really am a beginner I struggled to understand people's explanations
--Edit--
Moving to my runner class, this is what I wrote, trying to get for the desired output. I am not really sure how to deal with output as I really have just started learning to write them myself.
I keep getting a void error though:
import static java.lang.System.*;
public class LetterRemoverRunner
{
public static void main( String args[] )
{
LetterRemover test = new LetterRemover
(test.setRemover("I really want dumplings","l"));
}
}
Try the below code and confirm this is what your requirement is.
LetterRemoverRunner.java
public class LetterRemoverRunner {
public static void main(String args[])
{
LetterRemover test = new LetterRemover ();
test.setRemover("I really want dumplings","l");
System.out.println(test.toString());
System.out.println("Removed :"+test.removeLetters());
}
}
LetterRemover.java
public class LetterRemover
{
private String sentence;
private String lookFor;
public LetterRemover()
{
//I am not sure what this means
}
public void setRemover(String s, String rem)
{
this.sentence = s;
this.lookFor = rem;
}
public String removeLetters()
{
sentence = sentence.replaceAll(lookFor,"");
String cleaned=sentence;
return cleaned;
}
public String toString()
{
return sentence + " - letter to remove " + lookFor;
}
}
I'm pleased you suggested you don't want the answer - much better way to learn!
I'm not sure you've understood constructors yet. You're line:
LetterRemover test = new LetterRemover
(test.setRemover("I really want dumplings","l"));
Is going to give you a null pointer error because it's calling setRemover on test before test has been constructed. You should be constructing the object with its sentence and lookFor values before calling setRemover.
Here are some things you might want to look at:
The String.indexOf method will look for a certain character or string and tell you where to find it (or if it isn't in the string at all).
The String.substring method allows you to take part of a string using string positions
You can build a new string by concatenating substrings together
Using a while loop you can continue using indexOf until the target cannot be found.
As you've pointed out, you can also use one of the replace methods to replace the target with "".
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;
}
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