How to compare attributes from multiple class instances? - java

Alright, so here's the pickle. I'm taking this course that teaches logic programming in Java. I only know a bit of JavaScript so Java is pretty much alien tech for me.
I'm doing this assignment where I need to create a conference manager app (which is console-based only). Each conference holds lectures (as many as you want). Each conference has attributes such as the conference manager's name, his telephone number, his hourly rate etc; and it's the same for the lectures. I wanted to be able to input these data with Scanner method. So this is what I did so far:
Started creating two classes:
1) a conference creator
import java.util.*;
public class Conference {
String nameConference;
String nameManagerConference;
String telManagerConference;
String dateStartConference;
String dateEndConference;
float hourlyRateManager;
float hoursAmountConference;
public void setConferenceData() {
Scanner keyboard = new Scanner(System.in);
System.out.print("Conference name: ");
this.nameConference = keyboard.nextLine();
System.out.print("Conference manager name: ");
this.nameManagerConference = keyboard.nextLine();
System.out.print("Conference manager telephone number: ");
this.telManagerConference = keyboard.nextLine();
System.out.print("Conference start date: ");
this.dateStartConference = keyboard.nextLine();
System.out.print("Conference end date: ");
this.dateEndConference = keyboard.nextLine();
System.out.print("Manager hourly rate: ");
this.hourlyRateManager = keyboard.nextFloat();
System.out.print("Conference amount of hours: ");
this.hoursAmountConference = keyboard.nextFloat();
System.out.println(this.nameManagerConference + ", manager of the conference " + "\"" + this.nameConference +"\"" + ", cost R$ " + (this.hoursAmountConference * this.hourlyRateManager));
}
}
2) a lecture creator
import java.util.*;
public class Lectures {
float totalCost = 0;
String lecturesList = "Lectures list: ";
ArrayList<Float> arrLecturesCostTotal = new ArrayList<>();
ArrayList<String> listLectures = new ArrayList<>();
public void getLecturesTotalCost() {
for (int i = 0; i < arrLecturesCostTotal.size(); i++) {
totalCost += arrLecturesCostTotal.get(i);
}
System.out.println("The total lectures cost is $ " + totalCost);
}
public void getLecturesList() {
for (int i = 0; i < listLectures.size(); i++) {
lecturesList += "\n" + "- " + listLectures.get(i);
}
System.out.println(lecturesList);
}
public class Lecture{
String lectureTitle;
String lectureStartHour;
String lecturerName;
String lecturerTelephone;
String lectureDescription;
float lecturerHourlyRate;
float lectureHoursAmount;
float lectureCost = 0;
public void setDataLecture() {
Scanner keyboard = new Scanner(System.in);
System.out.print("Lecture title: ");
this.lectureTitle = keyboard.nextLine();
System.out.print("Lecture start time: ");
this.lectureStartHour = keyboard.nextLine();
System.out.print("Lecturer name: ");
this.lecturerName = keyboard.nextLine();
System.out.print("Lecturer telephone number: ");
this.lecturerTelephone = keyboard.nextLine();
System.out.print("Lecture description: ");
this.lectureDescription = keyboard.nextLine();
System.out.print("Lecturer hourly rate ");
this.lecturerHourlyRate = keyboard.nextFloat();
System.out.print("Lecture hours amount: ");
this.lectureHoursAmount = keyboard.nextFloat();
this.lectureCost = this.lecturerHourlyRate * this.lectureHoursAmount;
System.out.println("The cost of the lecture " + this.lecturerName + " is $ " + this.lectureCost);
arrLecturesCostTotal.add(this.lecturerHourlyRate * this.lectureHoursAmount);
listLectures.add(this.lectureTitle + " by " + this.lecturerName);
}
}
}
As you can see, there are a lot of attributes to each class.
Then, I proceeded to create another class to create the objects using these setters (setConferenceData() and setDataLecture()).
public class Manager {
public static void main(String[] args) {
Conference conference01 = new Conference();
Lectures lectureSet = new Lectures();
Lectures.Lecture lecture01 = lectureSet.new Lecture();
Lectures.Lecture lecture02 = lectureSet.new Lecture();
conference01.setConferenceData();
lecture01.setDataLecture();
lecture02.setDataLecture();
lectureSet.getLecturesList();
lectureSet.getLecturesTotalCost();
}
}
So, one of the deliverables is a comparison between the lectures' costs. I need to return the most and the least expensive lectures (their costs and their names). However, I can't figure out how to do that because I don't know how to compare instances' attributes values. Specially because they're created by inputting data in the console.
My logic is probably wrong as I'm pretty much experimenting and crossing my fingers so I don't see an error in the console, but this is all I could come up with.
Could someone assist me, please?

