Displaying inputs using methods in java - java

I copied this code in a book I found in the internet about Data Structures and Algorithm in Java. This is the code:
//GameEntry Class
public class GameEntry
{
protected String name;
protected int score;
public GameEntry(String n, int s) {
name = n;
score = s;
}
public String getName() { return name; }
public int getScore() { return score; }
public String toString() {
return "(" + name + ", " + score + ")";
}
}
//Scores Class
public class Scores
{
public static final int maxEntries = 10;
protected int numEntries;
protected GameEntry[] entries;
public Scores(){
entries = new GameEntry[maxEntries];
numEntries = 3;
}
public String toString() {
String s = "[";
for(int i=0; i<numEntries; i++) {
if(i > 0) {
s = s + ", ";
}
s = s + entries[i];
}
return s + "]";
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Scores s = new Scores();
for(int i=0; i<s.numEntries; i++){
System.out.print("Enter Name: ");
String nm = input.nextLine();
System.out.print("Enter Score: ");
int sc = input.nextInt();
input.nextLine();
s.entries[i] = new GameEntry(nm, sc);
System.out.println(s.toString());
}
}
}
This runs well like what it said in the book. It outputs:
//just an example input
[(John, 89), (Peter, 90), (Matthew, 90)]
What I don't understand is how did the names inside the parenthesis which is made in the GameEntry Class inside its toString() method (John, 89) is being outputted and yet what I written inside the System.out.println(s.toString); in Scores Class only pertains to the toString method in its own class?
I am expecting that the brackets in the toString() method in the Scores Class will be outputting only the brackets "[]" for it is the only one that I called in the main method... Can anyone please explain this to me how did this happened? I am little bit new in Java Data Structures.
Another thing I try to do this in a different sample program following the concept of what I see in the book..
This my codes:
//FirstClass
public class FirstClass
{
protected String name;
protected int age;
protected FirstClass(String n, int a) {
name = n;
age = a;
}
public String getName() { return name; }
public int getAge() { return age; }
public String printData() {
return "My name is: " + name + ", I am " + age + " years old";
}
}
//Second Class
import java.util.Scanner;
public class SecondClass
{
protected FirstClass f;
private static String nm;
private static int ag;
public SecondClass() {
f = new FirstClass(nm, ag);
}
public String toString(){
return "(" + f + ")";
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
SecondClass s = new SecondClass();
System.out.print("Enter Name: ");
nm = input.nextLine();
System.out.print("Enter Age: ");
ag = input.nextInt();
input.nextLine();
s.f = new FirstClass(nm, ag);
System.out.println(s.toString());
}
}
//Sample Input
Enter Name: John
Enter Age: 16
The output of this is:
(FirstClass#7cc7b1d2)
What I am expecting is:
("My name: is John, I am 16 years old")
What is my error in this???

Related

Java adding from multiple classes with an interface

Based on the following UML class diagram I am trying to get the total population of all the House and ApartmentBuilding objects using an interface (Dwelling) and I am stuck on how to proceed. I have included the code I have so far.
Dwelling:
interface Dwelling {
int getNumberOfOccupants();
}
House:
import javafx.scene.canvas.GraphicsContext;
import java.util.Scanner;
public class House extends Building implements Dwelling {
private final int bedrooms;
private final int occupants;
private House(String name, double xPosition,int bedrooms, int occupants){
super(name,xPosition);
this.bedrooms = bedrooms;
this.occupants = occupants;
}
public static House create() {
Scanner scan = new Scanner(System.in);
House a;
System.out.println("Enter name of the House: ");
String name = scan.nextLine();
System.out.println("Enter XPosition of the House: ");
int xPosition = scan.nextInt();
System.out.println("Enter number of bedrooms: ");
int bedrooms = scan.nextInt();
System.out.println("Enter number of occupants: ");
int occupants = scan.nextInt();
a = new House(name, xPosition, bedrooms, occupants);
return a;
}
public void draw(GraphicsContext canvas){
}
#Override
public String toString(){
return "House: " + "bedrooms= " + bedrooms + " occupants= " + occupants + "\n" + super.toString();
}
#Override
public int getNumberOfOccupants() {
return occupants;
}
}
ApartmentBuilding:
import javafx.scene.canvas.GraphicsContext;
import java.util.Scanner;
public class ApartmentBuilding extends HighRise implements Dwelling{
private final int occupantsPerFloor;
private ApartmentBuilding(String name, double xPosition, int numberOfFloors, int occupantsPerFloor){
super(name, xPosition, numberOfFloors);
this.occupantsPerFloor = occupantsPerFloor;
}
public static ApartmentBuilding create() {
Scanner scan = new Scanner(System.in);
ApartmentBuilding a;
System.out.println("Enter name of the Apartment Building: ");
String name = scan.nextLine();
System.out.println("Enter XPosition of the Apartment Building: ");
int xPosition = scan.nextInt();
System.out.println("Enter number of floors: ");
int numberOfFloors = scan.nextInt();
System.out.println("Enter number of occupants per floor: ");
int occupantsPerFloor = scan.nextInt();
a = new ApartmentBuilding(name, xPosition, numberOfFloors, occupantsPerFloor);
return a;
}
public void draw(GraphicsContext canvas){
}
#Override
public String toString(){
return "Apartment Building: " + "occupantsPerFloor= " + occupantsPerFloor + "\n" + super.toString() + "\n";
}
#Override
public int getNumberOfOccupants() {
return numberOfFloors * occupantsPerFloor;
}
}
Building:
import javafx.scene.canvas.GraphicsContext;
public class Building implements Drawable {
private final String name;
private final double xPosition;
public Building(String name, double xPosition){
this.name = name;
this.xPosition = xPosition;
}
public String getName(){
return name;
}
public void draw(GraphicsContext canvas) {
}
public double getXPosition() {
return xPosition;
}
#Override
public String toString(){
return "Type... Building: " + "name= " + getName() + ", xPosition= " + getXPosition() + "\n";}
}
HighRise:
public class HighRise extends Building{
int numberOfFloors;
public HighRise(String name, double xPosition, int numberOfFloors) {
super(name, xPosition);
this.numberOfFloors=numberOfFloors;
}
public int getNumberOfFloors(){
return numberOfFloors;
}
#Override
public String toString() {
return "Type... HighRise: " + "numberOfFloors= " + getNumberOfFloors() + "\n" + super.toString();
}
}
Village:
import javafx.scene.canvas.GraphicsContext;
import java.util.Scanner;
public class Village extends Building{
private static String name;
private static int xPosition;
public static final double Y_FLOOR = 300;
private int size;
private final String villageName;
private final Building[] buildings;
private Village(String villageName, int size){
super(name, xPosition);
this.size = size;
this.villageName = villageName;
this.buildings = new Building[size];
}
public static Village create() {
Scanner scan = new Scanner(System.in);
Village a;
System.out.println("Enter name of village: ");
String villageName = scan.nextLine();
System.out.println("Enter number of buildings: ");
int num = scan.nextInt();
a = new Village(villageName, num);
for(int i = 0; i < num; i++) {
System.out.println("Enter type of Building: 1= House, 2= Apartment, 3= Store ");
int choice = scan.nextInt();
if (choice == 1){
a.buildings[i] = House.create();
}
if (choice == 2){
a.buildings[i] = ApartmentBuilding.create();
}
}
return a;
}
public int getPopulation(){
return size;
}
public void draw(GraphicsContext canvas){
}
public String toString(){
String str = "\n"+ "Village of " + villageName + "\n\n";
for (int i=0; i<buildings.length; i++) {
str = str + buildings[i].toString() + "\n"; // this adds each buildings information to the string
}
return str;
}
}
I am new at programming and trying my best to learn but I am getting stuck on this, unfortunately.
..I am trying to get the total population of all the House and ApartmentBuilding objects using an interface (Dwelling)..
You can not get the population while using that UML. Please try modify a bit as below.
First, Dwelling must declaire getPopulation();
Implementing getPopulation() within House and ApartmentBuilding
You need a variable to keep the population within House and ApartmentBuilding class as well (it will be returned while calling getPopulation()).
After that, you able to cast House and ApartmentBuilding to Dwelling. Then dwelling.getPopulation(). Hope it is useful.

I don't know how to do an array to store for each semester the details. I am supposed to create a subclass of the class Student

The question wants me to do:
An array of Finance called financeRecord to store the details
of the payments for each semester.
This is my code
package lab5;
class Student_U extends Student {
public String student_name;
private String studentID;
public int student_age;
private byte currentSemester;
private byte TotalFinanceRecord;
private String cohort;
public Student_U() {
student_name = " ";
studentID = " ";
student_age = 0;
currentSemester = 1;
TotalFinanceRecord = 0;
cohort = " ";
}
public Student_U(String student_name, String studentID, int student_age,
String course, String year,
String section, String subject, String student_name2,
String studentID2, int student_age2,
byte currentSemester, byte totalFinanceRecord, String cohort) {
super(student_name, studentID, student_age, course, year,
section, subject);
student_name = student_name2;
studentID = studentID2;
student_age = student_age2;
this.currentSemester = currentSemester;
TotalFinanceRecord = totalFinanceRecord;
this.cohort = cohort;
}
public String getStudent_name() {
return student_name;
}
public void setStudent_name(String student_name) {
this.student_name = student_name;
}
public String getStudentID() {
return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public int getStudent_age() {
return student_age;
}
public void setStudent_age(int student_age) {
this.student_age = student_age;
}
public byte getCurrentSemester() {
return currentSemester;
}
public void setCurrentSemester(byte currentSemester) {
this.currentSemester = currentSemester;
}
public byte getTotalFinanceRecord() {
return TotalFinanceRecord;
}
public void setTotalFinanceRecord(byte totalFinanceRecord) {
TotalFinanceRecord = totalFinanceRecord;
}
public String getCohort() {
return cohort;
}
public void setCohort(String cohort) {
this.cohort = cohort;
}
public void initStudent() {
}
public void print() {
System.out.print("Student name: " + student_name + " ");
System.out.print("\nMatric No: " + studentID + " ");
System.out.print("\nAge: " + student_age + " ");
System.out.print("\nCurrent Semester: " + currentSemester + " ");
System.out.print("\nCohort: " + cohort + " ");
System.out.println();
}
}
Please help me fix my code I would appreciate it so much.
This is my lab assignment which needs to be submitted by tomorrow.
You could try this, but it's also better to review standard java concepts (arrays, classes, etc). After, just adapt your code as suitable.
public class Finance extends Student
{
public static void main(String args[])
{
Finance f1 = new Finance("Student_1");
System.out.println(f1);
f1.setPayment(1, 10);
System.out.println(f1);
f1.setPayment(2, 10.77);
System.out.println(f1);
Student s2 = new Student("Student 2");
Finance f2 = new Finance(s2);
f2.setPayment(2, 88.77);
System.out.println(f2);
}
Double finaceRecord[] = new Double[3];
private void initPayment()
{
for(int i=0;i<finaceRecord.length;i++)
{
finaceRecord[i]=0.0;
}
}
public Finance(Student s)
{
super(s.name);
initPayment();
}
public Finance(String name)
{
super(name);
initPayment();
}
//store first or second
public void setPayment(int i, double d)
{
if(d<=0) return;
if(i==1)
{
finaceRecord[i] = d;
}
else
{
finaceRecord[2] = d;
}
finaceRecord[0] = finaceRecord[2] + finaceRecord[1];
}
public String toString()
{
return "name="+super.name+", Total Paid="+finaceRecord[0]+","
+ " Sem1="+finaceRecord[1]+", Sem2="+finaceRecord[2];
}
}
...
public class Student
{
String name;
int Semester;
Student(String name)
{
this.name = name;
this.Semester = 1;
}
}
Ouptut
name=Student_1, Total Paid=0.0, Sem1=0.0, Sem2=0.0
name=Student_1, Total Paid=10.0, Sem1=10.0, Sem2=0.0
name=Student_1, Total Paid=20.77, Sem1=10.0, Sem2=10.77
name=Student 2, Total Paid=88.77, Sem1=0.0, Sem2=88.77
from what I understand you are supposed to create an array of Finance type
Finance []financeRecord = new Finance[totalFinanceRecord];
and then you can access the values of Finance class
financeRecord[indexNumber].methodName();

Java Objects and Classes - something wrong with my code?

I'm having issues trying to figure out the problem with my code. Basically, the program is supposed to be a GPA calculator.
The first part:
import java.io.*;
import java.util.ArrayList;
public class Student {
// Data
private String name;
private int student_id;
private double gpa;
private ArrayList<Integer> grades;
private int num_courses;
// Methods
// Constructor Method
public Student() {
name = "";
student_id = 0;
gpa = 0.0;
grades = new ArrayList<Integer>();
}
// Accessor Methods (getters and setters)
public void setGrade(int g) {
grades.add(g);
calcGPA();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStudent_id() {
return student_id;
}
public void setStudent_id(int student_id) {
this.student_id = student_id;
}
public double getGPA() {
return gpa;
}
public void setGpa(double gpa) {
this.gpa = gpa;
}
public int getNum_courses() {
return num_courses;
}
public void setNum_courses(int num_courses) {
this.num_courses = num_courses;
}
// Functional Methods
public void calcGPA() {
int sum_grades = 0;
for (int i=0; i<this.grades.size(); i++) {
sum_grades = sum_grades * this.grades.get(i);
}
gpa = sum_grades/this.grades.size();
}
public void displayGrades() {
for (int i=0; i<this.grades.size(); i++) {
System.out.println("Grade in course " + i + ": " + this.grades.get(i));
}
}
}
and the second class:
import java.io.*;
public class TestStudent {
public static void main(String[] args) {
Student s1 = new Student(); //Object creation/instantiation
s1.setName("John Rodgers");
s1.setStudent_id(111);
s1.setGrade(3);
s1.setGrade(4);
s1.setGrade(3);
System.out.println("Student " + s1.getName() + "\'s GPA: " + s1.getGPA());
Student s2 = new Student();
s2.setName("Jenny Marshall");
s2.setStudent_id(333);
s2.setGrade(4);
s2.setGrade(4);
s2.setGrade(3);
s2.setGrade(4);
s2.setGrade(3);
System.out.println("Student " + s2.getName() + "\'s GPA: " + s2.getGPA());
}
}
The output shows as:
Student John Rodgers's GPA: 0.0
Student Jenny Marshall's GPA: 0.0
The GPA is supposed to be calculated but it appears as 0.0.
Your calcGPA() logic is incorrect (you are doing a product with 0), rather you should sum all grades as shown below:
public void calcGPA(){
int sum_grades = 0;
for(int i=0; i<this.grades.size(); i++){
sum_grades = sum_grades + this.grades.get(i);//sum the grades
}
gpa = sum_grades/this.grades.size();
}

how we can call the object of second call in the first class in java

here i have a code which i am giving u please correct my code and run it when i enter the extend or make object of attendence class in the student class then attendence class is not worked
import java.util.Scanner;
public class Attendence {
private int c;
public Attendence(){
}
public void project(){
System.out.println("Enter the total no of students of the class");
Scanner input=new Scanner(System.in);
int c=input.nextInt();
String[][] array=new String[c][6];
for(int i=0; i<c; i++){
for(int j=0;j<6;j++){
array[i][j]=input.next();
}}
System.out.println("RollNO \t Name \t Class \t Attendence Mark \tTeacher Name \tSubject Name");
for(int k=0; k<c; k++){
for(int l=0;l<6;l++){
System.out.print(array[k][l]+ "\t\t" );
}
System.out.println("\n");
}
}}
here this is second class
import java.util.Scanner;
public class student extends Attendence {
private int password;
private String ID;
public student(int passsword , String ID){
super();
this.password= password;
this.ID=ID;
}
public int getPassword() {
return password;
}
public void setPassword(int password) {
this.password = password;
}
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public void mainfunction(){
Scanner input=new Scanner(System.in);
System.out.println("enter the password");
int password=input.nextInt();
System.out.println("enter the ID");
String ID=input.next();
if(password==123 || ID=="abc"){
System.out.println("u enter right password and ID so you can acess the Attendance sheet");
}
else
System.out.println("u enter wrong password and ID so you can't acess the Attendance sheet");
}
#Override
public String toString(){
return this.getPassword()+ this.getID()+super.toString();
}
public static void main(String[] args) {
Attendence z = new Attendence();
student a=new student(123, "abc");
//a.mainfunction();
a.mainfunction();
z.project();
}
}
Call the Attendance class in if loop(if password and ID is correct)..and close the input(Scanner) object..
Student.class
import java.util.Scanner;
public class Student extends Attendence {
private int password;
private String ID;
public Student(int passsword, String ID) {
super();
this.ID = ID;
}
public static void main(String[] args) {
Student a = new Student(123, "abc");
a.mainfunction();
}
public void mainfunction() {
Scanner input = new Scanner(System.in);
System.out.println("enter the password");
int password = input.nextInt();
System.out.println("enter the ID");
String ID = input.next();
if (password == 123 || ID == "abc") {
System.out.println("u enter right password and ID so you can acess the Attendance sheet");
Attendence z = new Attendence();
z.project();
} else {
System.out.println("u enter wrong password and ID so you can't acess the Attendance sheet");
}
input.close();
}
#Override
public String toString() {
return this.getPassword() + this.getID() + super.toString();
}
public int getPassword() {
return password;
}
public void setPassword(int password) {
this.password = password;
}
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
}
Attendance.class
import java.util.Scanner;
public class Attendence {
public void project() {
System.out.println("Enter the total no of students of the class");
Scanner input = new Scanner(System.in);
Integer c = input.nextInt();
String[][] array = new String[c][6];
for (int i = 0; i < c; i++) {
System.out.println("Enter the Roll No,Name,Class,Attendance Mark,Teacher Name,Student Name for student "+(i+1));
for (int j = 0; j < 6; j++) {
array[i][j] = input.next();
}
}
System.out.println("RollNO \t Name \t Class \t Attendence Mark \tTeacher Name \t Subject Name");
for (int k = 0; k < c; k++) {
for (int l = 0; l < 6; l++) {
System.out.print(array[k][l] + "\t\t");
}
System.out.println("\n");
}
input.close();
}
}
It is working as expected.
I tried to execute your code got following output . check it this is what you expect.
enter the password
123
enter the ID
abc
u enter right password and ID so you can acess the Attendance sheet
Enter the total no of students of the class
1
2
xyz
2
2
2
abc
RollNO Name Class Attendence Mark Teacher Name S
ubject Name
2 xyz 2 2 abc
or else ask precisely what you exactly want.

Having trouble with searching in an Arraylist

I'm doing a program for school that requires me to do things like add/remove/edit/search bands on the Hall of Fame, with which the user adds bands to. I'm having trouble getting the index of a band in the arraylist hallOfFame. Can anybody recommend any solution to this?
Here is my HallofFame Class:
import java.util.*;
public class HallofFame
{
public static ArrayList<Band> hallOfFame = new ArrayList<Band>();
public static Scanner scan = new Scanner(System.in);
public static void main(String[]args){
boolean running = true;
while(running == true){
System.out.println("What would you like to do?");
System.out.println("");
System.out.println("1. Add");
System.out.println("2. Remove");
System.out.println("3. Edit");
System.out.println("4. Clear");
System.out.println("5. Search");
System.out.println("6. Quit");
System.out.println("");
String choice = scan.nextLine();
if(choice.equals ("1")){
add();
}
else if(choice.equals ("2")){
remove();
}
else if(choice.equals ("3")){
edit();
}
else if(choice.equals ("4")){
clear();
}
else if(choice.equals ("5")){
search();
}
else if(choice.equals ("6")){
running = false;
}
}
}
public static void add(){
Scanner booblean = new Scanner(System.in);
System.out.println("What is the name of the band you would like to add?");
String name = scan.nextLine();
System.out.println("What kind of genre is this band?");
String genre = scan.nextLine();
System.out.println("How many members are in the band?");
int numMem = scan.nextInt();
System.out.println("How many songs does this band have?");
int numSongs = scan.nextInt();
System.out.println("How many albums does this band have?");
int numAlbs = scan.nextInt();
System.out.println("Is this band currently active?");
String yesno = booblean.nextLine();
boolean isActive = false;
if(yesno.equalsIgnoreCase ("yes")){
isActive = true;
}
Band b1 = new Band(name, genre, numMem, numSongs, numAlbs, isActive);
hallOfFame.add(b1);
System.out.println("");
System.out.println("The band " + name + " has been added to the database.");
System.out.println("");
}
public static void remove(){
}
public static void edit(){
System.out.println("What band info do you want to edit?");
String editband = scan.nextLine();
}
public static void search(){
System.out.println("What band are you looking for?");
String searchband = scan.nextLine();
}
public static void clear(){
hallOfFame.clear();
}
}
And here's the code to the class Band:
public class Band
{
//1.Class Variables
private String nameOfBand;
private String[] members;
private String genre;
private int numberOfMembers;
private int numberOfSongs;
private int numberOfAlbums;
private boolean isActive;
//2. Constructors
public Band(String name, String genre, int numMem, int numSongs, int numAlbs, boolean isActive)
{
}
//3. Methods
//setters
public void setName(String newName)
{
nameOfBand = newName;
}
public void setGenre(String s)
{
genre = s;
}
public void setNumberOfMembers(int num)
{
numberOfMembers = num;
}
public void setNumberOfSongs(int numsongs){
numberOfSongs = numsongs;
}
public void setNumberOfAlbums(int numalbs){
numberOfAlbums = numalbs;
}
public void setIsActive(boolean isactive){
isActive = isactive;
}
public String getName()
{
return nameOfBand;
}
public String getGenre(){
return genre;
}
public int getNumberofMembers(){
return numberOfMembers;
}
public int getNumberofSongs(){
return numberOfSongs;
}
public int getNumberofAlbums(){
return numberOfAlbums;
}
public boolean getIsActive(){
return isActive;
}
#Override public String toString()
{
String output = "";
output += "Name: " + nameOfBand + "\n";
output += "Genre: " + genre + "\n";
output += "Number of members: " + numberOfMembers + "\n";
output += "Number of songs: " + numberOfSongs + "\n";
output += "Number of albums: " + numberOfAlbums + "\n";
output += "Is this band active: " + isActive + "\n";
return output;
}
}
You can do the following code to search Band with name in ArrayList.
public static void search(){
System.out.println("What band are you looking for?");
String searchband = scan.nextLine();
boolean bandFooud = false;
for(Band band : hallOfFame)
{
if(band.getName().equals(searchband))
{
bandFooud = true;// Set the flag to true to indicate the band is found.
//Make your code to display the band information here.
break;
}
}
if(!bandFooud){
System.out.printf("Band %s is not found.");
}
}
Maybe you want something like this
public static Band search(){
System.out.println("What band are you looking for?");
String searchband = scan.nextLine();
for (Band b : hallOfFame){
if (searchBand.equals(b.name){
return b;
break;
}
}
return null;
}
Also, consider override the toString() method in Band if you want the search() method to return void and just print out the Band info.
public class Band
{
//1.Class Variables
private String nameOfBand;
private String[] members;
private String genre;
private int numberOfMembers;
private int numberOfSongs;
private int numberOfAlbums;
private boolean isActive;
//2. Constructors
public Band(String name, String genre, int numMem, int numSongs,
int numAlbs, boolean isActive)
{
nameOfBand = name;
this.genre = genre;
numberOfMemembers = numMem;
numberOfSongs = numSongs;
numberOfAlbums = numAlbs;
this.isActive = isActive;
}
#Override
public String toString(){
return "Name: " + nameOfBand "
+ "Genre: " + genre
+ " Members: " + numOfMembers
+ " Songs: " + numOfSongs
+ " Albums:" + numOfAlbums
+ " Active? " + isActive;
}
Then you could do this
public static void search(){
System.out.println("What band are you looking for?");
String searchband = scan.nextLine();
for (Band b : hallOfFame){
if (searchBand.equals(b.name){
System.out.println(b);
break;
}
}
}

Categories

Resources