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?
Related
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;
}
I have been working on an assignment and i am stuck at here. Basically i have 1 class which defines all functions and members.
And another class to initialize and manipulate objects.
Here is my first class code.
public class cyryxStudent_association {
String studentID, studentName, studentCourse_level, studentTitle;
int course_completed_year;
static double registration_fee;
double activity_fee;
double total_amt;
//Default constructor
cyryxStudent_association ()
{
studentID = "Null";
studentName = "Null";
studentCourse_level = "Null";
studentTitle = "Null";
course_completed_year = 0;
}
//Parameterized Constructor
cyryxStudent_association (String id, String name, String course_level, String title, int ccy)
{
this.studentID = id;
this.studentName = name;
this.studentCourse_level = course_level;
this.studentTitle = title;
this.course_completed_year = ccy;
}
//Getters
public String getStudentID ()
{
return studentID;
}
public String getStudentName ()
{
return studentName;
}
public String getStudentCourse_level ()
{
return studentCourse_level;
}
public String getStudentTitle ()
{
return studentTitle;
}
public int getCourse_completed_year ()
{
return course_completed_year;
}
public double getRegistration_fee ()
{
return registration_fee;
}
public double getActivity_fee ()
{
return findActivity_fee(registration_fee);
}
public double getTotal_amt ()
{
return total_amt(registration_fee, activity_fee);
}
//Setters
public void setStudentID (String id)
{
studentID = id;
}
public void setStudentName (String name)
{
studentName = name;
}
public void setStudentCourse_level (String course_level)
{
studentCourse_level = course_level;
}
public void setStudentTitle (String title)
{
studentTitle = title;
}
public void setCourse_completed_year (int ccy)
{
course_completed_year = ccy;
}
//Find registration fee method
public static double findRegistration_fee (String course_level)
{
if (course_level.equalsIgnoreCase("Certificate"))
{
registration_fee = 75;
}
else if (course_level.equalsIgnoreCase("Diploma"))
{
registration_fee = 100;
}
else if (course_level.equalsIgnoreCase("Degree"))
{
registration_fee = 150;
}
else if (course_level.equalsIgnoreCase("Master"))
{
registration_fee = 200;
}
return registration_fee;
}
//Find activity method
public static double findActivity_fee (double registration_fee)
{
return registration_fee * 0.25;
}
//Find total amount
public static double total_amt (double registration_fee, double activity_fee)
{
return registration_fee + activity_fee;
}
//To string method
public String toString ()
{
return "ID: "+getStudentID()+"\nName: "+getStudentName()+"\nCourse Level:
"+getStudentCourse_level()+"\nTitle: "+getStudentTitle()+"\nCourse Completed Year:
"+getCourse_completed_year()+"\nRegistration Fee: "+getRegistration_fee()+"\nActivity Fee:
"+getActivity_fee()+"\nTotal Amount: "+getTotal_amt ();
}
}
And here is my second class code.
import java.util.Scanner;
public class test_cyryxStudent_association {
public static void main (String[] args)
{
Scanner sc = new Scanner (System.in);
int num, i;
System.out.println("Welcome!");
System.out.println("\nEnter the number of students: ");
num = sc.nextInt();
sc.nextLine();
cyryxStudent_association Std[] = new cyryxStudent_association[num];
for (i = 0; i < Std.length; i++)
{
System.out.println("\nEnter ID: ");
Std[i].setStudentID(sc.nextLine());
System.out.println("Enter Name: ");
Std[i].setStudentName(sc.nextLine());
System.out.println("Enter Course Level [Certificate, Diploma, Degree, Master]: ");
Std[i].setStudentCourse_level(sc.nextLine());
System.out.println("Enter Title: ");
Std[i].setStudentTitle(sc.nextLine());
Std[i].getRegistration_fee();
Std[i].getActivity_fee();
Std[i].getTotal_amt();
}
for (i = 0; i < Std.length; i++)
{
System.out.println("\nStudent " + i + 1 + " Information");
System.out.println("===================================");
Std[i].toString();
}
sc.close();
}
}
I get an error when values in the for loop. Can someone help me? I'm pretty new to programming and studying java for 2 months now. What am i doing wrong?
Here is my objectives.
Create an array of objects and get user input for number of objects to be manipulated.
Read and display array of object values.
Thank you!
You have to initialize the objects of your array.
After the line:
cyryxStudent_association Std[] = new cyryxStudent_association[num];
do a for loop like:
for(i = 0; i<std.length; i++){
std[i] = new cyryxStudent_association();
}
I'm a beginner in object-oriented programming and this is my first little project.I've heard that here everyone can help you in your code and this is my first time.Anyway, my problem why array doesn't store any value?
Here is the code:
public class Information {
private IT_Members[] member= new IT_Members[10];
private int counter = 0;
Information()
{
for ( int ctr=0;ctr<member.length;ctr++)
{
member[ctr] = new IT_Members ();
}
}
public void Add(IT_Members member)
{
if(counter<10)
{
this.member[counter].setName(member.getName());
this.member[counter].setDeparment(member.getDeparment());
this.member[counter].setPostion(member.getPostion());
this.member[counter].setID(member.getID()+counter);
counter++;
}
else
System.out.println("Add List Full");
}
public void Display()
{
if (counter!=0)
{
for (int ctr=0;ctr<10;ctr++){
System.out.println(this.member[ctr].getName()+
this.member[ctr].getDeparment()+
this.member[ctr].getPostion()+
this.member[ctr].getID());
}
}
else
System.out.println("No member yet!");
}
Here is the Main class:
import java.util.Scanner;
import java.util.Arrays;
public class Interface {
public static void main(String[]args)
{
Scanner in=new Scanner(System.in);
IT_Members input1 = new IT_Members();
Information input2 = new Information();
int x=1;
while(x!=0)
{
System.out.println(" \n[1] Add new student member. \n[2] View members.\nChoose now: ");
int choose = in.nextInt();
switch (choose){
case 1:
System.out.println("Name: ");
input1.setName(in.nextLine());
System.out.println("Deparment: ");
input1.setDeparment(in.nextLine());
System.out.println("Postion: ");
input1.setPostion(in.nextLine());
System.out.println("Student record has been added. ");
break;
case 2:
input2.Display();
break;
}
}
.........................................................................
public class IT_Members {
private String name,deparment,postion;
private int ID=1000;
private int Flag=0;
IT_Members (){
}
IT_Members (String name, String deparment , String postion ,int ID , int Flag){
this.name= name;
this.deparment=deparment;
this.postion=postion;
this.ID=ID;
this.Flag=Flag;
}
public String getName (){
return this.name;
}
public String getDeparment (){
return this.deparment;
}
public String getPostion (){
return this.postion;
}
public int getID (){
return this.ID;
}
public int getFlag (){
return this.Flag;
}
public void setName (String name){
this.name = name;
}
public void setDeparment (String Deparment){
this.deparment = deparment;
}
public void setPostion (String postion){
this.postion = postion;
}
public void setID (int ID){
this.ID = ID;
}
public void setFlag (int Flag){
this.Flag = Flag ;
}
public String toStu()
{
String str = "";
str = "\nName: " + this.name +
"\nDeparment: " + this.deparment +
"\nPostion: " + this.postion +
"\nID: " + this.ID;
return str;
}
}
Please, I'm stuck with this I appreciate any help.
Thanks.
You never call the Add function in the Information class. Therefore you never initialize any of the array elements you then want to display.
You need to add input2.Add(input1) before you print that is has been added.
You have to create every time a new Object and in the end you have to add in the list.
import java.util.Scanner;
import java.util.Arrays;
public class Interface {
public static void main(String[]args)
{
Scanner in=new Scanner(System.in);
Information input2 = new Information();
int x=1;
while(x!=0)
{
System.out.println(" \n[1] Add new student member. \n[2] View members.\nChoose now: ");
int choose = in.nextInt();
switch (choose){
case 1:
IT_Members input1 = new IT_Members();// this need to be here so that every time crete new object
System.out.println("Name: ");
input1.setName(in.nextLine());
System.out.println("Deparment: ");
input1.setDeparment(in.nextLine());
System.out.println("Postion: ");
input1.setPostion(in.nextLine());
input2.Add(input1); // that was missing
System.out.println("Student record has been added. ");
break;
case 2:
input2.Display();
break;
}
}
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 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...