create variable of either data type - java

I need to create a variable of either data type on runtime (via scanner class)
This is what my assignment asked
"A selling arrangement could be an offered price OR an auction date"
This is what i have created but not sure if it is correct..
public class SellingArrangement {
private Object dateOrPrice;
public SellingArrangement()
{
}
public void setDateOrPrice(String price)
{
dateOrPrice = new Object();
dateOrPrice = price;
}
public void setDateOrPrice(Double price)
{
dateOrPrice = new Object();
dateOrPrice = price;
}

I have done something similar before (when an API may return JSON or XML)
However, you have two sets of two choices here - the input can either be a String or a Double, and that input can either represent a Date or a Price.
Instead of using an Object, I would just create two separate fields and populate the correct one using two separate constructors like this.
public class SellingArrangement {
private Date date;
private Price price;
public SellingArrangement(String input)
{
if ( // String is a price ) {
this.price = new Price(input);
}
if ( // String is a date ) {
this.date = new Date(input)
}
}
public SellingArrangement(Double input)
{
if ( // Double is a price ) {
this.price = new Price(input);
}
if ( // Double is a date ) {
this.date = new Date(input)
}
}
}
Of course, I am assuming you can figure out some way to validate whether the String or Double you are getting as input is a date or a price, and that you have constructors which will take a String / Double for each type. Treat this as pseudocode...
However as others have mentioned in comments if you dont have to do this with a single class, it would be better to use another method entirely...

Related

Java calling an object without using parameters [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am new to programming. I have made this constructor:
public Attraction(int baseprice, String name) {
this.baseprice = baseprice;
this.name = name;
}
I have initialized the constructor in a different class:
Attraction attraction = new Attraction(ridename, price)
I would like to use this data in a third class without having to pass in parameters, so it would look like this:
Attraction attraction = new Attraction()
This would then allow me to use getters and setters to change the existing data in the attraction object. However, this is not possible at the moment because I have to pass in the name and price even though I want to use the existing data.
Can anyone show me what to do? Any help would be appreciated.
You seem to misunderstand how java works.
The new name of the keyword to make new objects wasn't chosen at random: Every time you write new Attraction([doesn't matter what goes here]), a well, new object is made (this object is then 'an instance' of Attraction). Each individual object has its own set of the fields. There is also no 'one instance to rule them all' - there is no way to just go: "Give me the instance I created last" or "Give me the one instance; I never want more than one to exist".
You need to pass the reference around:
Attraction a = new Attraction(ridename, price);
... do stuff
someOtherMethod(a); // pass 'a' around via a parameter, or...
return a; // pass 'a' around by returning it, or...
this.someFieldOfTypeAttaction = a; // pass 'a' around by assigning it to a field.
many ways to do it.
You can also program 'give me the attraction I created last' or even 'there will only ever be a single attraction', but this doesn't sound right here: Surely you are planning to have many different attractions, and in general having global mutable state leads to spaghetti code that is hard to debug and which is prone to failure.
I assume you have a class like below
public static class Attraction {
private String ride;
private int price;
public Attraction(String ride, int price) {
this.ride = ride;
this.price = price;
}
public String getRide() {
return ride;
}
public void setRide(String ride) {
this.ride = ride;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
So to create the class Attraction you need to pass two arguments. if you want to create an object without data and later you want to update it, you can make use of default constructor and later you can update the values of the object. like below
public static class Attraction {
private String ride;
private int price;
public Attraction(String ride, int price) {
this.ride = ride;
this.price = price;
}
// this is a default construtor
public Attraction(){
this("", 0); // pass a default values for the object.
}
public String getRide() {
return ride;
}
public void setRide(String ride) {
this.ride = ride;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
later you can create object of Attraction with or without passing argument parameters.
Attraction attraction = new Attraction() //will create the object with emptyString and 0
attraction.setRide("Your ride"); //sets ride
attraction.setPrice(1233); // sets price
attraction.getRide(); //gives the value of ride
attraction.getPrice(); // gives the price of the ride
Or You can create with argument data.
Attraction attraction = new Attraction("myRide", 20) //will create the object with value passed.
attraction.setRide("Your ride"); //sets ride
attraction.setPrice(1233); // sets price
attraction.getRide(); //gives the value of ride
attraction.getPrice(); // gives the price of the ride

No suitable constructor found for book error?

Hi sorry beginner coder here and I am not good at explaining things but I needed help and was wondering why I keep getting this error no matter how I format or rearrange the date name and title. so I just was wondering if anyone can help on what order I am suppose put the name dates and titles in? I am using BlueJ compiler.
Here is my code for the issue that I am having:
public BookStore()
{
inventory = new Book[100];
inventory[0] = new Book( "James", "Joyce",2013,1,1, 2013,1,1, 2013,1,1, "ULYSSES");
inventory[1] = new Book(2013, "THE GREAT GATSBY", "F. Scott Fitzgerald");
I keep getting this error no suitable constructor found for Book(java.lang.String,java.lang.String,int,int,int,java.lang.String) constructor Book.Book() is not applicable; (actual and formal arguments list differ in length); constructor Book.Book(Author,Date,java.lang.String) is not applicable (actual and formal argument lists differ in length)
Here is the Book class:
private static final String DEFAULT_TITLE = "Untitled";
private Author author;
private Date published;
private String title;
public Book()
{
this.author = new Author();
this.published = new Date();
this.title = DEFAULT_TITLE;
} // end constructor
public Book(Author author, Date published, String title)
{
setAuthor(author);
setDatePublished(published);
setTitle(title);
} // end constructor
public Author getAuthor()
{
return author;
} // end accessor
public Date getDatePublished()
{
return published;
} // end accessor
public String getTitle()
{
return title;
} // end accessor
public void setAuthor(Author author)
{
this.author = (null == author ? new Author() : author);
} // end accessor
public void setDatePublished(Date published)
{
this.published = (null == published ? new Date() : published);
} // end accessor
public void setTitle(String title)
{
this.title = (null == title ? DEFAULT_TITLE : title);
} // end accessor
public String getAuthorName()
{
return author.getName().getFullName();
} // end method
public String getDayOfTheWeekBookWasPublished()
{
return published.getDayOfTheWeek();
} // end method
public void printDetails()
{
System.out.print(getAuthorName());
System.out.print("(");
System.out.print(author.getName().getInitials());
System.out.print(") wrote ");
System.out.print(title);
System.out.print(" on ");
System.out.print(getDayOfTheWeekBookWasPublished());
System.out.print(", ");
System.out.print(Date.getMonthName(published.getMonth()));
System.out.print(" ");
System.out.print(published.getDay());
System.out.print(", ");
System.out.print(published.getYear());
Name pseudonym = author.getPseudonym();
if (null != pseudonym)
{
System.out.print(", under the pseudonym ");
System.out.print(pseudonym.getFullName());
}
System.out.println();
} // end method
} // end class
When you want to create a Book object, you need to use one of the defined constructors. You have two options:
public Book()
public Book(Author author, Date published, String title)
The first one creates a book with a default author, date and title. The second one receives them as parameters. Assuming the second one is the one you need, you now know:
You need to call new Book(...) with three arguments. Not more, not less.
The first argument has to be an object of type Author. Not a string, not a number, an Author.
The second argument needs to be a Date object.
The third argument needs to be a String.
Now, here is your call:
new Book( "James", "Joyce",2013,1,1, 2013,1,1, 2013,1,1, "ULYSSES");
In this call, you pass twelve arguments! And they are just strings and numbers, not an Author, a Date and a String.
So, you need to create an Author object and a Date object and pass those. For example:
Author bookAuthor = new Author(...);
Date bookDate = new Date(...);
inventory[0] = new Book( bookAuthor, bookDate, "Ulysses" );
You can do the same without the extra variables:
inventory[0] = new Book( new Author(...), new Date(...), "Ulysses" );
Now, you should apply the same logic to the new Author(...) and new Date(...) calls.
Check which constructors you have in your code.
Find which one is the most suitable for the object you want to create.
Pass it the exact number of arguments of the exact type that is defined. If you need, use a call to new ... to create an object of the required type.

How do I create an object from another class (BlueJ)

I am making a program that simulates a Store and a Member. I am trying to write a method, memberRegister2(). This method is the the Store class but calls the constructor from the Member class to make a member object. This method is to be passed the name, id and pinNumber as parameters and then creates the Member object, which is to be stored in a local variable 'member'. I have no idea how to do this. As you will see from the code below I have tried to use the 'Member member = new Member()' But i do not know how to make the parameters user input.
(P.S I am using BlueJ)
Here is my code for both classes hopefully making my question make more sense. I am very new to java so excuse bad coding.
public class Store
{
// instance variables
private String storeName;
private int total;
//Member member;
/**
* Constructor for objects of class Store
*/
public Store(String newStoreName, int newTotal)
{
// initialise instance variables
storeName = newStoreName;
total = newTotal;
}
//Accessor Methods
public String getStoreName()
{
return storeName;
}
public int getTotal()
{
return total;
}
public void memberRegister1(Member newMember)
{
System.out.println("Salford Thrifty " + storeName + ": Welcome " + newMember.getName() + " (id:" + newMember.getId() + ")" );
}
public void memberRegister2()
{
//Member member = new member(memberName, memberId, memberPinNumber);
}
//Mutator Methods
public void newStoreName(String newName)
{
storeName = newName;
}
public void newTotal(int newTotal)
{
total = newTotal;
}
}
and the Member class
public class Member
{
// instance variables
private String name;
private String id;
private String pinNumber;
/**
* Constructor for objects of class Member
*/
public Member(String memberName, String memberId, String memberPinNumber)
{
// initialise instance variables
name = memberName;
id = memberId;
pinNumber = memberPinNumber;
}
public Member()
{
// initialise instance variables
name = "Bob";
id = "ASD123";
pinNumber = "5678";
}
//Accessor Methods
public String getName()
{
return name;
}
public String getId()
{
return id;
}
public String getPinNumber()
{
return pinNumber;
}
//Mutator Methods
public void newName(String newMemberName)
{
name = newMemberName;
}
public void newId(String newMemberId)
{
name = newMemberId;
}
public void newPinNumber(String newMemberPinNumber)
{
name = newMemberPinNumber;
}
}
I have been told to keep the variable at the top private and use pointers? Not sure what this means but it has not been explained to me very well.
You can a Scanner to read the user's input like so.
Scanner s = new Scanner(System.in);
String userInput = s.nextLine();
Then just initialize your member instance using the strings entered by the user.
String memberName, memberId, memberPin;
Scanner s = new Scanner(System.in);
System.out.println("Enter a name");
memberName = s.nextLine();
System.out.println("Enter an id");
memberId = s.nextLine();
System.out.println("Enter a pin");
memberPin = s.nextLine();
Member m = new Member(memberName, memberId, memberPin);
Also, you probably want to make pin, and maybe the id ints instead of strings.
Here's something I have from an old class that should show you how:
SavingsAccount myAccount = new SavingsAccount(200, 5);
So when you want to create an object from another class you have to use that second class to initialize it as shown above the SavingsAccount is like int it instantiates the object and then the two integers SavingsAccount(200, 5); is used because the method within the second class is instantiated with two integers of its own so the object you are creating must have two integers of its own. And what I mean by the method has two integer instantiated is as shown in the code below:
public SavingsAccount(double amount, double rate)
{
super(amount);
interestRate = rate;
}
if you do not instantiate a method with two objects within the parentheses then you do not need them within:
SavingsAccount myAccount = new SavingsAccount(200, 5);
I hope this helps any with your question i'm fairly new myself and am trying to help with as much as I can My course uses BlueJ as well and I know a good bit about BlueJ so I hope this helps.

Javafx: Retrieve observableList individual elements from ScheduledService and bind them individually to different properties

I am trying to scrape google finance. The getStockInfoFromGoogle method stores two strings: (1) stock Name and (2) closing price into an ObservableList<String>. This works fine.
Then I tried to run this method in the background using ScheduledService and thus, priceService should return an ObservableList<String>.
Problem occurs when I try to retrieve the ObservableList<String> from ScheduledService method, as I am not able to individually extract the strings from the list and associate them with the lastValueProperty() and bind that to the closingPrice property.
How should I solve this problem? (I want to retain lastValueProperty() here).
public class Trade{
private final ReadOnlyStringWrapper stockName;
private final ReadOnlyDoubleWrapper closingPrice;
private final ScheduledService<ObservableList<String>> priceService = new ScheduledService<ObservableList<String>>() {
#Override
public Task<ObservableList<String>> createTask(){
return new Task<ObservableList<String>>() {
#Override
public Number call() throws InterruptedException, IOException {
return getStockInfoFromGoogle();
}
};
}
};
// constructor
public Trade(){
priceService.setPeriod(Duration.seconds(100));
priceService.setOnFailed(e -> priceService.getException().printStackTrace());
this.closingPrice = new ReadOnlyDoubleWrapper(0);
this.stockName = new ReadOnlyStringWrapper("");
// this is the part where things goes wrong for the two properties below
this.closingPrice.bind(Double.parseDouble(priceService.lastValueProperty().get().get(1)));
this.stockName.bind(priceService.lastValueProperty().get().get(0));
}
public ObservableList<String> getStockInfoFromGoogle() throws InterruptedException, IOException{
ObservableList<String> output = FXCollections.observableArrayList();
// do some web scraping
output.add(googleStockName);
output.add(googleClosingPrice);
return output;
}
Your design looks pretty confused, as the Trade class seems to be both encapsulating a trade (name and price) but also seems to be managing the service (which just updates a single trade?).
Anyway, using a List here is not the way to go, you should create a class to encapsulate the data you get back from the service:
class TradeInfo {
private final String name ;
private final double price ;
public TradeInfo(String name, double price) {
this.name = name ;
this.price = price ;
}
public String getName() {
return name ;
}
public double getPrice() {
return price ;
}
}
Now make your ScheduledService a ScheduledService<TradeInfo>, etc, and you can do
public TradeInfo getStockInfoFromGoogle() throws InterruptedException, IOException{
// do some web scraping
return new TradeInfo(googleStockName, googleClosingPrice);
}
Now create the bindings:
this.closingPrice.bind(Bindings.createDoubleBinding(() ->
priceService.getLastValue().getPrice(),
priceService.lastValueProperty());
this.stockName.bind(Bindings.createStringBinding(() ->
priceService.getLastValue().getName(),
priceService.lastValueProperty());
(You may need to deal with the case where priceService.getLastValue() is null.)

Calling Set / Get Methods from another Class and .java file

Alright, I'm trying to call setters and getters from another function that's inside another class, in another file. Here's what I'm getting, and I really don't know what I'm doing wrong...
Bank.java
package Bank;
import java.io.*;
import java.util.*;
public class Bank
{
public static void main (String args[]) throws FileNotFoundException
{
final String fileName = "Bank/AcctInfo.txt";
File accounts = new File(fileName);
ArrayList <Object> acctInfo = new ArrayList <Object> ();
acctInfo = setObjects(accounts);
}
public static ArrayList setObjects(File document) throws FileNotFoundException
{
ArrayList <Object> objectArray = new ArrayList <Object> ();
Scanner fileInput = new Scanner(document);
String blankInfo;
String accountType;
String customerType;
String customerName;
int accountNumber;
float balance;
int counter = 0;
while (fileInput.hasNext())
{
accountNumber = fileInput.nextInt();
blankInfo = fileInput.nextLine();
accountType = fileInput.nextLine();
customerName = fileInput.nextLine();
customerType = fileInput.nextLine();
balance = fileInput.nextFloat();
blankInfo = fileInput.nextLine();
objectArray.add(new BankAccount());
objectArray.get(counter).setAccNumber(accountNumber);
counter++;
}
return objectArray;
}
}
BankAccount.java
package Bank;
public class BankAccount extends Bank
{
private int accNumber;
private String accType;
private String cusName;
private String cusType;
private float bal;
public void setAccNumber(int accountNumber)
{
int accNumber = accountNumber;
}
public int getAccNumber()
{
return accNumber;
}
public void setAccType(String accountType)
{
String accType = accountType;
}
public String getAccType()
{
return accType;
}
public void setCusName(String customerName)
{
String cusName = customerName;
}
public String getCusName()
{
return cusName;
}
public void setCusType(String customerType)
{
String cusType = customerType;
}
public String getCusType()
{
return cusType;
}
public void setBal(float balance)
{
float bal = balance;
}
public float getBal()
{
return bal;
}
}
Errors:
Bank.java:51: error: cannot find symbol
objectArray.get(counter).setAccNumber(accountNumber);
^
symbol: method setAccNumber(int)
location: class Object
Note: .\Bank\Bank.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error
It's not completed yet, but if someone can help me through that bit, it'd be a huge help...
Instead of ArrayList<Object>, use ArrayList<BankAccount>.
Object is a class that doesn't have a method with the signature setAccNumber(int) whereas BankAccount does.
The ArrayList<Object> declaration says that you're declaring an ArrayList that will have Objects inside it; since all classes inherit from Object, putting instances of BankAccount in the list is valid, but as far as the compiler is concerned, when you refer to an element inside the list, it's an Object and only has the standard methods available to Object.
There are other peculiarities in your class too (e.g. in your setter methods, you declare a new variable and assign to it, inside of assigning it to a field). I would recommend revisiting your course lecture notes if available. There's an online free PDF called Java Precisely which is a very concise look at Java - the free version is up to Java 5 I think, but it's enough to cover the topics here.
Because you're doing this:
ArrayList <Object> objectArray = new ArrayList <Object> ();
the list there doesn't know what the things inside are, because you said they are Object.
if you make that
ArrayList <BankAccount> objectArray = new ArrayList <BankAccount> ();
it should work like you expect.
If you want to use the methods of BankAccount on the items of your ArrayList, you have to specify that it is a list of BankAccounts. Speficically, the line
ArrayList <Object> objectArray = new ArrayList <Object> ();
should really be
ArrayList <BankAccount> objectArray = new ArrayList <BankAccount>();
You can think of generics as specifying what you have a list of. So for the first example, you can read it as "An ArrayList of Objects." Since you don't know if they are BankAccounts or not, you don't know if you can call settAccNumber() on them.
For the second example, you can read it as "An ArrayList of BankAccounts." In this case you know that they are BankAccounts, so you know that you can call setAccNumber() on them.
Here's a lesson on generics, since you don't seem to quite have the hang of them.
Here's the oracle documentation on them as well.
Other answers correctly suggest using ArrayList<BankAccount>
If (for whatever strange reason) you cannot or do not want to do it, then you need to implicitly cast the retrieved list element to BankAccount type.
Your
objectArray.get(counter).setAccNumber(accountNumber);
will become
((BankAccount)objectArray.get(counter)).setAccNumber(accountNumber);

Categories