Few tips here.
You probably should not call Scanner in you data classes. Instead call scanner in your main method and just feed the results to your classes through constructor or setters. This way you separate concerns and classes like Conference and Lecture don't need to know anything about your input method (scanner in this case).
Conference should contain lectures means that List<Lecture> should probably be field inside the class Conference among other fields.
Lecture should probably have two fields (among other stuff) double lengthHours and double hourlyCost. Then you could have a method in Lecture:
public double totalCost() {
return hourlyCost * lengthHours;
}
And then you could have a method in Conference:
public double totalCost() {
double lecturesTotal = 0.0;
for (Lecture lecture : lectures {
lecturesTotal += lecture.totalCost();
}
return lecturesTotal + //other stuff like conference managers pay;
}
Hope that gets you going in the right direction.

Related

Struggling with Java assignment that reads name, age and height

I am working on a java assignment for class. Very basic but just starting to learn programming. The main jist of the assignment is to write a Java program that reads a student name, his/her age, and his/her height (in feet) from the console and prints out all pieces of data related to a student on one line. This is what I have so far but I am getting a few errors.
import java.util.Scanner;
public class assignment1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String Name = Mike;
int age = 21;
double height = 5.9;
Scanner inReader = new Scanner(System.in);
System.out.println("Mike");
Name = inReader.nextLine("Mike");
System.out.print("21");
age = inReader.nextInt("21");
System.out.println("5.9");
height = inReader.nextDouble ("5.9");
System.out.println ("Mike" + "21" + "5.9");
}
}
You are off track in a few ways.
inReader.nextLine("Mike"); should be inReader.nextLine();. You cannot put something between those brackets in this case.
String Name = Mike; int age = 21;double height = 5.9;
just need to be declared. You want to enter the data in the console, not the code itself.
String Name; int age = 0;double height = 0;
System.out.println("Mike"); is not where you put inputs. Rather, it is where you put prompts that go to the user. You want to ask the user for their input there.
To print the variables in a string, you want to put the variable name in the string like so: System.out.println (height);
The full working code is below, but I encourage you to try and understand how this works. Feel free to ask any questions in the comments below.
public static void main(String[] args) {
// TODO Auto-generated method stub
String Name;
int age = 0;
double height = 0;
Scanner inReader = new Scanner(System.in);
System.out.println("What is their name?");
Name = inReader.nextLine();
System.out.println("What is their age?");
age = inReader.nextInt();
System.out.println("What is their height?");
height = inReader.nextDouble ();
System.out.println (Name + " " + age + " " + " " + height);
}
Here ist a first solution to give you a starting point:
public static void main(String[] args) {
String name ;
int age ;
double height;
Scanner inReader = new Scanner(System.in);
System.out.println("Enter name:");
name = inReader.nextLine();
System.out.println("Enter age:");
age = inReader.nextInt();
System.out.println("Enter height");
height = inReader.nextDouble();
System.out.println ("name: " + name + ", age: " +age + ", height: " + height);
}
The above code will work as long as you enter valid input. Try it. Then input something invalid (for example a char for age)

Enter name and grades from user input to get average grade

