I am sure this is something stupid, but I can't figure it out for the life of me.... In the main method, when I am trying to create new artists, I keep getting an error on the creating a new "Recording" line (ie: surfacing and pop). It is saying it requires String, String[] but is getting String, MusicCollection.Artist. And it says "actual argument MusicCollection.Artist cannot be converted to String[] by method invocation conversion.
public class MusicCollection {
private Artist[] artists = new Artist[100];
private Recording[] recordings = new Recording[200];
private int artistCount = 0;
private int recordingCount = 0;
//toString method for MusicCollection
public String toString() {
StringBuffer sb = new StringBuffer();
if (recordingCount > 0) {
sb.append(recordings[0].toString());
for (int i = 1; i < recordingCount; i++) {
sb.append("\n" + recordings[i]);
}
}
return sb.toString();
}
public class Artist {
private String name;
/**
* Construct an artist object and add it to the collection.
*
* #param name the name of the Artist
*/
public Artist(String name) {
this.name = name;
artists[artistCount++] = this;
}
/**
* Retrieve the artist as a string
*
* #return the string representation of the artist
*/
public String toString() {
return name;
}
}
public class Recording {
private String name;
private Artist[] artists = new Artist[100];
private Track[] tracks = new Track[200];
private int trackCount = 0;
public class Track {
private String name;
/**
* Construct track object and add it to the collection.
*
* #param name the name of the track
*/
public Track(String name) {
this.name = name;
tracks[trackCount++] = this;
}
/**
* Retrieve the track as a string
*
* #return the string representation of the track
*/
public String toString() {
return name;
}
}
public Recording(String name, String Artist[]) {
this.name = name;
this.artists = artists;
recordings[recordingCount++] = this;
}
public String toString() {
StringBuffer sb = new StringBuffer(name);
sb.append(" by " + artists + ": ");
if (trackCount > 0) {
sb.append(tracks[0].toString());
for (int i = 1; i < trackCount; i++) {
sb.append(", " + tracks[i]);
}
}
return sb.toString();
}
}
public static void main(String[] args) {
MusicCollection mc = new MusicCollection();
Artist sarahM = mc.new Artist("Sarah McLachlan");
Recording surfacing = mc.new Recording("Surfacing", sarahM);
Recording.Track surfacing1 = surfacing.new Track("Building a Mystery");
Recording.Track surfacing4 = surfacing.new Track("Adia");
Artist u2 = mc.new Artist("U2");
Recording pop = mc.new Recording("Pop", u2);
Recording.Track pop1 = pop.new Track("Discotheque");
Recording.Track pop5 = pop.new Track("Miami");
System.out.println(mc);
}
}
Needed to have:
public Recording(String name, Artist someArtist)
and in my Recording class, only have:
private Artist artist;
since I had already declared Artist as an array.
I also had to change this.artists = artists; to this.artists = someArtist;, since that was the variable I am passing. Worked like a charm after!
Related
Ok so heres the thing I am working with an api that for one JSON parameter can return two different types. So I can receive from the server either a JSON Object or a String. I'm pretty new to Android development so if someone could explain to me with maybe a code example how I can handle that problem.
Example json responses {video:"ID OF VIDEO"} or {video:{id:"ID OF VIDEO",...extra data}}. I had a look at custom deserialisers but can't find an example that is easy to follow. There must be a simple way of solving my problem. Currently I receive error "Expected string but found BEGIN OBJECT"
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class MyNotification {
#SerializedName("_id")
#Expose
private String Id;
#SerializedName("comment")
#Expose
private String comment;
#SerializedName("createdAt")
#Expose
private String createdAt;
#SerializedName("message")
#Expose
private String message;
#SerializedName("read")
#Expose
private Boolean read;
#SerializedName("recipient")
#Expose
private String recipient;
#SerializedName("sender")
#Expose
private User sender;
#SerializedName("type")
#Expose
private String type;
// #SerializedName("video")
// #Expose
// private String video;
/**
*
* #return
* The Id
*/
public String getId() {
return Id;
}
/**
*
* #param Id
* The _id
*/
public void setId(String Id) {
this.Id = Id;
}
/**
*
* #return
* The comment
*/
public String getComment() {
return comment;
}
/**
*
* #param comment
* The comment
*/
public void setComment(String comment) {
this.comment = comment;
}
/**
*
* #return
* The createdAt
*/
public String getCreatedAt() {
return createdAt;
}
/**
*
* #param createdAt
* The createdAt
*/
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
/**
*
* #return
* The message
*/
public String getMessage() {
return message;
}
/**
*
* #param message
* The message
*/
public void setMessage(String message) {
this.message = message;
}
/**
*
* #return
* The read
*/
public Boolean getRead() {
return read;
}
/**
*
* #param read
* The read
*/
public void setRead(Boolean read) {
this.read = read;
}
/**
*
* #return
* The recipient
*/
public String getRecipient() {
return recipient;
}
/**
*
* #param recipient
* The recipient
*/
public void setRecipient(String recipient) {
this.recipient = recipient;
}
/**
*
* #return
* The sender
*/
public User getSender() {
return sender;
}
/**
*
* #param sender
* The sender
*/
public void setSender(User sender) {
this.sender = sender;
}
/**
*
* #return
* The type
*/
public String getType() {
return type;
}
/**
*
* #param type
* The type
*/
public void setType(String type) {
this.type = type;
}
// /**
// *
// * #return
// * The video
// */
// public String getVideo() {
// return video;
// }
//
// /**
// *
// * #param video
// * The video
// */
// public void setVideo(String video) {
// this.video = video;
// }
}
and the part that craps out
Gson gson = new Gson();
String jsonString = String.valueOf(dataset);
Type listType = new TypeToken<List<MyNotification>>(){}.getType();
notficationsList = (List<MyNotification>) gson.fromJson(jsonString, listType);
Sorry it took so long:
Your best bet is to repair the JSON, if you must map it to an Object.
Try cleaning the JSON with this code:
public static String cleanJson(String json) {
int videoPos = json.indexOf("video");
if(videoPos == -1) {
return json; //return, no video here
}
boolean isObject = false;
int objectBegin = -1;
String cleanedJson = json.replaceAll("\\\"", "\\\\");
for(int i = videoPos; i < cleanedJson.length(); i++) {
if(cleanedJson.charAt(i) == '"') {
System.out.println("string");
return json; // its a string anyway
}
if(cleanedJson.charAt(i) == '{') {
//its an object
// i now is the position beginning the object
objectBegin = i;
}
} //replace " with space
if(objectBegin == -1) {// we did not find any { or " it is a string
return json;
}
boolean inString = false;
int objectEnd = -1;
for(int i = objectBegin; i < cleanedJson.length(); i++) {
//looking for the end of the object;
if(cleanedJson.charAt(i) == '"') inString = !inString;
if(cleanedJson.charAt(i) == '}') {
objectEnd = i;
break;
}
}
if(objectEnd != -1) {
String start = json.substring(0,objectBegin);
String videoPart = json.substring(objectBegin, objectEnd+1);
String end = json.substring(objectEnd+1);
// now we want to get the id
String newVideoPart = "";
int idStart = videoPart.indexOf("id");
int idStringStart = -1;
int idStringEnd = -1;
for(int i = idStart; i < videoPart.length(); i++) {
if(videoPart.charAt(i) == '"') {
if(idStringStart == -1) {
idStringStart = i;
} else {
idStringEnd = i;
break;
}
}
}
if(idStringStart != -1 && idStringEnd != -1) {
newVideoPart = videoPart.substring(idStringStart, idStringEnd+1);
}
return start+newVideoPart+end;
}
return json;
}
Works with these two test jsons:
System.out.println(cleanJson("{video:\"1234\"}"));
System.out.println(cleanJson("{video:{id:\"2345\", name=\"test\"}}"));
Try it like this:
notficationsList = (List<MyNotification>) gson.fromJson(cleanJson(jsonString), listType);
Ok so the solution I went with I wrote my own type adapter that gson allow you to use
public class Helper_StringAdapter extends TypeAdapter<String>{
#Override
public String read(com.google.gson.stream.JsonReader in) throws IOException {
if(in.peek() == JsonToken.NULL){
in.nextNull();
return null;
}else if(in.peek() == JsonToken.BEGIN_OBJECT && in.getPath().contains(".video")){
L.e("VIDEO IS AN OBJECT!");
String userId = readAndReturnVideoId(in);
return userId;
}else{
return in.nextString();
}
}
private String readAndReturnVideoId(com.google.gson.stream.JsonReader reader) throws IOException{
String id = "";
reader.beginObject();
while(reader.hasNext()){
String name = reader.nextName();
if(name.equals("_id")){
id = reader.nextString();
}else{
reader.skipValue();
}
}
reader.endObject();
L.e("READ ID RETURNED"+id);
return id;
}
#Override
public void write(com.google.gson.stream.JsonWriter out, String value) throws IOException {
L.e("TEST "+out);
}
}
Then in my activity data manager (Recyclerview Adapter)
public void updateData (JSONArray dataset) {
GsonBuilder gsonb = new GsonBuilder();
gsonb.registerTypeAdapter(String.class,new Helper_StringAdapter());
Gson gson = gsonb.create();
String jsonString = String.valueOf(dataset);
Type listType = new TypeToken<List<FrameNotification>>(){}.getType();
notficationsList = (List<FrameNotification>) gson.fromJson(jsonString, listType);
}
Seems to do the job
For my assignment I have created a class called Agency which will store data about talent agencies and i have created the required attributes. I've also been given a data file which i will need to read from. But first i am to test my class. I can use the getter and setters fine to display my desired output but now I want to create new instance of object Agency and add the details their but i get an error message saying no suitable constructor found. I have matched the settings to my constructor or at least can't see where my mistake is. Any help thanks.
public class Agency {
//Attributes for class Agency
private String name;
private String[] address;
private String[] adminStaff;
private int phoneNumber;
private String type;
/**
*Constructor that creates object Agency
*/
public Agency() {
}
/**
* Constructor that creates object Agency with values
* #param name
* #param address
* #param adminStaff
* #param phoneNumber
* #param type
*/
public Agency(String name, String[] address, String[] adminStaff, int phoneNumber, String type) {
this.name = name;
this.address = address;
this.adminStaff = adminStaff;
this.phoneNumber = phoneNumber;
this.type = type;
}
/**
*
* #return
*/
public String getName() {
return name;
}
/**
*
* #param name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* #return
*/
public String[] getAddress() {
return address;
}
/**
*
* #return
*/
public String[] getAdminStaff() {
return adminStaff;
}
/**
*
* #return
*/
public int getPhoneNumber() {
return phoneNumber;
}
/**
*
* #param phoneNumber
*/
public void setPhoneNumber(int phoneNumber) {
this.phoneNumber = phoneNumber;
}
/**
*
* #return
*/
public String getType() {
return type;
}
/**
*
* #param type
*/
public void setType(String type) {
this.type = type;
}
private String getArrayAsString(String[] a) {
String result = "";
/*for(int i = 0; i<a.length; i++)
{
result += a[i] +" ";
}*/
for(String s: a)
{
result += s + " ";
}
result = result.trim();
return result;
}
private String[] getStringAsArray(String a) {
String[] result = a.split(":");
return result;
}
public void setAddress(String Address) {
this.address = getStringAsArray(Address);
}
public void setAddress(String[] Address) {
this.address = Address;
}
public String getAddressAsString() {
return getArrayAsString(address);
}
public void setAdminStaff(String adminStaff) {
this.adminStaff = getStringAsArray(adminStaff);
}
public void setAdminStaff(String[] adminStaff) {
this.adminStaff = adminStaff;
}
public String getAdminStaffAsString() {
return getArrayAsString(adminStaff);
}
#Override
public String toString(){
return name +"\t"+ getAddressAsString() +"\t"+
getAdminStaffAsString() +"\t"+ phoneNumber +"\t"+ type + "\n";
}
}
My main Class
public class AgencyTest {
public static void main(String[] args) {
/*a.setName("Potters Talent Agency");
a.setAddress("126-182 Ashwood Road:Potters Bar:Hertfordshire EN6 2:UK");
a.setAdminStaff("Megan Speagle:Daron Spilman");
a.setPhoneNumber(2598052);
a.setType("All");
System.out.println(a.getName());
System.out.println(a.getAddressAsString());
System.out.println(a.getAdminStaffAsString());
System.out.println(a.getPhoneNumber());
System.out.println(a.getType());*/
Agency a = new Agency("Potters Talent Agency, 126-182 Ashwood Rd: Potters Bar: Hertfordshire EN6 2: UK, "
+ "Megan Speegle:Daron Spilman:Leonel Striegel:Hubert Tesoro:Nathanial Pompey, 2598052, All");
System.out.println(a);
}
}
Commented out lines work but if i try to do it all from the 'Agency a = new Agency()' line it won't work.
plz help am a novice and am probably using bad terminology so not sure if it makes sense what im trying to do.
Ok added a new constructor which takes it as one string but get an error with integer value for phonenumber.
Here's the code:
`public Agency(String csvString) {
String[] attributes =csvString.split(",");
int i = 0;
for(String s : attributes)
{
switch(i)
{
case 0:
this.name = s;
break;
case 1:
this.address = getStringAsArray(s);
break;
case 2:
this.adminStaff = getStringAsArray(s);
break;
case 3:
this.phoneNumber = getIntAsString(s);
break;
case 4:
this.type = s;
break;
}
I have tried to convert it to string but doesn't seem to work.
More Code:
private String getIntAsString(int a){
String result = Integer.toString(a);
return result;
}
public String getPhoneNumberAsString() {
return getIntAsString(phoneNumber);
}
public void setPhoneNumber(int phoneNumber){
this.phoneNumber = phoneNumber;
}
i++;
}`
Agency a = new Agency("Potters Talent Agency ... EN6 2: UK, "
+ "Megan Speegle:Daron ... 2598052, All");
is trying to call a constructor with a single string and no such constructor exists.
You need to either provide such a constructor (which will split the string into its component fields), or split the string yourself and call the current constructor with those component fields.
In the line
Agency a = new Agency("Potters [...] All");
you are basically calling a constructor that takes a single string as its argument. So the compiler is looking for such a constructor:
Agency(String properties) { ... }
This constructor does not exist. Instead you have a constructor
Agency(String name, String[] address, String[] adminStaff, int phoneNumber, String type) { ... }
which takes the arguments separately. So you must call it like so:
Agency a = new Agency(
"Potters Talent Agency",
new String[] {"126-182 Ashwood Rd", "Potters Bar", "Hertfordshire EN6 2", "UK"},
new String[] {"Megan Speegle", "Daron Spilman", "Leonel Striegel", "Hubert Tesoro", "Nathanial Pompey"},
2598052,
"All"
);
You could - alternatively - provide a constructor taking a single string, which then does some string magic to disassemble the parts. This is somewhat complex and error-prone, so I would advise not to do so.
See error is in
Agency a = new Agency("Potters Talent Agency, 126-182 Ashwood Rd: Potters Bar: Hertfordshire EN6 2: UK, "
+ "Megan Speegle:Daron Spilman:Leonel Striegel:Hubert Tesoro:Nathanial Pompey, 2598052, All");
You are simply passing one string to the constructor and there is no constructor in your class which accepts the only string as parameter.
So form your parameters properly.
Try to create object this way
String myAddress[] = "BLR India".split(" ");
String myAdmin[] = "my admin array".split(" ");
Agency a = new Agency("MyName", myAddress, myAdmin, 1235678, "myType");
You are using wrong constructor. What you have now is
Agency a = new Agency("Potters Talent Agency, 126-182 Ashwood Rd: Potters Bar: Hertfordshire EN6 2: UK, "
+ "Megan Speegle:Daron Spilman:Leonel Striegel:Hubert Tesoro:Nathanial Pompey, 2598052, All");
So it will expect a constructor with just single string argument which you don't have.
You should do something like
List<String> addr = new ArrayList<String>();
addr.add("126-182 Ashwood Rd");
addr.add("Potters bar");
addr.add("Hertfordshire EN6 2");
addr.add("UK");
List<String> adminStaff = new ArrayList<String>();
adminStaff.add("Megan Speegle");
adminStaff.add("Daron Spilman");
agency a = new Agency("Potters Talent Agency", addr.toArray(), adminStaff.toArray(),2598052, "All");
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have looked on here and spent some time on this and now I have hit a brick wall.
I am wokring on the Parking Ticket simulator in Java.
I am not very good at Java, but seem to have most of it working.
The only problem is that I put in a demo/test file and it gives me the same answer all the time. Even with ridiculous values.
Can someone point me in the right direction on how to resolve this?
Thanks, All the code is below:
/**
* #(#)ParkedCar.java
*
* ParkedCar application
*
*
* #version 3.00 2014/2/9
*/
public class ParkedCar
{
//Define Variables
private String CarMake;
private String CarModel;
private String CarColour;
private String CarLicensePlate;
private static int NumberOfMinutesParked;
//Define Constructors
// NO ARGUMENT CONSTRUCTOR
// Set Vaules to Zero or null
public ParkedCar()
{
CarMake = " ";
CarModel = " ";
CarColour = " ";
CarLicensePlate = " ";
NumberOfMinutesParked = 0;
}
// CONSTRUCTOR WHICH ACCEPTS AN INPUT
public ParkedCar(String Make,String Model,String Colour,String Reg, int NoMinsPkd)
{
CarMake = Make;
CarModel = Model;
CarColour = Colour;
CarLicensePlate = Reg;
NumberOfMinutesParked = NoMinsPkd;
}
// Use the SET Method
// Set the variables - no needed
public void setMake(String Make)
{
CarMake = Make;
}
public void setModel(String Model)
{
CarModel = Model;
}
public void setColour(String Colour)
{
CarColour = Colour;
}
public void setReg(String Reg)
{
CarLicensePlate = Reg;
}
public void setNoMinsPkd(int NoMinsPkd)
{
NumberOfMinutesParked = NoMinsPkd;
}
// USE THE GET METHODS
// Get the Variables - used to read in values
public String getMake()
{
return CarMake;
}
public String getModel()
{
return CarModel;
}
public String getColour()
{
return CarColour;
}
public String getReg()
{
return CarLicensePlate;
}
public static int getNoMinsPkd()
{
return NumberOfMinutesParked;
}
// USE THE TO STRING METHODS
// Output to a Sting
public String toString()
{
String PkdCar = "Make: " + CarMake
+ "\nModel: " + CarModel
+ "\nColor: " + CarColour
+ "\nLicense Plate: " + CarLicensePlate;
return PkdCar;
}
}
Then
/**
* #(#)ParkingMeter.java
*
* ParkedCar application
*
*
* #version 4.00 2014/2/9
*/
public class ParkingMeter
{
//Define Variables
private static int MinsPurchsed;
//Define Constructors
// NO ARGUMENT CONSTRUCTOR
// Set Vaules to Zero or null
public ParkingMeter()
{
// MinsPurchsed = 0;
}
// CONSTRUCTOR WHICH ACCEPTS AN INPUT
public ParkingMeter(int Purchased)
{
MinsPurchsed = Purchased;
}
// Use the SET Method
// Set the variables - not needed
public void setPurchased(int Purchased)
{
MinsPurchsed = Purchased;
}
// USE THE GET METHODS
// Get the Variables
public static int getPurchased()
{
return MinsPurchsed;
}
// USE THE TO STRING METHODS
// Output to a Sting
public String toString()
{
String MeterString = "Minutes Purchased: " + MinsPurchsed;
return MeterString;
}
}
Then
/**
* #(#)GardaOfficer.java
*
* ParkedCar application
*
*
* #version 3.00 2014/2/9
* #version 4.50 2014/4/13
*/
public class GardaOfficer //extends ParkedCar
{
// Define all the variables
//==========================
private String Name;
private String BadgeNumber;
private double Ticket;
// Constructor to accept all the variables
//========================================
public GardaOfficer(String n, String num)
{
Name = n;
BadgeNumber = num;
}
// NO ARGUMENT CONSTRUCTOR
//========================
public GardaOfficer()
{
Name = "";
BadgeNumber = "";
}
// SET METHODS
//===============
public void setName(String n)
{
Name = n;
}
public void setBadgeNumber(String num)
{
BadgeNumber = num;
}
// GET METHODS
//===============
public String getName()
{
return Name;
}
public String getBadgeNumber()
{
return BadgeNumber;
}
// TO STRING METHOD
//=================
public String toString()
{
String GardaString = "Garda : " + this.Name
+ "\nBadge: " + BadgeNumber
+ "\nTicket: " + Ticket;
return GardaString;
}
public ParkingTicket search(ParkedCar car, ParkingMeter meter)
{
GardaOfficer Garda = new GardaOfficer(this.Name,this.BadgeNumber);
int time = ParkedCar.getNoMinsPkd() - ParkingMeter.getPurchased();
if(ParkedCar.getNoMinsPkd() > ParkingMeter.getPurchased())
{
if(time <= 60)
{
Ticket = 50;
}
else
{
Ticket = 50 + (10 * (time/60));
}
}
if(time <0)
return null;
return new ParkingTicket(car, Garda, getTicket(), time);
}
public double getTicket()
{
return Ticket;
}
public void setTicket(double ticket)
{
this.Ticket = Ticket;
}
}
Then
/**
* #(#)ParkingTicket.java
*
* ParkedCar application
*
*
* #version 4.00 2014/2/9
*/
public class ParkingTicket
{
//Define Variables
private ParkedCar Vehicle;
private GardaOfficer GuardString;
private double ParkingFine;
private int Minutes;
private double firstFine = 50;
private double moreFine = 50;
public ParkingTicket()
{
}
// CONSTRUCTOR WHICH ACCEPTS AN INPUT
public ParkingTicket(ParkedCar car, GardaOfficer Guard, double guyFine, int mins)
{
Vehicle = car;
GuardString = Guard;
ParkingFine = guyFine;
Minutes = mins;
}
// Use the SET Method
// Set the variables - not needed
// USE THE GET METHODS
// Get the Variables
public void getTotalFine()
{
int time = ParkedCar.getNoMinsPkd() - ParkingMeter.getPurchased();
if (time <= 60)
{
ParkingFine = firstFine;
}
else
{
ParkingFine = firstFine + moreFine * (time / 60);
}
}
public double getFirstFine()
{
return firstFine;
}
public double getMoreFine()
{
return moreFine;
}
public ParkedCar getVehicle()
{
return Vehicle;
}
public GardaOfficer getGuardString()
{
return GuardString;
}
public int getMinutes()
{
return Minutes;
}
public double getFine()
{
return ParkingFine;
}
// USE THE TO STRING METHODS
// Output to a Sting
public String toString()
{
String TicketString = "Fine : " + this.ParkingFine
+ "\nMinutes: " + Minutes
+ "\n" + Vehicle.toString()
+ "\n" + this.getGuardString().toString();
return TicketString;
}
}
Finally
//This is a demo file to show the program
public class DemoCar
{
public static void main(String[] args)
{
ParkedCar Test1 = new ParkedCar("BMW", "2014", "Yellow", "141D12345", 30);
ParkingMeter parking = new ParkingMeter(50);
GardaOfficer Murphy = new GardaOfficer("Guard Murphy", "10");
ParkingTicket ticket = Murphy.search(Test1, parking);
if (ticket != null)
{
System.out.println(ticket.toString());
}
else
{
System.out.println("No ticket issued!");
}
// A second car checked to see if it passes or not, it's over
ParkedCar Test2 = new ParkedCar("VW", "2001", "Green", "01D321", 225);
ParkingMeter parking2 = new ParkingMeter(200);
ParkingTicket ticket2 = Murphy.search(Test2, parking2);
if (ticket != null)
{
System.out.println(ticket.toString());
}
else
{
System.out.println("No ticket issued!");
}
}
}
You're printing ticket instead of ticket2 the second time around.
Also you should always make your variables lowercase.
This is an Object Oriented program with two classes Catalog and Products that reads a file that contains the product name, quantity, and price, adds them to a list array, and calculate the total Price of the items. Everything works with my program except that it has a toString method that when I ran the program it prints something like this #445ea7e I think this happens because the addProducts() and getProducts(String name) on the Catalog class has to do something with the toString() and I don't know how to connect them to work.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Catalog{
private static int MAX_ITEMS = 10;
/**
* List of Products objects.
*/
private Products[] list;
private int nextItem;
/**
* Default constructor
*/
public Catalog(){
list = new Products[MAX_ITEMS];
nextItem = 0;
}
/**
* Adds an item to the list
*/
public void addProducts (String name, int quantity, double price){
**//I tried this: list[nextItem] = new Products(name, quantity, price);
//but I'm not sure if that's ok.**
}
/**
* Reads items from an input file.
*/
public void loadList(String fileName)
throws FileNotFoundException {
if ( (fileName != null) && (!fileName.equals("")) ) {
Scanner input = new Scanner(new File(fileName));
String newLine = null;
String name = null;
int quantity = 0;
double price = 0.0;
while (input.hasNextLine() && nextItem < MAX_ITEMS) {
if (input.hasNext()) {
name = input.next();
} else {
System.err.println("ERROR Not a String");
System.exit(2);
}
if (input.hasNextInt()) {
quantity = input.nextInt();
} else {
System.err.println("ERROR Not an integer");
System.exit(2);
}
if (input.hasNextDouble()) {
price = input.nextDouble();
} else {
System.err.println("ERROR Not a double");
System.exit(2);
}
list[nextItem] = new Products(name, quantity, price);
newLine = input.nextLine();
nextItem += 1;
}
}
return;
}
/**
* Calculate the total cost of products.
*/
public double getTotalPrice(){
double total = 0.0;
for(int i=0; i < nextItem; i++){
Products products = list[i];
total+=products.getTotalPrice();
}
return total;
}
/**
* Search Catalog items with a product name
*/
public Products getProducts(String name){
**//search a list for string equality using the name of the product and returns it to the caller**
}
public static void main(String[] args)
throws FileNotFoundException {
Catalog catalog= new Catalog();
catalog.loadList(args[0]);
System.out.println();
//System.out.println(toString()); **I don't know how to call toString**
System.out.println();
System.out.format("Total Price = %9.2f\n", catalog.getTotalPrice());
}
}
This is the Products class with the toString() method.
public class Products {
private String name;
private int quantity;
private double price;
/**
* Constructor.
*/
public Products(String name, int quantity, double price){
this.name = name;
this.quantity = quantity;
this.price = price;
}
/**
* Gets name of the product.
*/
public String getName(){
return this.name;
}
/**
* Gets the quantity of products.
*/
public int getQuantity(){
return this.quantity;
}
/**
* Gets the cost per product.
*/
public double getPrice(){
return price;
}
/**
* set quantity of the products.
*/
public void setQuantity(int quantity){
this.quantity=quantity;
}
/**
* Calculate the total price.
*/
public double getTotalPrice(){
return quantity * price;
}
/**
* Returns a spaced-separated list of the attributes.
*/
public String toString(){
String s=null;
s+=getName();
s+=s + " ";
s+=getQuantity();
s+=s + " ";
s+=getPrice();
return s;
}
}
This is the file with the Products information
Football 2 15.50
ChapStick 1 3.87
Book 4 10.00
You add toString() to your Catalog class as Product class :
public class Catalog {
private static int MAX_ITEMS = 10;
/**
* List of Products objects.
*/
private Products[] list;
private int nextItem;
// your old code here
// new code
#Override
public String toString() {
return "this is a catalog";
}
}
You call catalog.toString():
public static void main(String[] args)
throws FileNotFoundException {
Catalog catalog= new Catalog();
catalog.loadList(args[0]);
System.out.println();
//System.out.println(toString()); **I don't know how to call toString**
// use this line
System.out.println(catalog.toString());
System.out.println();
System.out.format("Total Price = %9.2f\n", catalog.getTotalPrice());
}
In your toString() method of Product class. you should change initialize variable from s=null; to s="";. Here is sample :
public String toString(){
String s="";
s+=getName();
s+=s + " ";
s+=getQuantity();
s+=s + " ";
s+=getPrice();
return s;
}
Hope this help :)
In your toString() method (in products class), change
String s = null;
to
String s = "";
Also, you have to make a toString method for the Catalog class in order to call it.
An example toString method for catalog class can be:
public String toString(){
String toReturn = "";
for(Products current: list){
toReturn+=current.toString()+"\n";
}
return toReturn;
}
Then if main just call, System.out.println(catalog.toString());
Try adding override to your toString method this might be the solution base on your current output.
#Override
public String toString(){
String s=null;
s+=getName();
s+=s + " ";
s+=getQuantity();
s+=s + " ";
s+=getPrice();
return s;
}
hi guys I have created a basket field in this browser class but, however I now need to declare this basket field in the browser class as arraylist collection class object but cant figure out how to do this, below is my code so far
/**
* Write a description of class Browser here.
*
* #author (johnson)
* #version (10/12/13)
*/
public class Browser
{
// instance variables - replace the example below with your own
private int iD;
private String email;
private int yearOfBirth;
private boolean memberID;
private WineCase wineCase;
private boolean loggedIn;
private Website website;
private boolean discount;
List<Boolean> basketList = new ArrayList<Boolean>();
/**
* Constructor for objects of class Browser
*/
public Browser()
{
// initialise instance variables
wineCase = null;
website = null;
iD = 00065;
yearOfBirth = 1992;
memberID = true;
discount = false;
}
/**
* Constructor for objects of class Browser
*/
public Browser(String newEmail,int newYearOfBirth)
{
// initialise instance variables
wineCase = null;
website = null;
iD = 0;
email = newEmail;
yearOfBirth = newYearOfBirth;
loggedIn = false;
memberID = true;
discount = false;
}
/**
* Constructor for objects of class Browser
*/
public Browser(int newID, String newEmail,int newYearOfBirth)
{
// initialise instance variables
wineCase = null;
website = null;
iD = newID;
email = newEmail;
yearOfBirth = newYearOfBirth;
memberID = true;
discount = false;
}
/**
* returns the ID
*/
public int getId()
{
return iD;
}
/**
* gets the email of the browser class
*/
public String getEmail()
{
return email;
}
public boolean getDiscount()
{
return discount;
}
/**
* gets the yearOfBirth for the browser class
*/
public int yearOfBirth()
{
return yearOfBirth;
}
public double getWineCost()
{
return wineCase.getWineCost();
}
/**
* returns
*/
public void setLoginStatus(boolean status)
{
loggedIn = status;
}
/**
* returns
*/
public void selectWineCase(WineCase winecase)
{
wineCase = winecase;
System.out.println ("Browser "+getId()+" has selcted wine case"+wineCase.getRefNo()+ "of "+winecase.getNoOfBottles()+ wineCase.getDescription()+ " at £"+wineCase.getWineCost());
}
/**
* returns
*/
public void payForWine()
{
website.checkout(this);
}
public void setId()
{
iD = 999;
}
public void setWebSite(Website website)
{
this.website = website;
}
public void setDiscount(boolean discount)
{
this.discount = discount;
}
}
any answers or replies would be greatly appreciated
Try this out
List<Boolean> basketList = new ArrayList<Boolean>();
That must not be boolean as boolean is a primitive type not a collection of Objects.
what you need to do is:
ArrayList basket = new ArrayList();
Or if you need a collection of Boolean Objects (still not boolean) you can do:
ArrayList basket = new ArrayList();
A list of Boolean(s)?
java.util.List<Boolean> basketAl = new java.util.ArrayList<Boolean>();
And I urge you to add a toString method to your class
// Something like this...
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(iD).append(" ").append(email).append(" ");
sb.append(yearOfBirth).append(" ").append(memberID).append(" ");
sb.append(wineCase).append(" ").append(loggedIn).append(" ");
sb.append(website).append(" ").append(discount).append(" ");
sb.append(Basket);
return sb.toString();
}
It's a bit hard to tell what you're doing but declare this at the top of your class. Also, don't forget to import packages java.util.ArrayList and import java.util.List.
private List<Boolean> baskets = new ArrayList<Boolean>();
This will replace the previous declaration of:
private boolean Basket;