Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have code that has several classes with different cars and some classes. Below is my code, I'm not sure why vanClass van; is not working as it is basically a copy paste of the past classes that work. Any help is appreciated. To clarify, I am only having problems with the last few lines of the autopark class where I initiate vanClass as van and go from there.
import java.util.*;
class sedan {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
boolean isheavyDuty;
String carries;
public sedan(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;
}
}
class SUV {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
String carries;
public SUV(String initMake, String initModel, String initColor, int initYear, double initPrice, boolean initFourWD){
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
fourWD = initFourWD;
}
public String toString() {
String name = "SUV";
String main = new String();
if (fourWD) {
main = ("4WD " + color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
}
else {
main = (color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
}
return main;
}
}
class truckClass {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
boolean isheavyDuty;
String carries;
public truckClass(String initMake, String initModel, int initYear, double initPrice, boolean initisheavyDuty, String initCarries){
make = initMake;
model = initModel;
year = initYear;
price = initPrice;
isheavyDuty = initisheavyDuty;
carries = initCarries;
}
public String toString() {
String name = "Truck";
String main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
return main;
}
class vanClass {
String make;
String model;
int year;
double price;
boolean isCovered;
String carries;
public vanClass(String initMake, String initModel, int initYear, double initPrice, boolean initisCovered, String initCarries){
make = initMake;
model = initModel;
year = initYear;
price = initPrice;
isCovered = initisCovered;
carries = initCarries;
}
public String toString() {
String name;
String main;
if (isCovered()){
name = "covered Van";
String main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
}
else {
name = "Van";
String main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
}
return main;
}
}
public class autoPark {
public static void main(String args[]) {
sedan sedan1; // declaring cars object by name sedan1
sedan1 = new sedan("Ford" , "Model-1" , "white" , 2015, 20000); // initialising sedan1 using sedan constructor
System.out.println(sedan1); // printing sedan1 for invoking toString() method
SUV suv; // declaring cars object by name suv
suv = new SUV("Ford" , "Model-1" , "white" , 2015, 20000, true); // initialising suv using SUV constructor
System.out.println(suv); // printing suv for invoking toString() method
truckClass truck; //declaring cars object by name truck
truck = new truckClass("Ford" , "Model-1" , 2015, 20000, true, "2"); // initialising truck using truck constructor
System.out.println(truck); // printing truck for invoking toString() method
vanClass van;
van = new vanClass("Ford" , "Model-1" , 2015, 20000, true, "2";
System.out.println(van);
}
}
I came across 4 issues
missing } just before starting vanClass
missing ) after van = new vanClass("Ford" , "Model-1" , 2015, 20000, true, "2");
extra pair of parenthesis after isCovered which is a member data instead of method
Declaring main as String twice inside the toString method of SUV class
import java.util.*;
class sedan {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
boolean isheavyDuty;
String carries;
public sedan(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;
}
}
class SUV {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
String carries;
public SUV(String initMake, String initModel, String initColor, int initYear, double initPrice, boolean initFourWD){
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
fourWD = initFourWD;
}
public String toString() {
String name = "SUV";
String main = new String();
if (fourWD) {
main = ("4WD " + color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
}
else {
main = (color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
}
return main;
}
}
class truckClass {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
boolean isheavyDuty;
String carries;
public truckClass(String initMake, String initModel, int initYear, double initPrice, boolean initisheavyDuty, String initCarries){
make = initMake;
model = initModel;
year = initYear;
price = initPrice;
isheavyDuty = initisheavyDuty;
carries = initCarries;
}
public String toString() {
String name = "Truck";
String main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
return main;
}
}
class vanClass {
String make;
String model;
int year;
double price;
boolean isCovered;
String carries;
public vanClass(String initMake, String initModel, int initYear, double initPrice, boolean initisCovered, String initCarries){
make = initMake;
model = initModel;
year = initYear;
price = initPrice;
isCovered = initisCovered;
carries = initCarries;
}
public String toString() {
String name;
String main;
if (isCovered){
name = "covered Van";
main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
}
else {
name = "Van";
main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
}
return main;
}
}
public class autoPark {
public static void main(String args[]) {
sedan sedan1; // declaring cars object by name sedan1
sedan1 = new sedan("Ford" , "Model-1" , "white" , 2015, 20000); // initialising sedan1 using sedan constructor
System.out.println(sedan1); // printing sedan1 for invoking toString() method
SUV suv; // declaring cars object by name suv
suv = new SUV("Ford" , "Model-1" , "white" , 2015, 20000, true); // initialising suv using SUV constructor
System.out.println(suv); // printing suv for invoking toString() method
truckClass truck; // declaring cars object by name truck
truck = new truckClass("Ford" , "Model-1" , 2015, 20000, true, "2"); // initialising truck using truck constructor
System.out.println(truck); // printing truck for invoking toString() method
vanClass van;
van = new vanClass("Ford" , "Model-1" , 2015, 20000, true, "2");
System.out.println(van);
}
}
You need to consider using inheritance as mentioned by others.
I fixed and refactored your class using inheritance:
abstract class Vehicle{
protected String maker;
protected String model;
protected int year;
protected double price;
public Vehicle(String maker, String model, int year, double price) {
this.maker=maker;
this.model=model;
this.year=year;
this.price=price;
}
abstract String getType();
#Override
public String toString() {
return maker + " " + model + " " + getType() + " (" + year + ") costs $" + price;
}
}
abstract class HeavyVehicle extends Vehicle{
protected String carries;
public HeavyVehicle(String maker, String model, int year, double price, String carries) {
super(maker, model, year, price);
this.carries=carries;
}
}
class SUV extends HeavyVehicle{
String color;
boolean fourWD;
public SUV(String maker, String model, String initColor, int year, double price,
boolean initFourWD) {
super(maker,model,year,price,"1");
color = initColor;
fourWD = initFourWD;
}
public String toString() {
StringBuilder sb = new StringBuilder();
if (fourWD) {
sb.append("4WD ");
}
sb.append(color + " " + super.toString());
return sb.toString();
}
#Override
String getType() {
return "SUV";
}
}
class Truck extends HeavyVehicle{
public Truck(String maker, String model, int year, double price,String carries) {
super(maker,model,year,price,carries);
}
public String toString() {
return maker + " " + model + " " + getType() + " (" + year + ") carries" + carries + " costs $" + price;
}
#Override
String getType() {
return "Truck";
}
}
class Van extends HeavyVehicle{
boolean isCovered;
public Van(String maker, String model, int year, double price, boolean isCovered, String carries){
super(maker,model,year,price,carries);
this.isCovered = isCovered;
}
public String toString() {
String name = isCovered ? "covered Van" : getType();
return maker + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price;
}
#Override
String getType() {
return "Van";
}
}
class Sedan extends Vehicle{
String color;
public Sedan(String maker, String model, String color, int year, double price) {
super(maker,model,year,price);
this.color = color;
}
#Override
public String toString() {
return color + " " + super.toString();
}
#Override
String getType() {
return "Sedan";
}
}
public class Main {
public static void main(String args[]) {
Sedan sedan1; // declaring cars object by name sedan1
sedan1 = new Sedan("Ford", "Model-1", "white", 2015, 20000); // initialising sedan1 using sedan constructor
System.out.println(sedan1); // printing sedan1 for invoking toString() method
SUV suv; // declaring cars object by name suv
suv = new SUV("Ford", "Model-1", "white", 2015, 20000, true); // initialising suv using SUV constructor
System.out.println(suv); // printing suv for invoking toString() method
Truck truck; // declaring cars object by name truck
truck = new Truck("Ford", "Model-1", 2015, 20000, "2"); // initialising truck using truck constructor
System.out.println(truck); // printing truck for invoking toString() method
Van van;
van = new Van("Ford", "Model-1", 2015, 20000, true, "2");
System.out.println(van);
}
}
Was missing a } and ). Silly mistake
How do I make it so I'm able to change the jar1.toString() value and put it in the player.toString() value.
my programs output:
"Jill[](1) [a#1](1) [b#2](2) [c#3](3) /7\(4)"
desired output when using turn() method:
"Jill[a#1](1) [](1) [b#2](2) [c#3](3) /7\(4)"
I've already made it so that when a player inputs the string "P" for pickup, it deletes the value in the 1st jar "[](1) [b#2](2) [c#3](3)", I did this by making stone null and doing an if statement under the jar class java if stone == null we return the empty brackets [] but it is yet to transfer it to the player.toString() jar "Jill[](1)"
i've tried implementing if statements for Class Player String toString() method,
public String toString() {
return name + "[" + "]" + "(" + position + ")";
}
something along the lines of
return name + "[" + stone.toString() "]" + "(" + position + ")";
public class Ground
{
public Jar jar1;
private Jar jar2;
private Jar jar3;
private Player player;
private Chest chest;
private String move;
public String toString(){
return player.toString() + " " +
jar1.toString() + " " +
jar2.toString() + " " +
jar3.toString() + " " +
"/" + chest.combination + "\\" + "(" + chest.getPosition() + ")";
}
public void turn(){
System.out.print("Move (l/r/p/d): ");
move = Global.keyboard.nextLine();
if (move.equals("p") && player.getPosition() == jar1.getPosition()){
jar1 = new Jar(1, null);
}
public class Jar
{
private int position;
private Stone stone;
private Player pos;
public String toString() {
if (stone == null) {
return "[]" + "(" + getPosition() + ")";
}
return "[" + stone.toString() + "]" + "(" + getPosition() + ")";
}
public class Player
{
private String name;
private int position;
private static Jar jar;
private Stone stone;
private Ground ground;
public String toString() {
return name + "[" + "]" + "(" + position + ")";
}
public class Stone
{
private String name;
private int weight;
public Stone()
{
System.out.print("Enter stone name: ");
name = Global.keyboard.nextLine();
System.out.print("Enter stone weight: ");
weight = Global.keyboard.nextInt();
Global.keyboard.nextLine();
}
public String toString()
{
return name + "#" + weight;
}
Change Player.toString to include the player's stone. Also add a stone setter if you don't already have one:
public class Player {
private String name;
private int position;
private static Jar jar;
private Stone stone;
private Ground ground;
public String toString() {
return name + "[" + stone + "]" + "(" + position + ")";
}
public void setStone(Stone s) {
stone = s;
}
}
Add a stone getter to the Jar if you don't already have one:
public class Jar
{
private int position;
private Stone stone;
private Player pos;
public String toString() {
if (stone == null) {
return "[]" + "(" + getPosition() + ")";
}
return "[" + stone.toString() + "]" + "(" + getPosition() + ")";
}
public Stone getStone() {
return stone;
}
And when the player takes the turn, have them pick up the stone:
public void turn() {
System.out.print("Move (l/r/p/d): ");
move = Global.keyboard.nextLine();
if (move.equals("p") && player.getPosition() == jar1.getPosition()) {
player.setStone(jar1.getStone());
jar1 = new Jar(1, null);
}
}
I have the following class and two constructors:
public Book(String bookTitle,ConcurrentHashMap<Integer,String> authors, String bookType ) throws InvalidDataException{
this.setBookTitle(bookTitle);
this.setAuthors(authors);
this.setType(bookType);
}
public Book(String bookTitle,ConcurrentHashMap<Integer,String> authors, String bookType, String bookStyle, String ISBN, int numberofPages) throws InvalidDataException{
this (bookTitle,authors,bookType);
this.fullConstructor = true;
this.setStyle(bookStyle);
this.setISBN(ISBN);
this.setNumberofPages(numberofPages);
}
I also have the following variable:
private Boolean fullConstructor= false; to check which constructor was called.
I did this so that I can properly format my toString() method:
#Override
public String toString() {
String viewOutput="";
if (!this.fullConstructor)
{
viewOutput="Book: " + this.getBookTitle() + " " + " Author(s): " + this.loopAuthors() + " Genre: " + this.bookType;
}
else{
viewOutput="Book: " + this.getBookTitle() + " " + " Author(s): " + this.loopAuthors() + " Genre: " + this.bookType + " Book Style: " + this.getBookStyle() + " ISBN-10: " + this.getISBN() + " Number of Pages: " + this.getNumberofPages() + " Book Style: " +this.getBookStyle() + " ISBN: " + this.getISBN() + "Number of Pages: " + this.getNumberofPages();
}
return viewOutput;
}
Explanation:
If the full constructor is called the private variable fullConstructor is set to true. The toString knows how to format the return value based on the fullConstructor value. I did it this way, because I would have to check again to see what variables are empty, which the setters already do, it seemed repetitive.
Is what I did in bad practice? If so, how do I properly check if the values are empty so that I can correctly create the return string?
I'd probably use this:
public Book(String bookTitle, Map<Integer, String> authors, String bookType, String bookStyle, String isbn, int numberOfPages) throws InvalidDataException {
setBookTitle(bookTitle);
setAuthors(authors);
setType(bookType);
setStyle(bookStyle);
setISBN(isbn);
setNumberOfPages(numberOfPages);
}
public Book(String bookTitle, Map<Integer, String> authors, String bookType) throws InvalidDataException {
this(bookTitle, authors, bookType, null, null, null);
}
#Override
public String toString() {
String result = String.format("Book: %s Author(s): %s Genre: %s",
getBookTitle(), loopAuthors(), bookType);
if (getBookStyle() == null && getISBN() == null && getNumberOfPages() == null)
return result;
return String.format("%s Book Style: %s ISBN-10: %s Number of Pages: %s",
result, getBookStyle(), getISBN(), getNumberOfPages());
}
That way, you don't need a "fully-constructed" flag (seeing as the additional fields have setters and could be called later); the fields are just checked at toString time. Also, I took the liberty of changing your toString method to use String.format, and to be less repetitious.
i know how to parse Json in android. but i can't seem to wrap my head around parsing JSONC from Youtube using GSON. i just need to parse the title of the video. Thanks here is the url
http://gdata.youtube.com/feeds/api/videos/iS1g8G_njx8?v=2&alt=jsonc
The following code works to parse the given response with Gson
public class ExampleParser {
public static final String JSONC =
"{\"apiVersion\":\"2.1\","
+ " \"data\":{"
+ " \"id\":\"iS1g8G_njx8\","
+ " \"uploaded\":\"2014-05-30T20:00:01.000Z\","
+ " \"updated\":\"2014-11-26T14:14:11.000Z\","
+ " \"uploader\":\"arianagrandevevo\","
+ " \"category\":\"Music\","
+ " \"title\":\"Ariana Grande - Problem ft. Iggy Azalea\","
+ " \"description\":\"Ariana Grande ft. Iggy Azalea - Problem\nBuy now! http://smarturl.it/ArianaMyEvrythnDlxiT?IQid=vevo.cta.problem\nGoogle Play: http://goo.gl/n7rey5\n\nPre-order My Everything and get access to the iHeartRadio Concert video stream where Ariana performs songs from her new album FOR THE FIRST TIME!\nhttp://myplay.me/19ys\","
+ " \"thumbnail\":{"
+ " \"sqDefault\":\"http://i.ytimg.com/vi/iS1g8G_njx8/default.jpg\","
+ " \"hqDefault\":\"http://i.ytimg.com/vi/iS1g8G_njx8/hqdefault.jpg\"},"
+ " \"player\":{"
+ " \"default\":\"http://www.youtube.com/watch?v=iS1g8G_njx8&feature=youtube_gdata_player\"},"
+ " \"content\":{"
+ " \"5\":\"http://www.youtube.com/v/iS1g8G_njx8?version=3&f=videos&app=youtube_gdata\"},"
+ " \"duration\":208,"
+ " \"aspectRatio\":\"widescreen\","
+ " \"rating\":4.731269,"
+ " \"likeCount\":\"1527921\","
+ " \"ratingCount\":1637964,"
+ " \"viewCount\":307368910,"
+ " \"favoriteCount\":0,"
+ " \"commentCount\":156682,"
+ " \"status\":{"
+ " \"value\":\"restricted\","
+ " \"reason\":\"limitedSyndication\"},"
+ " \"restrictions\":["
+ " {\"type\":\"country\","
+ " \"relationship\":\"deny\","
+ " \"countries\":\"DE\"}],"
+ " \"accessControl\":{"
+ " \"comment\":\"allowed\","
+ " \"commentVote\":\"allowed\","
+ " \"videoRespond\":\"moderated\","
+ " \"rate\":\"allowed\","
+ " \"embed\":\"allowed\","
+ " \"list\":\"allowed\","
+ " \"autoPlay\":\"allowed\","
+ " \"syndicate\":\"allowed\"}}}";
public static void main(String[] args) {
Gson gson = new GsonBuilder()
// Add your date deserializer
.create();
YoutubeResponse response = gson.fromJson(JSONC, YoutubeResponse.class);
System.out.println(response);
}
public static class YoutubeResponse {
Double apiVersion;
Data data;
}
public static class Data {
String id;
String uploaded; // TODO should be a date
String updated; // TODO should be a date
String uploader;
String category;
String title;
String description;
Thumbnail thumbnail;
Player player;
Integer duration;
String aspectRatio;
Double rating;
Integer likeCount;
Integer ratingCount;
Integer viewCount;
Integer favoriteCount;
Integer commentCount;
Status status;
List<Restriction> restrictions;
}
public static class Thumbnail {
String sqDefault;
String hqDefault;
}
public static class Player {
#SerializedName("default")
String defaultt; // default is a reserved java keyword
}
public static class Status {
String value;
String reason;
}
public static class Restriction {
String type;
String relationship;
String countries;
}
public static class AccessControl {
String comment;
String commentVote;
String videoRespond;
String rate;
String embed;
String list;
String autoPlay;
String syndicate;
}
}
I try to change the values of coupe but the output doesn't change. In NetBeans, I saved these two programs under the same project and package. I did not include it here because it may have made the code too long, but I also wrote accessor methods which work fine, so I am confused as to why the mutator methods don't work.
Class code:
package auto;
public class Auto
{
private String model;
private int milesDriven;
private double gallonsOfGas;
public Auto(String startModel,
int startMilesDriven,
double startGallonsOfGas)
{
model = startModel;
setMilesDriven(startMilesDriven);
setGallonsOfGas(startGallonsOfGas);
}
public void setModel(String newModel)
{
model = newModel;
}
public void setMilesDriven(int newMilesDriven)
{
if (newMilesDriven >= 0)
milesDriven = newMilesDriven;
else
{
System.err.println("Miles driven cannot be negative.");
System.err.println("Value not changed.");
}
}
public void setGallonsOfGas(double newGallonsOfGas)
{
if (newGallonsOfGas >= 0.0)
gallonsOfGas = newGallonsOfGas;
else
{
System.err.println("Gallons of gas cannot be negative.");
System.err.println("Value not changed.");
}
}
}
Client class code:
package auto;
import java.text.DecimalFormat;
public class AutoClient
{
public static void main(String [] args)
{
DecimalFormat milesPattern = new DecimalFormat("#,###");
Auto coupe = new Auto("Corvette", 300000, 0.0);
String coupeModel = coupe.getModel();
int coupeMiles = coupe.getMilesDriven();
double coupeGallons = coupe.getGallonsOfGas();
System.out.println("coupe:"
+ "\nmodel: " + coupeModel
+ "\nmiles: " + milesPattern.format(coupeMiles)
+ "\ngallons: " + coupeGallons);
coupe.setModel("Viper");
coupe.setMilesDriven(10000);
coupe.setGallonsOfGas(50.0);
System.out.println("coupe:"
+ "\nmodel: " + coupeModel
+ "\nmiles: " + milesPattern.format(coupeMiles)
+ "\ngallons: " + coupeGallons);
}
}
Given your current code, after you changed the values
coupe.setModel("Viper");
coupe.setMilesDriven(10000);
coupe.setGallonsOfGas(50.0);
You need to get them again
coupeModel = coupe.getModel();
coupeMiles = coupe.getMilesDriven();
coupeGallons = coupe.getGallonsOfGas();
Before you can call
System.out.println("coupe:"
+ "\nmodel: " + coupeModel
+ "\nmiles: " + milesPattern.format(coupeMiles)
+ "\ngallons: " + coupeGallons);
I suggest you update Auto and add a toString()
#Override
public String toString() {
return "coupe:"
+ "\nmodel: " + coupeModel
+ "\nmiles: " + milesPattern.format(coupeMiles)
+ "\ngallons: " + coupeGallons;
}
Then you can replace (in both places)
System.out.println("coupe:"
+ "\nmodel: " + coupeModel
+ "\nmiles: " + milesPattern.format(coupeMiles)
+ "\ngallons: " + coupeGallons);
With
System.out.println(coupe); // <-- Java will call toString() for you