I am working on a code where you have a students name and his grades and it prints his name total scores and his average scores. I want to make it more functional in allowing the user to input there name and scores and get all that info back. I may try to further this into a class average where it allows to input multiple individual names, scores, and average, print each one separately then showing the class average. This is a second thought though, as I need to have user input of grades and names first.
This is what I have so far.
I have a separate class to make some things simpler.
public class Student {
private String name;
private int numOfQuizzes;
private int totalScore;
public Student(String name){
this.name = name;
}
public String getName() {
return name;
}
public int getTotalScore() {
return totalScore;
}
public void addQuiz(int score) {
totalScore = totalScore + score;
numOfQuizzes++;
}
public double getAverageScore(){
return totalScore/(double)numOfQuizzes;
}
}
Then i have the main method:
public static void main(String[] args) {
Scanner nameInput = new Scanner(System.in);
System.out.print("What is your name? ");
String name = nameInput.next();
Student student = new Student(name);
student.addQuiz(96);
student.addQuiz(94);
student.addQuiz(93);
student.addQuiz(92);
System.out.println("Students Name: " + student.getName());
System.out.println("Total Quiz Scores: " + student.getTotalScore());
System.out.println("Average Quiz Score: " + student.getAverageScore());
}
This is what it prints out currently:
What is your name? Tom
Students Name: Tom
Total Quiz Scores: 375
Average Quiz Score: 93.75
UPDATE:
This is what i have done so far. i added a loop and trying to use my student class but it doesn't seem to work with the array.
ArrayList<String> scores = new ArrayList<String>();
Scanner nameInput = new Scanner(System.in);
System.out.print("What is your name? ");
String name = nameInput.next();
Scanner scoreInput = new Scanner(System.in);
while (true) {
System.out.print("Please enter your scores (q to quit): ");
String q = scoreInput.nextLine();
scores.add(q);
if (q.equals("q")) {
scores.remove("q");
Student student = new Student(name);
System.out.println("Students Name: " + student.getName());
System.out.println("Total Quiz Scores: " + student.getTotalScore());
System.out.println("Average Quiz Score: " + student.getAverageScore());
break;
}
}
}
}
Since you are only learning the language just yet, I'll give you a few suggestions to send you on your way. You might want to use a while-loop to consistently ask the user for a new grade until they've given you an empty line or something. You can reuse your scanner to read the new grades and they can be converted to integers using Integer.parseInt. Hopefully this'll allow you to write your code further, it's already looking great :).
EDIT
There are several points which can be improved upon in your edited code. The following shows some of them (using import java.io.Console;):
Scanner inp = new Scanner(System.in);
// Request the name
System.out.print("What is your name? ");
String name = inp.nextLine();
// Create the student object
Student student = new Student(name);
// Ask for the grades
System.out.print("Please enter your scores (q to quit): ");
String grade = inp.nextLine();
while (!grade.equals("q")) {
// Convert the grade to an integer and pass it
student.addQuiz(Integer.parseInt(grade));
// Request a new grade
grade = inp.nextLine();
}
// Report the results
System.out.println("Students Name: " + student.getName());
System.out.println("Total Quiz Scores: " + student.getTotalScore());
System.out.println("Average Quiz Score: " + student.getAverageScore());

How to search an array with a string to bring up corresponding number

How do I search an array using a string to bring up the corresponding number? my assignment asked us to let the user type in a name and then have their corresponding pay come up with it, this is the code that I have so far , I am not really sure what to use to do this
import java.io.*;
public class Employees {
public static void main(String agrs[]) throws IOException {
BufferedReader keyboardInput = new BufferedReader(new InputStreamReader(System.in));
double pay;
String name;
String answer;
//Arrays
double[] employeePay = new double[3];
String[] employeeName = new String[3];
pay = employeePay.length;
//for loops
for (int x = 0; x <= employeePay.length - 1; x++) {
System.out.print("Please enter the employee name:");
employeeName[x] = (keyboardInput.readLine());
System.out.print("Please enter the employe pay :");
employeePay[x] = Double.parseDouble(keyboardInput.readLine());
}
//requesting a name
System.out.println("Please enter an employee name to search for:");
answer = (keyboardInput.readLine());
for (int x = 0; x <= employeePay.length - 1; x++) {
if (employeeName[x].equalsIgnoreCase(answer)) {
System.out.print(employeeName + " pay rate is " + pay);
} else {
System.out.print(" The employee name hasnt been entered");
}
}
}
}
Rather than using 2 single dimension arrays consider using a HashMap instead
int employeeCount = 3;
HashMap<String, Double> employeePayMap = new HashMap<String, Double>();
// ... code to capture input
for (int x = 0; x < employeeCount; x++) {
System.out.print("Please enter the employee name:");
String name = (keyboardInput.readLine());
System.out.print("Please enter the employe pay :");
Double pay = Double.parseDouble(keyboardInput.readLine());
employeePayMap.put( name, pay );
}
and then retrieve the pay as
Double payFound = employeePayMap.get(answer);
Check payFound for null - if its null, the name was not matched.
What you have done wrong:
if (employeeName[x].equalsIgnoreCase(answer)) {
System.out.print(employeeName + " pay rate is " + pay);
}
Here you are printing the whole employeeName, not the expected index. It should be employeeName[x]. Also pay is nothing but employeePay.length. I don't think you are trying to print the length of employeePay array here. It should be employeePay[x].
if (employeeName[x].equalsIgnoreCase(answer)) {
System.out.print(employeeName[x] + " pay rate is = " + employeePay[x]);
}
Better approach:
If you have something those are paired (like employee name and payment in your example), better use Map instead of two discrete array. This is better and cleaner way to do this.
You can not only insert data into map easily, but also you can search data from the map without need of iteration that you have done for searching in your code.

