Is there any way to retrieve an input value from the past - java

I'm a beginner in java and it is my only code I know how to use so far. I'm working on a food system for an RPG game. Basically it displays a list of the available food items and ask you to press number to eat . After pressing a number, it prints out what you have decided to eat based on what your number corresponded to. I then need to retrieve what "food" you ate so that I can use it's stats. Here's what I have so far:
public String eatmenu() {
System.out.print ( "Consumables: ");
for ( Sustenance consum : consumables ) {
System.out.print ( "[" + consum + "], " );
}
int number = consumables.size();
int counter = 1;
while ( counter <= number ){
System.out.print ("\nPress " + counter + " to consume " + consumables.get(counter-1));
counter++;
}
int choice = reader.nextInt();
String eatchoice = "You decided to consume " + consumables.get(choice-1);
return eatchoice;
}
public String eat3(){
//the food just eaten,
}
Heres the code for the Food Class or "Sustenance":
public class Sustenance extends Item {
String n;
int v;
int s;
public Sustenance ( String name, int Nvalue, int size ){
n= name;
Nvalue = v;
size = s;
}
public String toString() {
String str = "The " + n + "increased your Nutrition level by " + v + ".\nYour backpack is also " +
s + " pounds lighter.";
return str;
}
}
Any ideas are appreciated as to what to put for the eat3 method. I know I will be using the toString method in order to print out the effects of eating the specific item but how do I refer to the item I just ate? I will take everything as critique. Thank you for your time.

Use JavaBeans to set the food and then get it. For example:
public class FoodBean{
public FoodBean(){}
private String foodName;
// other fields which you wana set or get
public void setFoodName(String foodName){
this.foodName = foodName;
}
public String getFoodName(){
return this.foodName;
}
// override the toString() if you want the object to represent the foodName stored
#Override
public String toString(){
return this.foodName;
}
}
Ok so now we have a BeanClass..
now you need to create a bean object whenever the user clicks any item
FoodBean fb = new FoodBean();
fb.setFoodName("get food name from the mapped list here against its number");
now use getFoodName() anywhere in the program, just be careful, the bean object above has local scope if you create it in a method, you need to make a same reference to FoodBean globally and assign the new created object to it, and then use that global reference anywhere in the class.
Further take a look at this simple tutorial

Related

Java toString in class

I am getting an error of cannot find symbol in my code posted below. I am trying to initalise a sedan using it's class and have the toString function right after but nothing is working for me. Please help
class cars {
String make;
String model;
String color;
int year;
double price;
public String sedancClass(String initMake, String initModel, String initColor, int initYear, double initPrice) {
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
String name = "Sedan";
String main = (color + " " + make + " " + model + " " + name + " " + year + " costs $" + price);
return main;
}
}
public class autoPark {
public static void main(String args[]) {
cars sedan1;
sedan1 = new sedanClass("Ford" , "Model-1" , "white" , 2015, 20000);
}
}
According to what you provided, I think this is what you are trying to do
class cars {
String make;
String model;
String color;
int year;
double price;
// parametised constructor
public cars (String initMake, String initModel, String initColor, int initYear, double initPrice) {
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
}
#Override
public String toString() {
String name = "Sedan";
String main = (color + " " + make + " " + model + " " + name + " " + year + " costs $" + price);
return main;
}
}
public class autoPark {
public static void main(String args[]) {
cars sedan1; // declaring cars object by name sedan1
sedan1 = new cars("Ford" , "Model-1" , "white" , 2015, 20000); // initialising sedan1 using cars constructor
System.out.println(sedan1); // printing sedan1 for invoking toString() method
}
}
Why we use #Override annotation source
Using #Override annotation while overriding a method is considered as a best practice for coding in java because of the following two advantages:
If programmer makes any mistake such as wrong method name, wrong parameter types while overriding, you would get a compile time error. As by using this annotation you instruct compiler that you are overriding this method. If you don’t use the annotation then the sub class method would behave as a new method (not the overriding method) in sub class.
It improves the readability of the code. So if you change the signature of overridden method then all the sub classes that overrides the particular method would throw a compilation error, which would eventually help you to change the signature in the sub classes. If you have lots of classes in your application then this annotation would really help you to identify the classes that require changes when you change the signature of a method.

Print the parameter of an object

