First, sorry if title is misleading or unclear, I'm new to Java and I couldn't find the correct way to describe it.
Below is a piece of my code, I have 3 classes, housing, management, and mainTest.
housing.java
public class housing {
private String occupantsName;
private double price;
public housing() {
occupantsName = "Noone";
price = 100.00;
}
public housing(String name, double pricing){
occupantsName = name;
price = pricing;
}
public void setName(String name){
occupantsName = name;
}
public void setPrice(double pricing){
price = pricing;
}
public String getName(){
return occupantsName;
}
public double getPrice(){
return price;
}
public String toString(){
return "Room occupied by " + occupantsName + " is priced at " + price;
}
}
management.java
public class management {
private housing[] house;
private int c;
public management(){
house = new housing[7];
c = 7;
}
public management(int noOfRoom){
if (noOfRoom>0&&noOfRoom<=10){
house = new housing[noOfRoom];
c = noOfRoom;
}
else{
house = new housing[7];
c = 7;
}
for (int i=0;i<c;i++){
house[i] = new housing();
if ((i|1)>i&&i!=0){
house[i].setPrice(150.00);
}
}
}
public String displayEven()
{
String all = "";
for (int i = 0;i<c;i++)
{
if ((i|1)>i&&i!=0)
all = all + house[i].toString() +"\n";
}
return all;
}
}
mainTest.java
import java.util.*;
public class mainTest {
public static void main(String[] args){
Scanner a = new Scanner(System.in);
management bad = new management(5);
System.out.println(bad.displayEven());
}
}
Current output when I run the program:
Room occupied by Noone is priced at 150.0
Room occupied by Noone is priced at 150.0
Is there any way to give an identifier representing the position of the data in the array index? In this case they are [2] and [4]. For example, something like:
2. Room occupied by Noone is priced at 150.0
4. Room occupied by Noone is priced at 150.0
Yes just how Guy Incognito discribed it change this
public String displayEven()
{
String all = "";
for (int i = 0;i<c;i++)
{
if ((i|1)>i&&i!=0)
all = all + house[i].toString() +"\n";
}
return all;
}
to this
public String displayEven()
{
String all = "";
for (int i = 0;i<c;i++)
{
if ((i|1)>i&&i!=0)
all = all + i + ". " + house[i].toString() +"\n";
}
return all;
}
Related
Hi guys i am fairly new to Java but ive come across a problem that i cant seem to fix, the problem is in the 'WashingMachine' Class its not displaying the 'spinSpeed' details , any answers will be appreciated
here are my codes:
enter code here
package test;
public class Client {
private String Name;
private String PhoneNo;
Client () {
Name = null;
PhoneNo= null;
}
Client (String N, String P){
Name = N;
PhoneNo = P;
}
public void setName(String N){
Name = N;
}
public void setPhoneNo(String P) {
PhoneNo = P;
}
public String getName(){
return Name;
}
public String setPhoneNo() {
return PhoneNo;
}
public String toString() {
return "\nName: "+ Name + "\nPhoneNo:"+ PhoneNo.toString();
}
}
enter code here
package test;
public class Machine {
private String Make;
private double Price;
private Client Cust;
public Machine(String make, double price, Client cust)
{
Make = make;
Price = price;
Cust = cust;
}
#Override
public String toString() {
return "\n" +"Make of machine: " + Make + "\n" + "Price: " + Price + "\n" + Cust.toString();
}
public String getMake() {
return Make;
}
public double getprice() {
return Price;
}
public Client getcust() {
return Cust;
}
}
enter code here
package test;
public class WashingMachine extends Machine {
private int spinSpeed;
public WashingMachine (String make, double price, Client cust, int spinSpeed){
super(make, price, cust);
}
#Override
public String toString() {
return "WashingMachine [spinSpeed=" + spinSpeed + ", spinSpeed()=" + spinSpeed() + "]";
}
public int spinSpeed() {
return spinSpeed;
}
enter code here
package test;
import java.util.ArrayList;
public class MachinePurchaseTestVerC {
public static void main(String [] args) {
ArrayList<Machine> gadgets = new ArrayList<Machine> ();
Client mCust2 = new Client("Paul", "0487654321");
Client mCust3 = new Client("Chandra", "0487651234");
Client wCust1 = new Client("Catherine", "0412345678");
Client wCust4 = new Client("Mike", "0412348756");
gadgets.add(new WashingMachine("Bosch", 549.50, wCust1, 3500));
gadgets.add(new Machine("Samsung", 678.50, mCust2));
gadgets.add(new Machine("Electrolux", 449.25, mCust3));
gadgets.add(new WashingMachine("LG", 500.00, wCust4, 3200));
for(int i = 0; i<gadgets.size(); i++){
System.out.println(gadgets.get(i).toString());
System.out.println("----------------------------------");
}
}
}
In your WashingMachine class, you forgot to set the speed in your constructor
public WashingMachine (String make, double price, Client cust, int spinSpeed){
super(make, price, cust);
this.spinSpeed = spinSpeed;
}
hope that helps :)
I've created a Java class called 'Book'. Using this class I'm willing to update information about a new object 'book1'. I'm also wanting to add Author information into the object 'book1'. So, I've dynamically allocated memory using a class-array called 'Author[ ]'. By this I mean there's a separate code in which I've created a class called 'Author' with its own set of instance variables. I'm not getting into that now. However, when I'm testing the class 'Book' using another class called 'TestBook' there's no compilation error BUT I'm getting the following message in the console window when I'm running the code:
Exception in thread "main" java.lang.NullPointerException
at Book.addAuthors(Book.java:34)
at TestBook.main(TestBook.java:12)
The code for 'Book' is shown below:
public class Book {
private String name;
private Author[] A = new Author[];
private int numAuthors = 0;
private double price;
private int qtyInStock;
public Book(String n, Author[] authors, double p) {
name = n;
A = authors;
price = p;
}
public Book(String n, Author[] authors, double p, int qIS) {
name = n;
A = authors;
price = p;
qtyInStock = qIS;
}
public Book(String n, double p, int qIS) {
name = n;
price = p;
qtyInStock = qIS;
}
public String getName() {
return name;
}
/*
public Author getAuthors() {
return A;
}
*/
public void addAuthors(Author newAuthor) {
A[numAuthors] = newAuthor; // THIS LINE IS WHERE THE ERROR POINTS TO
++numAuthors;
}
public void printAuthors() {
/*
for (int i = 0; i < A.length; i++) {
System.out.println(A[i]);
}
*/
for (int i = 0; i < numAuthors; i++) {
System.out.println(A[i]);
}
}
public void setPrice(double p) {
price = p;
}
public double getPrice() {
return price;
}
public void setqtyInStock(int qIS) {
qtyInStock = qIS;
}
public int getqtyInStock() {
return qtyInStock;
}
/*
public String getAuthorName() {
return A.getName();
}
public String getAuthorEmail() {
return A.getEmail();
}
public char getAuthorGender() {
return A.getGender();
}
*/
public String toString() {
/*
return getName() + " " + getAuthor() + " Book price: " + getPrice() +
" Qty left in stock: " + getqtyInStock();
*/
//return getName() + " is written by " + A.length + " authors.";
return getName() + " is written by " + numAuthors + " authors.";
}
}
The code for 'TestBook' is shown below:
public class TestBook {
public static void main(String args[]) {
//Author[] authors = new Author[2];
//authors[0] = new Author("Tapasvi Dumdam Thapashki", "tapasvi#thapashki.com", 'M');
//authors[1] = new Author("Paul Rand", "paulie#aol.com", 'M');
Book book1 = new Book("The Quickie Man", 69.00, 5);
//System.out.println(book1.toString());
//book1.setqtyInStock(5);
//System.out.println(book1.toString());
//System.out.println(book1.getAuthorName() + " " + book1.getAuthorEmail());
//book1.printAuthors();
book1.addAuthors(new Author("Linda Lee", "lindalee#grinchtown.com", 'F'));
book1.addAuthors(new Author("Joseph Caputo", "caputo#lfp.com", 'M'));
System.out.println(book1.toString());
book1.printAuthors();
}
}
The code for 'Author' is shown below:
public class Author {
private String name;
private String email;
private char gender;
public Author(String n, String e, char g) {
name = n;
email = e;
gender = g;
}
public String getName() {
return name;
}
public void setEmail(String e) {
email = e;
}
public String getEmail() {
return email;
}
public char getGender() {
return gender;
}
public String toString() {
return getName() + " [" + getGender() + "] " + getEmail();
}
}
I'd like some help with this.
Initialize Author array with proper size like private Author[] A = new Author[4];
You forgot to specify the size of the Array.
private Author[] A = new Author[15];
For making a dynamic array you can use ArrayList.
private ArrayList<Author> list = new ArrayList<Author>();
addAuthors()
public void addAuthors(Author newAuthor) {
list.add(newAuthor);
}
printAuthors()
public void printAuthors() {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
I'm learning java and my programming skills are are good. I have been asked to find out the problem with codes below. when I paste them on netbeans, the error that had been detected was in the public class CheckoutProgram (String wordIn = Keyboard.readInput(); and wordIn = Keyboard.readInput();) and I noticed that the public static void method was empty but I'm not sure it has anything to do with the error. I have tried to find a solution myself but I can't sort it out. Can you help me with this issue? please
import java.io.*;
import java.text.DecimalFormat;
public class CheckoutProgram {
public static void main (String[] args) {
}
public void start() {
SalesItem[] items = getStock();
System.out.print("Type item code (press enter to finish):");
String wordIn = Keyboard.readInput();
SalesItem[] goods = new SalesItem[1000];
int count = 0;
while (wordIn.length()>=4 && wordIn.length()<=4){
for (int i=0;i<items.length;i++) {
if (items[i] != null && wordIn.equals(items[i].getItemCode())){
System.out.println(items[i]);
goods[count] = items[i];
}
}
System.out.print("Type item code (press enter to finish):");
wordIn = Keyboard.readInput();
count++;
}
System.out.println();
System.out.println("==========Bill==========");
double amountDue = 0.0;
for (int i=0; i<count; i++){
System.out.println(goods[i]);
amountDue = amountDue + goods[i].getUnitPrice();
}
System.out.println();
System.out.println("Amount due: $" + new DecimalFormat().format(amountDue));
System.out.println("Thanks for shopping with us!");
}
// method to read in "stock.txt" and store the items for sale in an array of type SalesItem
private SalesItem[] getStock(){
SalesItem[] items = new SalesItem[1000];
try {
BufferedReader br = new BufferedReader(new FileReader("stock.txt"));
String theLine;
int count = 0;
while ((theLine = br.readLine()) != null) {
String[] parts = theLine.split(",");
items[count] = new SalesItem(parts[0],parts[1],Double.parseDouble(parts[2]));
if (parts.length==4){
String discount = parts[3];
String numPurchases = discount.substring(0, discount.indexOf("#"));
String price = discount.substring(discount.indexOf("#")+1);
items[count].setNumPurchases(Integer.parseInt(numPurchases));
items[count].setDiscountedPrice(Double.parseDouble(price));
}
count++;
}
}
catch (IOException e) {
System.err.println("Error: " + e);
}
return items;
}
}
import java.text.DecimalFormat;
public class SalesItem {
private String itemCode; //the item code
private String description; // the item description
private double unitPrice; // the item unit price
// An item may offer a discount for multiple purchases
private int numPurchases; //the number of purchases required for receiving the discount
private double discountedPrice; // the discounted price of multiple purchases
// the constructor of the SalesItem class
public SalesItem (String itemCode, String description, double unitPrice){
this.itemCode = itemCode;
this.description = description;
this.unitPrice = unitPrice;
}
// accessor and mutator methods
public String getItemCode(){
return itemCode;
}
public void setItemCode(String itemCode){
this.itemCode = itemCode;
}
public String getDescription(){
return description;
}
public void setDescription(String description){
this.description = description;
}
public double getUnitPrice(){
return unitPrice;
}
public void setUnitPrice(double unitPrice){
this.unitPrice = unitPrice;
}
public int getNumPurchases(){
return numPurchases;
}
public void setNumPurchases(int numPurchases){
this.numPurchases = numPurchases;
}
public double getDiscountedPrice(){
return discountedPrice;
}
public void setDiscountedPrice(double discountedPrice){
this.discountedPrice = discountedPrice;
}
// the string representation of a SalesItem object
public String toString(){
return description + "/$" + new DecimalFormat().format(unitPrice);
}
}
Keyboard most likely doesn't exist. It isn't a part of the standard Java library. You would have to import a class that uses Keyboard if you are trying to use some custom class to read user input.
I assume you are getting the error because you do not have the class Keyboard. Check for a file called Keyboard.java.. This is more of a comment than an answer.
Firstly you are using public for a class CheckoutProgram so the file name should be same as the class name when you used public access specifier for a class.
Secondly the Keyboard class is missing in your program so please check with these issues.
I have no idea why our professor is making us do this weird printing but its for our final, its due in an hour, and ive been trying to get it to run forever and I cant get anywhere. So i have four classes, MyWord, Section, Page and Newspaper. MyWord is just Myword. Section contains Section and MyWord. Page includes Section, Page, and MyWord. Newspaper contains them all. I have a main method that just prints off the info you type in. Here is the only example provided. All of my code is included from the classes to show I've actually done work and need help. thank you.
Word[] w = new Word[3]; //example
w[0] = new Word(“hello”);
w[1] = new Word(“bob”);
w[2] = new Word(“smith”);
Section s = new Section(w, 20);
s.print();
//the above call to print should print off the following or something
//very similar to the following:
//Section 20: hello bob smith
my classes are also here
public class MyWord
{
private String word;
public MyWord(){ //constructor
word = "";
}
public MyWord(String word){ //using this keyword to assign word
this.word=word;
}
public String getWord(){ //accessor
return word;
}
public void setWord(String word){ //mutator
this.word=word;
}
public void print(){
System.out.print(word);
}
}
public class Section
{
private MyWord[] words; //taking in MyWord
private int sectionNumber;
public Section(){ //default constructor
words = new MyWord[0];
sectionNumber = 0;
}
public Section(MyWord[] m, int num){ //constructor
words = m;
sectionNumber = num;
}
public int getSectionNumber(){ //accessor
return sectionNumber;
}
public void setSectionNumber(int num){ //mutator
sectionNumber = num;
}
public MyWord[] getWords(){ //accessor
return words;
}
public void setWords(MyWord[] m){ //mutator
words = m;
}
public void print(){
System.out.print("Section " + sectionNumber + ": ");
for(int i =0; i <words.length; i++){
words[i].print();
System.out.print(" ");
}
}
}
public class Page
{
private Section[] sections; //taking in other class
private int pageNumber;
public Page(){ //setting defaults
sections = new Section[0];
pageNumber = 0;
}
public Page(Section[] m, int num){ //passing in sections[]
sections = m;
pageNumber = num;
}
public int getPageNumber(){ //accessor
return pageNumber;
}
public void setPageNumber(int num){ //mutator
pageNumber = num;
}
public Section[] getSections(){ //accessor
return sections;
}
public void setSections(Section[] m){ //mutator
sections = m;
}
public void print(){
System.out.print("Page " + pageNumber + ": ");
for(int i =0; i <sections.length; i++){
sections[i].print();
System.out.print(" ");
}
System.out.println(" ");
}
}
public class Newspaper
{
private Page[] pages; //taking in Page[]
private String title;
private double price;
public Newspaper(){
pages = new Page[0];
title = "Comp Sci Newspaper"; //default title
price = 2.50; //default price
}
public Newspaper(Page[] m, double num, String t){
pages = m;
price = num; //assigning values
title = t;
}
public String getTitle(){ //accessor
return title;
}
public void setTitle(String t){ //mutator
title = t;
}
public Page[] getPages(){ //accessor
return pages;
}
public void setPages(Page[] m){ //mutator
pages = m;
}
public double getPrice(){ //accessor
return price;
}
public void setPrice(double num){ //mutator
price = num;
}
public void print(){
System.out.print("Newspaper " + title + " " + "Price: " + price);
for(int i =0; i <pages.length; i++){
pages[i].print();
System.out.print(" ");
}
System.out.println(" ");
}
}
I think you should be making your array as MyWord not Word, so :
MyWord[] w = new MyWord[3];
Then as far as I can see it might work? Can you say what happens when you try to run / compile it?
I'm here with my classes, my software is almost done after finishing last two things I will continue to GUI development. Anyway, here is my code:
public class Team
{
private String clubName;
private String preName;
private ArrayList<Branch> branches;
public Team(String clubName, String preName)
{
this.clubName = clubName;
this.preName = preName;
branches = new ArrayList<Branch>();
}
public Team() {
// TODO Auto-generated constructor stub
}
public String getClubName() { return clubName; }
public String getPreName() { return preName; }
public ArrayList<Branch> getBranches() { branches = new ArrayList<Branch>(branches);return branches; }
public void setClubName(String clubName) { this.clubName = clubName; }
public void setPreName(String preName) { this.preName = preName; }
public void setBranches(ArrayList<Branch> branches) { this.branches = new ArrayList<Branch>(branches); }
}
public class Branch
{
public ArrayList<Player> players = new ArrayList<Player>();
String brName;
public Branch() {}
public void setBr(String brName){this.brName = brName;}
public String getBr(){return brName;}
public ArrayList<Player> getPlayers() {players =new ArrayList<Player>(players); return players; }
public void setPlayers(ArrayList<Player> players) { this.players =new ArrayList<Player>(players); }
public String toString() {
return "Branches [" + brName + "]";}
}
public class Player
{
private String name;
private String pos;
private Integer salary;
private Integer number;
public Player(String name, String pos, Integer salary, Integer number)
{
this.name = name;
this.pos = pos;
this.salary = salary;
this.number = number;
}
public Player(){}
public String getName() { return name; }
public String getPos() { return pos; }
public Integer getSalary() { return salary; }
public Integer getNumber() { return number; }
public void setName(String name) { this.name = name; }
public void setPos(String pos) { this.pos = pos; }
public void setSalary(Integer salary) { this.salary = salary; }
public void setNumber(Integer number) { this.number = number; }
public String toString() {
return "Player [name=" + name + ", number=" + number + ", pos=" + pos
+ ", salary=" + salary + "]";
}
}
//TEST
String p1,p2;
int a1,a2;
String t, br;
System.out.print("Enter player name : ");
p1 = input.readLine();
System.out.print("Enter player position : ");
p2 = input.readLine();
System.out.print("Enter player salary : ");
a1 = Integer.parseInt(input.readLine());
System.out.print("Enter player number : ");
a2 = Integer.parseInt(input.readLine());
players[pCount].setName(p1);
players[pCount].setPos(p2);
players[pCount].setSalary(a1);
players[pCount].setNumber(a2);
ptmp.add(players[pCount]);
pCount++;
System.out.print("Enter the branch of player : ");
br = input.readLine();
int fff=0;
for(int i = 0; i<brCount;i++)
{
if(br.equals(myBranch[i].brName)==true){
myBranch[i].setPlayers(ptmp);fff=i;}
}
MY FIRST QUESTION : I'm trying to add a player to my system. When a player added I can easily add it to Branch class too and connect them. But I can't do it for Players' club. I mean I want to display which player plays in which club. But I can't do it.
MY SECOND QUESTION : Deleting a player is problem too. When I delete player it should be deleted everywhere. But couldn't figured that out.
In the test, you can see the display function I tried. It works fine for Branch-Player. And I wanna add Team connection too. Team-Branch-Player should be connected.
Q1: It depends how efficiently you want to do your searches.. for now, since you don't store back references you have to first search in which branch is your player and then search which is the club that contains your branch.
With good equals method for your Branch and Player class this is trivial:
for (Team t : teamList)
{
if (t.branches.contains(player))
return true;
}
return false;
But this won't be efficient since you'll have a O(n*m) complexity where n is the team size and m is the average branch size.
If you want something more efficient I'd suggest you to store backreferences inside your classes, you can have your Player class with two attributes
Branch currentBranch
Team currentTeam
and you can set them while you add the player to a branch/team.
Otherwise you can keep a separate HashMap that maps every player to his branch/team. Less memory efficient but quite straightforward.
Q2: to remove the Player from his branch/team you just have to know in which one he stays.. (using the answer to Q1), then before removing from players you just remove it from the corresponding branch/team:
Branch b = findWhichBranch(player);
Team t = findWhichTeam(player);
b.remove(player);
t.remove(player);
players[index] = null;
Of course if branch is implied by team you will just remove it from the branch, since there's no direct association between a player and a team.