Simplest Dialog/Message Box for beginners?

I am unsure of how to do this. I am in a intro to java class and it asks us to use a message box (instead of just system.out.println) I remember we imported something and it was an easy change, but I am unable to find any notes on it.
Furthermore all examples I've found across the web and this site are taking it beyond the scope of this class.
I apologize in advance if this is an incorrect format, this is my first time posting here.
TLDR: Trying to change
System.out.print("Enter renter name: ");
renterName = input.next();
to appear in a message box instead of in the Eclipse Console
I know we imported something (same way we import Scanner) to make this work, but every example I find is essentially saying create your own dialog box methods which is beyond my scope of knowledge, and this class.
COMPLETE CODE IS FOLLOWS:
import java.util.Scanner;
public class RentYourVideo {
public static void main(String[] args) {
int numberOfRentals, finalBill;
VideoRental rental = new VideoRental(); //runs constructor
Scanner input = new Scanner(System.in);
String renterName;
System.out.print("Enter renter name: ");
renterName = input.next();
System.out.print("Enter number of videos to rent: ");
numberOfRentals = input.nextInt();
rental.setRentalFee(); //needs to set rental fee to $5 according to assignment
rental.calculateBill(numberOfRentals); //from prev input
finalBill = rental.getFinalBill();
System.out.println(renterName + " your total bill for " +numberOfRentals+ " videos is $" +finalBill);
input.close();
}
}
//CHANGE ALL PROMPTS & OUTPUT TO DIALOG/MESSAGE BOX!!!!
public class VideoRental {
private int rentalFee, finalBill, numberOfRentals;
public VideoRental() { //constructor method
rentalFee = 0;
finalBill = 0;
}
public void setRentalFee() { //set method
rentalFee = 5;
} //the assignment claims this must set rentalFee = 5
public void calculateBill(int inRented) {
numberOfRentals = inRented;
finalBill = rentalFee * numberOfRentals;
}
public int getFinalBill() {
return finalBill;
}
}
Check this out:
String name = JOptionPane.showInputDialog(null, "Enter name here:");
http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html
import javax.swing.JOptionPane;
[...]
public static void main(String[] args) {
int numberOfRentals, finalBill;
VideoRental rental = new VideoRental(); //runs constructor
String renterName;
renterName = JOptionPane.showInputDialog(null, "Enter renter name: ");
numberOfRentals = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number of videos to rent: "));
rental.setRentalFee(); //needs to set rental fee to $5 according to assignment
rental.calculateBill(numberOfRentals); //from prev input
finalBill = rental.getFinalBill();
JOptionPane.showMessageDialog(null, renterName + " your total bill for " +numberOfRentals+ " videos is $" +finalBill);
}

Java : How to create an array from object then store String and double in that array