WordDef is an object that accepts String word, and String definition as parameters. dictionary is an ArrayList of WordDef objects. I need to print out just the definition parameter based on the word the user inputs. This is what I have tried:
//in a separate class
public String toString() {
return word + "\t" + definition;
}
String d = "";
System.out.println("Enter the word you would like to see the definition of: ");
String w = reader.nextLine();
for(int x = 0; x < dictionary.size(); x++) {
if(dictionary.get(x).equals(w)) {
d.toString(); //I know this wouldn't work but I was trying to see if anything would print at all
}
System.out.println("The definition for " + w + " is: " + d.toString());
I'm unsure how to search for specific parameters of an object. Thanks
A Map or a HashMap would be a better way to go for efficiency and convenience, but if you want to use an ArrayList, use:
if(dictionary.get(x).getWord().equals(w) {
System.out.println(dictionary.get(x).getDefinition())
}
getWord() and getDefinition() are just how you might have defined accessors. If word and definition are not private, you can access them directly with .word and .definition. But you probably want them to be private.
You just needed the code to access properties at that index in the ArrayList.
The below code works assuming there is a getter for definition class member.
System.out.println("Enter the word you would like to see the definition of: ");
String w = reader.nextLine();
for(int x = 0; x < dictionary.size(); x++) {
if(dictionary.get(x).word.equals(w)) {
System.out.println("The definition for " + w + " is: " + dictionary.get(x).getDefinition());
}
}
If WordDef class is somewhat like this :
public class WordDef {
private String word;
private String definition ;
public Student(String word, String definition){
this.word=word;
this.definition=definition;
}
#Override
public String toString(){
return "Word : "+word+", Definition : " +definition;
}
}
You can override toString for WordDef and call System.out.println(wordDefObject) it will work.

How do i assign and obtain values to objects created in an array?

Currently learning Java as a hobby and am making small game projects to reinforce the concepts. So for this one, I've made a method that creates an array of objects, in this case, a "Computer" object. I'm doing this because I want the user to decide at startup how many computer opponents they want to play against, instead of hard coding a set number of them. Now I want to assign and retrieve a value for each Computer object. For example a Computer name, bet amount, and a dice roll guess.
public class Computer {
static int bet;
static int guess;
int cash;
static Computer[] c;
public static void create(int numComps) {
c = new Computer[numComps];
for (int i = 0; i < numComps; i++) {
c[i] = new Computer();
c[i].cash = Game.startCash;
c[i].bet = bet();
c[i].guess = guess();
c[i].display();
}
}
public static int bet() {
bet = Rng.rand(Game.startCash / 50) * 50;
return bet;
}
public static int guess() {
guess = Dice.roll();
return guess;
}
public void display() {
String name = "Computer ";
System.out.println("My name is " + name + " i bet " + bet + " and guess " + guess);
}
}
When i do Computer.create(5) i get
My name is Computer i bet 150 and guess 9
My name is Computer i bet 50 and guess 3
My name is Computer i bet 450 and guess 11
My name is Computer i bet 250 and guess 11
My name is Computer i bet 50 and guess 10
This output gives the appearance of working but i don't think i'm on the right track. For the name i want the syntax to be something like, name = "Computer " + c[i]. Resulting in "Computer 1", "Computer 2", "Computer 3" etc, not sure how to do that correctly. And an individual bet and guess to be assigned to each individual object. Right now i think its just displaying a random number rather than assigning that value to the particular object.
The bet and guess member variables shouldn't be static.
To display the id you can add a new int member variable, set it to i for each computer when you initialize them in the loop, and update the display() method to print it.
public class Computer {
int id;
int bet;
int guess;
int cash;
static Computer[] c;
public static void create(int numComps) {
c = new Computer[numComps];
for (int i = 0; i < numComps; i++) {
c[i] = new Computer();
c[i].id = i;
c[i].cash = Game.startCash;
c[i].bet = bet();
c[i].guess = guess();
c[i].display();
}
}
public static int bet() {
return Rng.rand(Game.startCash / 50) * 50;
}
public static int guess() {
return Dice.roll();
}
public void display() {
String name = "Computer ";
System.out.println("My name is " + name + id + " bet " + bet + " and guess " + guess);
}
}

Java - adding to an inherited JOptionPane

Good evening all!
I think there's something I don't understand here about either inheritance or JOptionPane, but basically I want to figure out how to actually use a new JOptionPane in the LuxuryCarRental subclass.
Currently it displays 2 dialog boxes if the choice is "l", one box from the parent class and a new one I added in the subclass. Ideally I would want only one dialog box. I think this is something that I can do without JOptionPane but I would like to try to make it work with JOptionPane if possible.
My code:
CarRental.java (parent class)
import javax.swing.JOptionPane;
public class CarRental
{
private String name;
private String zipCode;
private String size;
private double dailyFee;
private int rentalDays;
private double totalFee;
public CarRental(String name, String zipCode, String size, int rentalDays)
{
this.name = name;
this.zipCode = zipCode;
this.size = size;
if (size.equals("e"))
{
dailyFee = 29.99;
}
else if (size.equals("m"))
{
dailyFee = 38.99;
}
else if (size.equals("f"))
{
dailyFee = 43.50;
}
this.rentalDays = rentalDays;
totalFee = dailyFee * rentalDays;
}
public void display()
{
JOptionPane.showMessageDialog(null, "Car for " + name + " from zip code " + zipCode + "\n"
+ "Type = " + size + "\n"
+ "Daily Fee = " + dailyFee + "\n"
+ "Days = " + rentalDays + "\n"
+ "Your rental is $" + totalFee);
}
//includes getters and setters but I didn't include this in this post
LuxuryCarRental.java (subclass)
import javax.swing.JOptionPane;
public class LuxuryCarRental extends CarRental
{
public LuxuryCarRental(String name, String zipCode, String size, int rentalDays)
{
super(name, zipCode, size, rentalDays);
if (size.equals("l"))
{
this.setDailyFee(79.99);
String includeChauffeur;
includeChauffeur = JOptionPane.showInputDialog(null, "Include chauffeur? Y/N");
if (includeChauffeur.equals("Y") || includeChauffeur.equals("y"))
{
this.setDailyFee(279.99);
this.setTotalFee(this.getDailyFee()*this.getRentalDays());
JOptionPane.showMessageDialog(null, "Chauffeur # $200/day = $" + 200 * this.getRentalDays());
}
}
}
}
UserCarRental.java (driver class)
import javax.swing.JOptionPane;
public class UseCarRental
{
public static void main(String[] args)
{
String name = JOptionPane.showInputDialog("Enter name");
String zip = JOptionPane.showInputDialog("Enter zip code");
String size = JOptionPane.showInputDialog("Enter type of car" + "\n" + "e - economy" + "\n" + "m - midsize" + "\n" + "f - full" + "\n" + "l - luxury");
int days = Integer.parseInt(JOptionPane.showInputDialog("Enter days to rent"));
CarRental userInfo = new LuxuryCarRental(name, zip, size, days);
userInfo.display();
}
}
Any help would be greatly appreciated!
I think that the lesson here is to not mix UI code with model code. Understand that your CarRental class and all of its subclasses are logical or model classes, and can be thought of here as classes that model a physical or logical reality. They should be used in this capacity, and should be written so information can be passed into them and extracted out of them, but they should not interact directly with the user. Instead that is the responsibility of the UI (user interface) classes, of which here it is quite simple and only your main method. So I suggest that you get your JOptionPane calls out of both CarRental and LuxeryCarRental, and instead display the JOptionPane in your main method after extracting state from your CarRental object.
Otherwise, if you absolutely must have the model classes display their information, then do it in a method that can be fully overridden. In fact you would have your child class override the display() method, and then print out its data there.

How can I get an Output with an increasing number per object with the toString()-Method? Java

I'm using the toString()-Method to get the proper output from my ArrayList.
But I'm still not able to get an Output where the number increases per object.
The current code I have written is as follows:
public class Book {
#Override
public String toString() {
StringBuilder result = new StringBuilder();
int i = 1;
result.append("\n\n-Book "+ i++ +": ");
result.append("\nTitel: " + this.Titel + "§ ");
result.append("\nAuthor: " + this.Autor + "§ ");
return result.toString();
}
by inserting ' i++ ' I'm trying to get an output,
where the number increases for each object from the public class Book();
Current Output:
-Buch **1**:
Titel: Hunger Games§
Author: Suzanne Collins§ ,
-Buch **1**:
Titel: Twilight§
Author: Stephanie Meyer§ ,
-Buch **1**:
Titel: Pride and Prejudice§
Author: Jane Austen§ ,
Output I'm trying to get:
-Buch **1**:
Titel: Hunger Games§
Author: Suzanne Collins§ ,
-Buch **2**:
Titel: Twilight§
Author: Stephanie Meyer§ ,
-Buch **3**:
Titel: Pride and Prejudice§
Author: Jane Austen§ ,
Exactly, you can use a static variable. But instead of increasing it inside the toString() Method id rather increase it in the constructor since your question suggests you want to count the number of objects, not the number of times the toString() method was called on one of your object instances.
public class Book {
private static int i = 0;
public Book(){
i++;
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append("\n\n-Buch"+ i +": ");
result.append("\nTitel: " + this.Titel + "§ ");
result.append("\nAuthor: " + this.Autor + "§ ");
return result.toString();
}
}
Edit: Below comment is correct, this will always print out how many books have been created the time you call the toString() method of any Book object.
Here is a second Version, you now have one variable per object instance identifing the books number according the time it was created and the same static variable from above, look at the sample output.
public class Book {
private static int i = 0;
private int i2;
public Book() {
i2 = i;
i++;
// or place 'i2 = i;' here if you want to start with "Book 1 of..."
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append("Book " + i2 + " of " + i + " books in total");
return result.toString();
}
}
Sample Call:
public class SampleCall{
public static void main(String[] args) {
Book b = new Book();
Book b1 = new Book();
Book b2 = new Book();
Book b3 = new Book();
System.out.println(b1);
System.out.println(b1);
}
}
Sample Output:
Book 0 of 4 books in total
Book 1 of 4 books in total
Since you just started using Java consider a solution where you are setting the number for each Book instance by yourself just for completion:
public class Book {
private static int i = 0;
private int bookNumber;
public Book(int bookNumber) {
i++;
/* this.bookNumber means "the variable of the currently in creation book object instance)
* you only need it if its not clear because there is a local variable with the same name
*/
this.bookNumber = bookNumber;
}
// a second (default) constructor in case you want to create book objects and dont yet know the number of it
// after creation you can use the get/set values to access the variable from "outside"
public Book(){
i++;
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
// Here you dont need this because there is no local variable bookNumber
// You can however always use it when referencing such object variables
result.append("Book " + bookNumber + " of " + i + " books in total");
return result.toString();
}
public int getBookNumber(){
return bookNumber;
}
public void setBookNumber(int bookNumber){
this.bookNumber = bookNumber;
}
}
Sample Call:
public class SumeMain {
public static void main(String[] args) {
Book b = new Book(1);
Book b1 = new Book(2);
Book b2 = new Book();
System.out.println(b);
System.out.println(b1);
//Note below book not yet has a number:
System.out.println("Forgotten book: "+b2);
//But you can set it from "outside" (here)
b2.setBookNumber(3);
System.out.println(b2);
//Also note you now took controll of those numbers so two books can have the same number:
b2.setBookNumber(2);
System.out.println("Duplicate book number: "+b2);
}
}
Sample Output:
Book 1 of 3 books in total
Book 2 of 3 books in total
Forgotten book: Book 0 of 3 books in total
Book 3 of 3 books in total
Duplicate book number: Book 2 of 3 books in total
By such examples i think youre on the best way to learn the language basics, keep up and have fun :)
What you need is to set your i variable as static and class field.
public class Book {
private static int i = 1;
#Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append("\n\n-Book "+ i++ +": ");
result.append("\nTitel: " + this.Titel + "§ ");
result.append("\nAuthor: " + this.Autor + "§ ");
return result.toString();
}
You are calling toString() method on an encapsulated Book object.
It has no knowledge of other Book's in ArrayList.
Try removing those lines from toString() method:
int i = 1;
result.append("\n\n-Book "+ i++ +": ");
And iterate over collection like this:
List<Book> books = ...
for(int i = 0; i < books.size(); i++){
System.out.println("\n\n-Book "+ (i + 1) +": ");
System.out.println(books.get(i));
}
Strange that you know how to use toString() and StringBuilder, but experience problems in iterating collections. Try going back to basic programming techniques.
Also, a lot of answers recommend using a static field. Don't go with that approach. Static fields are not good for this. It won't work in case you have to iterate the collection of books twice.

Categories

Resources