my dear Friends I am new to this java ..so plz help me thank u in advance.. Now i am workin on an examples to understand the concepts of java's objects, classes method in detail.
With all the knowledge i have i tried this example. . but i am unable to accomplish the task.. . Can any one plz give me suggestions of corrected coding..
I also wanted to know Which s the best site for learning JAVA (like MSDN for .NET )
Thank u in advance
Question:To Create Vehicle having following attributes: Vehicle No., Model, Manufacturer and Color. Create truck which has the following additional attributes: loading capacity( 100 tons…).Add a behavior to change the color and loading capacity. Display the updated truck details.
Codings:
import java.io.*;
class Vehicle
{
String VehicleNo;
String Model;
String Manufacturer;
String Color;
public void setNo(String VehicleNo)
{
this.VehicleNo=VehicleNo;
}
public String getNo()
{
return VehicleNo;
}
public void setModel(String Model)
{
this.Model=Model;
}
public String getModel()
{
return Model;
}
public void setManufacturer(String Manufacturer)
{
this.Manufacturer=Manufacturer;
}
public String getManufacturer()
{
return Manufacturer;
}
public void setColor(String Color)
{
this.Color=Color;
}
public String getColor(String s)
{
return s;
}
}
class Truck extends Vehicle
{
double LoadingCapacity;
public void setLoad(double LoadingCapacity)
{
this.LoadingCapacity=LoadingCapacity;
}
public double getLoad(double ld)
{
return ld;
}
}
public class VehicleInfo {
/**
* #param args
* #throws IOException
*/
public static void mainEntry2() throws IOException
{
//Truck D=new Truck();
//BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Color: ");
String col=br.readLine();
D.setColor(col);
System.out.print("Enter Loading Capacity: Maximum 100tons");
int load=Integer.parseInt(br.readLine());
D.setLoad(load);
}
public static void main(String[] args) throws IOException
{
int loop_option=0;
public Truck D=new Truck();
public BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Vehicle No: ");
String no=br.readLine();
D.setNo(no);
System.out.print("Model: ");
String model=br.readLine();
D.setModel(model);
System.out.print("Manufacturer: ");
String man=br.readLine();
D.setManufacturer(man);
mainEntry2();
do
{
System.out.println("");
System.out.println("----Vehicle Information----");
System.out.println();
System.out.println("Vehicle No: "+D.getNo());
System.out.println("Model: "+D.getModel());
System.out.println("Manufacturer: "+D.getManufacturer());
System.out.println("Color: "+D.getColor(col));
System.out.println("Loading Capacity: "+D.getLoad(load));
System.out.println("");
System.out.println(" if U want to update color and loading capacity press 1 and to exit press 2 ..");
loop_option=Integer.parseInt(br.readLine());
if(loop_option==1)
{
mainEntry2();
}
}while(loop_option==1);
}
}
Here are some general remarks. Hope they help:
getters should only return value, they do not have parameters (otherwise they are not getters).
if you're encapsulating fields, make them private
use descriptive variable names (eg. truck instead of D)
use descriptive method names (mainEntry2() tells absolutely nothing)
if you're parsing integer from user input, handle parsing exceptions (like NumberFormatException)
For instance, your program may be re-written like here:
import java.io.*;
class Vehicle {
private String vehicleNo;
private String model;
private String manufacturer;
private String color;
public void setNo(String vehicleNo) {
this.vehicleNo = vehicleNo;
}
public String getNo() {
return vehicleNo;
}
public void setModel(String model) {
this.model = model;
}
public String getModel() {
return model;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getManufacturer() {
return manufacturer;
}
public void setColor(String color)
{
this.color = color;
}
public String getColor() {
return color;
}
}
class Truck extends Vehicle
{
private double loadingCapacity;
public void setLoad(double loadingCapacity) {
this.loadingCapacity = loadingCapacity;
}
public double getLoad() {
return this.loadingCapacity;
}
}
public class VehicleInfo {
private static void updateColorAndCapacity(BufferedReader br, Truck truck)
throws IOException
{
System.out.print("Color: ");
String col = br.readLine();
truck.setColor(col);
while (true)
{
System.out.print("Enter Loading Capacity (maximum 100tons):");
String value = br.readLine();
value = value.trim();
try {
int load = Integer.parseInt(value);
truck.setLoad(load);
return;
} catch (NumberFormatException e) {
/// do it once again
continue;
}
}
}
public static void main(String[] args)
throws IOException {
Truck truck = new Truck();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Vehicle No: ");
String no = br.readLine();
truck.setNo(no);
System.out.print("Model: ");
String model = br.readLine();
truck.setModel(model);
System.out.print("Manufacturer: ");
String man = br.readLine();
truck.setManufacturer(man);
updateColorAndCapacity(br, truck);
int loop_option = 0;
do {
System.out.println();
System.out.println("----Vehicle Information----");
System.out.println();
System.out.println("Vehicle No: " + truck.getNo());
System.out.println("Model: " + truck.getModel());
System.out.println("Manufacturer: " + truck.getManufacturer());
System.out.println("Color: " + truck.getColor());
System.out.println("Loading Capacity: " + truck.getLoad());
System.out.println();
System.out.println(" if U want to update color and loading capacity press 1 and to exit press 2 ..");
loop_option = Integer.parseInt(br.readLine());
if (loop_option == 1) {
updateColorAndCapacity(br, truck);
}
} while (loop_option == 1);
}
}
You should start here for learning Java: http://download.oracle.com/javase/tutorial/
Related
I have a info class Vehicle that has multiple attributes and I have a Moped info class that extends the vehicle class. I need to create a main program that I can add multiple mopeds to an array list and then print them. Here is my attempt:
info class1:
package data;
public class Vehicle {
private float price;
private String color;
private int maximumSpeed;
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color= color;
}
public int getMaximumSpeed() {
return maximumSpeed;
}
public void setMaximumSpeed(int maximumSpeed) {
this.maximumSpeed = maximumSpeed;
}
public String toString() {
return "Price: "+this.price+" Color: "+this.color+" Maximum speed: "+this.maximumSpeed;
}
}
Info class2:
package data;
public class Moped extends Vehicle{
private String Brand;
private String type;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand= brand;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String toString() {
return "Brand: "+this.brand+" Type: "+this.type;
}
}
Main program:
package app;
import java.util.ArrayList;
import java.util.Scanner;
import data.*;
public class ExtendsTest {
public static void main(String[] args) {
ArrayList<Moped> list=new ArrayList<>();
Moped mp=new Moped();
askForMopedInfo(mp);
lista.add(mp);
printMoped(list);
}
private static void printMoped(ArrayList<Moped> list) {
for (int i=0;i<list.size(); i++) {
System.out.println(list.get(i));
}
}
private static void askForMopedInfo(Moped mp) {
Scanner scanner = new Scanner(System.in);
System.out.print("Brand: ");
String k = scanner.nextLine();
mp.setBrad(k);
System.out.print("Type: ");
k = scanner.nextLine();
mp.setType(k);
System.out.print("Price: ");
int k1 = Integer.parseInt(scanner.nextLine());
mp.setPrice(k1);
System.out.print("Color: ");
k = scanner.nextLine();
mp.setColor(k);
System.out.print("Maximum speed: ");
k1 = Integer.parseInt(scanner.nextLine());
mp.setMaximumSpeed(k1);
}
}
When I run the program I get asked for:
Brand:
Type:
Price:
Color:
Maximum speed:
But the program only prints:
Brand: x Type: x
And I am still not sure how to add multiple mopeds to the array list. Any help would be much appreciated!
Update toString method of your Moped class, like this:
package data;
public class Moped extends Vehicle {
/*
other code
*/
public String toString() {
return super.toString() +" Brand: "+this.brand+" Type: "+this.type;
}
}
to Add more mopeds to the array list, you can do this:
public static void main(String[] args) {
ArrayList<Moped> list=new ArrayList<>();
While(true){
Moped mp=new Moped();
askForMopedInfo(mp);
list.add(mp);
printMoped(list);
}
}
I have the following problem. Five classes are interacting with each other. Two of theme are doing fine. But with the creating of an Object of one class (Ticket) in my main class Event (getting user input from another class (UserInput), an processing this in the costructor) i have now problem to display the results.
Main class Event with main methode
import java.util.ArrayList;
public class Event {
private static String artistName;
private static int artistSalary;
private Language language;
private static ArrayList<String> trackList;
private InputReader inputReader;
private Ticket ticket;
private int amountOfTicketCategories;
private static Object[] ticketList;
private static int index;
public Event() {
}
public Event(Artist artist, Ticket ticket) {
artistName = artist.getArtistName();
artistSalary = artist.getArtistSalary();
trackList = artist.getArrayList();
for (index = 0; index < amountOfTicketCategories; index++) {
ticketList[index] = ticket.getTicket();
ticketList[index].toString();
}
}
public void chooseWhatToDefine() {
language = new Language();
language.whatToSpecify();
}
public void setTicketPrice(String ticketCategory, int ticketPrice) {
}
public void displayArtist(String artistName, int artistSalary) {
language = new Language();
language.displayArtistAndSalary(artistName, artistSalary);
}
public void displayTracklist(ArrayList<String> trackList) {
language = new Language();
language.displayTrackList(trackList);
}
public void displayTickets(Object[] ticketList) {
language = new Language();
language.displayTicket(ticketList);
}
public static void main(String[] args) {
Event event1 = new Event(new Artist(), new Ticket());
event1.displayArtist(artistName, artistSalary);
event1.displayTracklist(trackList);
event1.displayTickets(ticketList);
}
}
Ticket class with constructor that initalize the class with the user input comming from the InputReader class, and creates an object of Strings and Integers.
import java.util.Arrays;
public class Ticket {
private static String ticketCategory;
private static int ticketAmount;
private static int ticketPrice;
private InputReader inputReader;
private int amountOfTicketCategories;
private int index;
private Ticket[] ticketList;
public Ticket(String ticketCategory,int ticketAmount,int ticketPrice) {
}
public Ticket() {
inputReader = new InputReader();
inputReader.specifyTicketCategories();
ticketList = new Ticket[amountOfTicketCategories];
for (index = 0; index < amountOfTicketCategories; index++) {
inputReader.specifyTicket(ticketCategory, ticketAmount, ticketPrice);
ticketList[index] = new Ticket(ticketCategory, ticketAmount, ticketPrice);
}
}
public String toString() {
return("TicketCategory: " + ticketCategory + "Amount of Tickets: " + ticketAmount + "Ticket Price: " +ticketPrice);
}
public Object getTicket() {
return ticketList[index];
}
public int getAmountOfTicketCategories() {
amountOfTicketCategories = inputReader.specifyTicketCategories();
return amountOfTicketCategories;
}
}
InptReader class that processes the user input:
import java.util.ArrayList;
import java.util.Scanner;
public class InputReader {
private Scanner sc;
private Language language;
private ArrayList <String> tracks;
public InputReader() {
tracks = new ArrayList<String>();
language = new Language();
sc = new Scanner(System.in);
}
public int specifyTicketCategories() {
language.defineAmountOfTicketCategories();
return sc.nextInt();
}
public void specifyTicket(String ticketCategory, int ticketAmount, int ticketPrice) {
language.specifyTicketCategory();
ticketCategory = sc.next();
language.specifyTicketAmount();
ticketAmount = sc.nextInt();
language.specifyTicketPrice();
ticketPrice = sc.nextInt();
}
public int amountOfTickets() {
return sc.nextInt();
}
public int ticketPrice() {
return sc.nextInt();
}
public String readName() {
language.specifyArtist();
return sc.nextLine();
}
public int readInteger() {
language.specifyArtistSalary();
return sc.nextInt();
}
public void addTitle() {
int anzahlSongs = 3;
int index = 0;
while (index < anzahlSongs) {
language.specifyTrackList();
tracks.add(sc.nextLine());
index++;
}
}
public ArrayList<String> getArray() {
return tracks;
}
}
Language class that consists of the language statements
import java.util.ArrayList;
public class Language {
public Language () {
}
public void whatToSpecify() {
System.out.println("What would you like to specify fist? For Artist press 1, for Ticket press 2");
}
public void specifyArtist() {
System.out.println("Who is the artist? ");
}
public void specifyArtistSalary() {
System.out.println("How much does the artist earn? ");
}
public void displayTicket(Object[] ticketList) {
System.out.println("Ticketlist: " + ticketList);
}
public void displayArtistAndSalary(String artistName, int artistSalary) {
System.out.println("Artist: " + artistName + " " + "Salary: " + artistSalary);
}
public void displayTrackList(ArrayList<String> trackList) {
System.out.println("Tracklist: " + trackList);
}
public void specifyTicketCategory() {
System.out.println("What is the ticket category? ");
}
public void specifyTicketAmount() {
System.out.println("What ist the amount of tickets? ");
}
public void specifyTicketPrice() {
System.out.println("What is the price for your ticket?");
}
public void specifyTrackList() {
System.out.println("Add title: ");
}
public void defineAmountOfTicketCategories() {
System.out.println("How many ticket categories you like to set up?");
}
public void line() {
System.out.println("***********************************");
}
}
Artist class that that has creates an instance of an artist in the main class (same idea as for ticket) but with other variables and parameters.
import java.util.ArrayList;
public class Artist {
private int artistSalary;
private String artistName;
private InputReader inputReader;
ArrayList <String> trackList;
public Artist() {
inputReader = new InputReader();
artistName = inputReader.readName();
artistSalary = inputReader.readInteger();
inputReader.addTitle();
trackList = inputReader.getArray();
trackList.remove(2);
}
public String getArtistName() {
return artistName;
}
public int getArtistSalary() {
return artistSalary;
}
public ArrayList<String> getArrayList(){
return trackList;
}
}
Output in the console:
Add title:
Hello
Add title:
Hello
How many ticket categories you like to set up?
5
Artist: David Salary: 5000
Tracklist: [, Hello]
Ticketlist: null
First of all, in the Ticket class's constructor, you use the other constructor (The one with the 3 arguments), which has an empty body.
ticketList[index] = new Ticket(ticketCategory, ticketAmount, ticketPrice);
public Ticket(String ticketCategory,int ticketAmount,int ticketPrice) {
//this is empty
}
That means you're creating an object with.. nothing in it (null variables).
Try this:
public Ticket(String ticketCategory,int ticketAmount,int ticketPrice) {
this.ticketCategory = ticketCategory;
this.ticketAmount = ticketAmount;
this.ticketPrice = ticketPrice;
}
Then, your getTicket method is wrong. You never define the "index" integer in your Ticket class.
public Object getTicket() {
return ticketList[index];
}
Where "index" is undefined.
The ticketList should not be in the Ticket class => each time you create a Ticket instance, it will probably not be the same as the previous one.
I am trying to create a animal array to try and hold the information of different types of animals/owners. Been trying to solve this for 2 hours reading the book but nothing is working. Can anyone point me to the right direction? Also how would I go about importing information from a URL to a array?
import java.net.URL;
import java.math.BigInteger;
import java.net.URL;
import java.net.HttpURLConnection;
import static java.util.Arrays.sort;
public class janesj_Program5 {
public static void main(String[] args) {
Animal[] j = new Animal[1];
storeFile(j);
sort(j);
printArray(j);
}
public static class Animal {
String OwnerName;
int birthYear;
public int billBalance;
String Species;
String feature;
public Animal() {}
public Animal(String OwnerName,int birthYear,int billBalance,String Species,String feature) {
this.OwnerName = OwnerName;
this.birthYear = birthYear;
this.billBalance = billBalance;
this.Species = Species;
this.feature = feature;
}
public int getBalance() {
return billBalance;
}
public String toString() {
return OwnerName + "\t" + birthYear + "\t" + getBalance() + "\t" + Species + "\t" + feature;
}
}
public static void storeFile(Animal[] x) {
String URLString = "http://yoda.kean.edu/~pawang/CPS2231/Program5_veterinarian_input.txt";
try {
java.net.URL url = new java.net.URL(URLString);
int count = 0;
Scanner input = new Scanner(url.openStream());
while(input.hasNext()) {
String line = input.nextLine();
count+= line.length();
x = new Animal[count];
}
}catch(java.net.MalformedURLException ex){
System.out.println("Invalid URL");
}
catch(java.io.IOException ex) {
System.out.println("I/O Errors: no such file");
}
}
public static class sorts extends Animal implements Comparator<Animal> {
public int compare(Animal a, Animal b) {
return a.getBalance() - b.getBalance();
}
}
public static void printArray(Animal[] x) {
System.out.println("\t Veterinarian Services Report \t Page:1");
System.out.println(" ==================================");
System.out.println("No\tOwner Name\tYear\tBalance\tSpecies\tLegs\tFeature");
System.out.println("== ==================== ==== ============ ============ ============");
for(int i = 1; i<=x.length;i++) {
System.out.println(i + " " + x.toString());
}
}
}
As so kindly pointed out by MTilsted you really should have your Animal class within its own .java file.
If you plan to create an array of Animal objects where the data to fill those objects is coming from a data file then you need to realize that arrays are of a fixed size, they can't just grow on a whim (at least not without more coding). You would need to know how may animals are contained within the data file so as to properly size your Animal array. Your in luck, by the look of it your data file contains the number of animals within the first line of the file (which needs to be ignored when reading in the actual animal data).
First, make sure the file actually exist. No sense going through heartache if it's not even there or there is something wrong with the connection to its' location. Once done, you can declare and initialize your Animals array to the proper size so as to handle all the data rows you are about to re-read into the array.
Below is your code to demonstrate how this can be accomplished.
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
public class AnimalCare {
static Animals[] animals; // Declare The Anmimal Array as a class member variable
public static void main(String[] args) {
try {
URL url = new URL("http://yoda.kean.edu/~pawang/CPS2231/Program5_veterinarian_input.txt");
int lines = 0;
// Get the number of lines in file
try (Scanner s = new Scanner(url.openStream())) {
String firstFileLine = "";
while (firstFileLine.equals("")) {
firstFileLine = s.nextLine().trim();
if (!firstFileLine.equals("")) {
lines = Integer.parseInt(firstFileLine);
}
}
}
catch (IOException ex) {
String msg = "";
if (!ex.getMessage().equals(url.toString())) {
msg = "No Network Connection!";
}
else {
msg = "File Not Found! - " + ex.getMessage();
}
System.err.println(msg);
}
// Declare our Animals Array.
animals = new Animals[lines];
// Re-read the data file on network...
try (Scanner s = new Scanner(url.openStream())) {
int i = 0;
String dataLine;
s.nextLine(); // Skip the first line of file!
while (s.hasNextLine()) {
dataLine = s.nextLine().trim();
// Skip blank lines (if any)
if (dataLine.equals("")) {
continue;
}
String[] dataParts = dataLine.split("\\s+");
animals[i] = new Animals(dataParts[0],
Integer.parseInt(dataParts[1]),
Integer.parseInt(dataParts[2]),
dataParts[3],
dataParts[4]);
i++; // Increment i to create the next index value for array
}
// The Animals array is now filled with network file data
}
catch (IOException ex) {
String msg = "";
if (!ex.getMessage().equals(url.toString())) {
msg = "No Network Connection!";
}
else {
msg = "File Not Found! - " + ex.getMessage();
}
System.err.println(msg);
}
}
catch (MalformedURLException ex) {
System.err.println(ex.getMessage());
}
// Display the Animals array within the Console Window...
for (int i = 0; i < animals.length; i++) {
System.out.println(animals[i].toString());
}
}
}
And the Animals Class:
import java.util.Arrays;
public class Animals {
private String OwnerName;
private int birthYear;
private int billBalance;
private String Species;
private String feature;
//----------------- Constructors -------------------
public Animals() { }
public Animals(String OwnerName, int birthYear, int billBalance, String Species, String feature) {
this.OwnerName = OwnerName;
this.birthYear = birthYear;
this.billBalance = billBalance;
this.Species = Species;
this.feature = feature;
}
public Animals(Object[] data) {
if (data.length != 5 || !(data[0] instanceof String) ||
!(data[1] instanceof Integer) || !(data[2] instanceof Integer) ||
!(data[3] instanceof String) || !(data[4] instanceof String)) {
throw new IllegalArgumentException("Error in Animals Constructor data array! "
+ "Insufficiant data or invalid data element!" + System.lineSeparator() +
Arrays.deepToString(data));
}
this.OwnerName = data[0].toString();
this.birthYear = (int) data[1];
this.billBalance = (int) data[2];
this.Species = data[3].toString();
this.feature = data[4].toString();
}
//---------------------------------------------------
public int getBalance() {
return billBalance;
}
public String getOwnerName() {
return OwnerName;
}
public void setOwnerName(String OwnerName) {
this.OwnerName = OwnerName;
}
public int getBirthYear() {
return birthYear;
}
public void setBirthYear(int birthYear) {
this.birthYear = birthYear;
}
public int getBillBalance() {
return billBalance;
}
public void setBillBalance(int billBalance) {
this.billBalance = billBalance;
}
public String getSpecies() {
return Species;
}
public void setSpecies(String Species) {
this.Species = Species;
}
public String getFeature() {
return feature;
}
public void setFeature(String feature) {
this.feature = feature;
}
#Override
public String toString() {
String string = String.format("%-10s %-8d %-8d %-10s %-15s",
OwnerName, birthYear, getBalance(), Species, feature);
return string;
}
}
I am working on a simple text-based rpg battler program as an introduction to Java. I seem to have a decent understanding of the majority of code, but I have ran into a couple of issues.
The issues I am having are in the Project class.
In my switch statement I am trying to use the setSpells() and setArrows() methods and I am getting a "cannot find symbol" error message. I realize that this is probably due to something I have set up incorrectly in the sub-classes, but I am unsure what that is.
The second issue is in the print statement pulling the character name by use of c.getName(). The c part of that statement gives the same error message.
Is there something simple that I am misunderstanding in these situations? Any help resolving this would be appreciated. Thank you.
Here is my main project class file:
package project;
import java.util.Scanner;
public class Project {
public static void main(String[] args) {
System.out.println("Welcome to Lands of the Sun\n");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
System.out.print("Please choose your class (wizard or elf): \n");
String classChoice = sc.next();
sc.nextLine();
System.out.print("Please choose a name for your " + classChoice + ": ");
String charName = sc.next();
sc.nextLine();
int healthVal = (int) (Math.random() * 10) + 1;
switch (classChoice) {
case "wizard":
{
Character c = new Wizard();
c.setName(charName);
c.setGold(25);
c.setHealth(healthVal);
c.setSpells(10);
break;
}
case "elf":
{
Character c = new Elf();
c.setName(charName);
c.setGold(25);
c.setHealth(healthVal);
c.setArrows(10);
break;
}
}
System.out.print(c.getName());
System.out.print("Continue? (y/n): ");
choice = sc.nextLine();
System.out.println();
}
}
}
Here is my Character class:
package project;
public abstract class Character {
private String name;
private int gold;
private int health;
public static int count = 0;
public Character()
{
name = "";
gold = 0;
health = 0;
}
public Character(String name, int gold, int health) {
this.name = name;
this.gold = gold;
this.health = health;
}
public void setName(String name)
{
this.name = name;
}
public String getName(){
return name;
}
public void setGold(int gold)
{
this.gold = gold;
}
public int getGold()
{
return gold;
}
public void setHealth(int health)
{
this.health = health;
}
public int getHealth()
{
return health;
}
#Override
public String toString()
{
return "Name: " + name + "\n" +
"Gold: " + gold + "\n" +
"Health: " + health + "\n";
}
public static int getCount()
{
return count;
}
public abstract String getDisplayText();
}
Here is my Wizard sub-class:
package project;
public class Wizard extends Character {
private int spells;
public Wizard()
{
super();
spells= 0;
count++;
}
public void setSpells(int spells)
{
this.spells= spells;
}
public int getSpells(){
return spells;
}
#Override
public String getDisplayText()
{
return super.toString() +
"Spells: " + spells+ "\n";
}
}
And finally my Elf sub-class:
package project;
public class Elf extends Character{
private int arrows;
public Elf()
{
super();
arrows = 0;
count++;
}
public void setArrows(int arrows)
{
this.arrows = arrows;
}
public int getArrows(){
return arrows;
}
#Override
public String getDisplayText()
{
return super.toString() +
"Arrows: " + arrows + "\n";
}
}
When you create one of your Characters...
Character c = new Elf();
You are downcasting the instance to "act" like Character, this is very useful feature in Object Oriented Programming, but is causing you issues in this case, as Character does not have the methods you are looking for.
Instead, start by assigning the class to a concrete version of the instance...
Elf elf = new Elf();
Apply the properties you need and then assign it to a Character reference...
Character c = null;
//...
switch (classChoice) {
//...
case "elf":
{
Elf elf = new Elf();
//...
c = elf;
}
}
c = elf;
for example...
Have a look at the section on Polymorphism for more details
Your issue is with these lines
Character c = new Wizard();
....
Character c = new Elf();
The character class itself doesn't have the setFireballs or SetArrows methods. You need to define the object as a wizard or elf in order to get access to said methods... EG:
Elf c = new Elf();
Wizard c = new Wizard();
etc
Character c = new Wizard();
Character has neither a setFireBalls method nor a setArrows method.
I have made the some changes to your code..
here is the final code.
package h;
import java.util.Scanner;
public class he {
public static void main(String[] args) {
System.out.println("Welcome to Lands of the Sun\n");
Character c = new Wizard();
Character e = new Elf();
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
System.out.print("Please choose your class (wizard or elf): \n");
String classChoice = sc.next();
sc.nextLine();
System.out.print("Please choose a name for your " + classChoice + ": ");
String charName = sc.next();
sc.nextLine();
int healthVal = (int) (Math.random() * 10) + 1;
switch (classChoice) {
case "wizard":
{
c.setName(charName);
c.setGold(25);
c.setHealth(healthVal);
c.setFireballs(10);
break;
}
case "elf":
{
;
e.setName(charName);
e.setGold(25);
e.setHealth(healthVal);
e.setArrows(10);
break;
}
}
System.out.print(c.getName());
System.out.print("Continue? (y/n): ");
choice = sc.nextLine();
System.out.println();
}
}
}
Wizard class
public class Wizard extends Character {
private int fireballs;
public Wizard()
{
super();
fireballs = 0;
count++;
}
public void setFireballs(int fireballs)
{
this.fireballs = fireballs;
}
public int getFireballs(){
return fireballs;
}
#Override
public String getDisplayText()
{
return super.toString() +
"Fireballs: " + fireballs + "\n";
}
#Override
public void setArrows(int i) {
}
}
Elf class
public class Elf extends Character {
private int arrows;
public Elf()
{
super();
arrows = 0;
count++;
}
public void setArrows(int arrows)
{
this.arrows = arrows;
}
public int getArrows(){
return arrows;
}
#Override
public String getDisplayText()
{
return super.toString() +
"Arrows: " + arrows + "\n";
}
#Override
public void setFireballs(int i){
}
}
abstract class Character
public abstract class Character {
private String name;
private int gold;
private int health;
public static int count = 0;
public Character() {
name = "";
gold = 0;
health = 0;
}
public Character(String name, int gold, int health) {
this.name = name;
this.gold = gold;
this.health = health;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setGold(int gold) {
this.gold = gold;
}
public void setHealth(int health) {
this.health = health;
}
public int getHealth() {
return health;
}
#Override
public String toString() {
return "Name: " + name + "\n" + "Gold: " + gold + "\n" + "Health: "
+ health + "\n";
}
public static int getCount() {
return count;
}
public abstract String getDisplayText();
public abstract void setFireballs(int i);
public abstract void setArrows(int i);
}
hope this helps...
If I have an array of a class type (cars) and each car has been given a make and model
using set methods, how can I then print out the make and model of a particular element?
I need to print this out in a separate class
public class Car {
private String make;
private String model;
public void setMake (String str1) {
make = str1;
}
public void setModel (String str2) {
model = str2;
}
You need to add a toString() method to your class
public class Car {
private String make;
private String model;
public void setMake (String str1) {
make = str1;
}
public void setModel (String str2) {
model = str2;
}
#Override
public String toString() {
return "Make :"+ make + " Model :" + model;
}
}
Just printing a car
You can then use this as follows
public static void main(String[] args){
Car car=new Car();
car.setMake("Audi");
car.setModel("ModelName");
System.out.println(car);
}
Printing all of an array
Equally if this exists in an array of cars (I'm using the constructor I introduce in the notes for brevity)
public static void main(String[] args){
Car[] cars=new Car[3];
cars[0]=new Car("Audi","ModelName");
cars[1]=new Car("BMW","ModelName");
cars[2]=new Car("Honda","ModelName");
for(int i=0;i<cars.length;i++){
System.out.println(cars[i]);
}
}
Printing after user selects an index
public static void main(String[] args){
Car[] cars=new Car[3];
cars[0]=new Car("Audi","ModelName");
cars[1]=new Car("BMW","ModelName");
cars[2]=new Car("Honda","ModelName");
Scanner scan=new Scanner(System.in);
System.out.println("Select index to print, should be between 0 and " + (cars.length-1));
//checks that user actually inputs an integer,
//checking its in range is left as an excercise
while (scan.hasNextInt()==false){
scan.next(); //consume bad input
System.out.println("Select index to print, should be between 0 and " + (cars.length-1));
}
int index=scan.nextInt();
System.out.println(cars[index]);
}
Notes
It seems like the make and model are essential to the workings of the car class, consider changing your constructor to take them as arguments
public Car(String make, String model){
this.make=make;
this.model=model;
}
All this assumes you already have the element you wish to print
class Car{
String make ;
String model;
#Override
public String toString() {
return "make :"+ this.make + " model :" + this.model;
}
}
List<Car> list= new ArrayList<Car>();
Car c1=new Car();
Car c2=new Car();
Car c3=new Car();
Car c4=new Car();
list.add(c1);
list.add(c2);
list.add(c3);
list.add(c4);
for(Car car : list)
{
System.out.println(car);
}
public class Car {
private String make;
private String model;
public Car(String make, String model) {
this.make = make;
this.model = model;
}
public void setMake (String str1) {
make = str1;
}
public void setModel (String str2) {
model = str2;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
}
public class PrintCars {
public static void main(String []args) {
Car cars[] = new Car[10];
// Assume you populate the array with Car objects here by code
cars[0] = new Car("make1", "model1");
for (Car carObj : cars) {
System.out.println(carObj.getmake());
System.out.println(carObj.getmodel());
}
}
}
Try this
private static String toString(sample[] carTypes)
{
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < carTypes.length; i++)
{
if (carTypes[i] != null)
{
stringBuilder.append(" Name : ");
stringBuilder.append(carTypes[i].name);
stringBuilder.append(",");
stringBuilder.append(" Model : ");
stringBuilder.append(carTypes[i].model);
stringBuilder.append(",");
}
}
return stringBuilder.toString().substring(0, stringBuilder.toString().length() - 1);
}
output :
Name : BMW, Model : Mark 3, Name : AUDI, Model : A-6, Name : BENZ, Model : BZ