I want to create an array from object then store in that array with 2 different type of date
i'm still learning java and this is kinda my task and i searched many times and have find nothing so please i need your help :D
the base class :
package com.matcho.task;
public class Subject {
String name;
Double grade;
public Subject(String myname, double myGrade) {
name = myname;
grade = myGrade;
}
public void printermethod() {
System.out.println("Your Subject is " + name + " and ur grade is "
+ grade);
}
}
and this is the main class :
package com.matcho.task;
import java.util.Scanner;
public class subjectUseing {
public static void main(String[] args) {
String studentName = "";
double studentGrade = 0;
Subject object1 = new Subject(studentName, studentGrade);
Scanner input = new Scanner(System.in);
System.out.print("Please, Enter the Size of the Array : ");
int arraySize = input.nextInt();
Subject[] gradeArray = new Subject[arraySize];
for (int i = 0; i < gradeArray.length; i += 2) {
if ((i + 1) % 2 == 0) {
System.out.println("Please, Enter Subject Number Grade");
studentGrade = input.nextDouble();
studentGrade = object1.grade;
gradeArray[i] = object1.grade;
//Error said (cannot convert from Double to Subject)
//object1.grade = (Double)gradeArray[i];
//gradeArray[i] = object1.grade;
continue;
} else {
System.out.println("Please, Enter Subject Number Name");
studentName = input.next();
studentName = object1.name;
//Error said (cannot convert from String to Subject)
gradeArray[i] = new Subject(object1.name, object1.grade);
// gradeArray[i] = object1.name;
// gradeArray[i] = new String(object1.name); // Failed T_T
}
}// For End
for (int i = 0; i < gradeArray.length; i += 2) {
System.out.println("Your Grade in each Subject is : "
+ gradeArray[i] + " " + gradeArray[i + 1]);
}// For End
}
}
i tried many ways and search many times but found nothing so please i need help because this error
[cannot convert from Double to Subject] blow up my mind :D
You basically need to simplify your loop: on each iteration of the loop, ask for both the subject name and the grade, then create one object to store them both:
for (int i = 0; i < gradeArray.length; i++) {
System.out.println("Please enter the subject name");
String name = input.next();
System.out.println("Please enter the subject grade");
double grade = input.nextDouble();
gradeArray[i] = new Subject(name, grade);
}
Note the declaration of the variables inside the loop - you don't need them outside the loop, so don't declare them there.
Then for display, you'd just use:
for (Subject grade : gradeArray) {
System.out.println(grade);
}
Again, there's no need to skip every other item in the array - each element in the array is a reference to a Subject object, which contains both a name and a grade.
(Or add getName and getGrade methods to Subject so that you can customize the output.)
Note that you may find Scanner a bit of a pain to work with - nextDouble() won't consume a line break, for example, which may mean you get an empty string when reading the next name. You might want to consider just reading a line at a time and using Double.parseDouble to parse a string. (Or use NumberFormat.)
By Definition
An array is a container object that holds a fixed number of values of a single type
You can not create an array then fill it with values of other types.
In your code you've created an array of Subject then all it's elements should be of type Subject , The members of Subject class doesn't matter at this point the array should handle Elements of type Subject.
In your logic "Business requirements " you're asked to create an array which holds the values of Student subject plus their Grades , then you say OK Easy task and you create the array and then you try to store grades and names of an object of Subject Class in the array Saying that
" Object is a reference type , and so as it's members " but NO!! it's not;
Your array should contains only Subject Elements
Take a look in the correct solution:
Scanner in = new Scanner(System.in);
System.out.println("Enter array size");
int size = in.nextInt();
Subject[] subjects = new Subject[size];
String name;
Double grade;
Subject object;
for(int i =0; i<size; i++)
{
System.out.println("Enter Subject name: ");
name=in.next();
System.out.println("Enter Subject Grade: ");
grade = in.nextDouble();
object = new Subject(name,grade);
subjects[i] = object;
}
for(int i=0; i<size; i++)
System.out.println("Subject name is "+subjects[i].name + " Grade is "+subjects[i].grade);
}
You created an array of Subject objects, but you are storing Double.
studentGrade = object1.grade;
gradeArray[i] = object1.grade;
You should store it like:
object1.grade = studentGrade;
gradeArray[i].grade = object1.grade;
But as already mentioned, you don't need so many local variables. You could dou it lik:
gradeArray[i].grade = input.nextDouble();

Categories