I am trying to create a class that receives data about a person's name, exam subject, and exam score. I have these classes so far:
APExam:
public class APExam {
//instance variables
private String mySubject;
private int myScore;
//constructors
public APExam(String subject, int score) {
mySubject = subject;
myScore = score;
}
public APExam() {
mySubject = "";
myScore = 1;
}
//getters and setters
public void setSubject(String s) {
mySubject = s;
}
public String getSubject() {
return mySubject;
}
public void setScore(int score) {
myScore = score;
}
public int getScore() {
return myScore;
}
//compareTo
public String compareTo(int s) {
if(myScore == s)
return "Scores are equal.";
else if(myScore > s)
return "The first score is greater than the second score.";
else
return "The second score is greater than the first score.";
}
//equals
public boolean equals(String str) {
return mySubject.equals(str);
}
//toString
public String toString() {
return "Subject: " + mySubject + "\nScore: " + myScore;
}
}
APStudent:
public class APStudent {
//instance variables
private String myFirstName;
private String myLastName;
private ArrayList<APExam> myExams = new ArrayList<APExam>();
//constructors
public APStudent(String fname, String lname) {
myFirstName = fname;
myLastName = lname;
}
public APStudent() {
myFirstName = "";
myLastName = "";
}
//getters and setters
public void setFirstName(String fname) {
myFirstName = fname;
}
public String getFirstName() {
return myFirstName;
}
public void setLastName(String lname) {
myLastName = lname;
}
public String getLastName() {
return myLastName;
}
public ArrayList<APExam> getExams() {
return myExams;
}
//addExam
public void addExam(APExam ex) {
myExams.add(ex);
}
//computeExamAverage
public double computeExamAverage(List<APExam> exams) {
int sum = 0;
for(int i = 0; i < exams.size(); i++) {
sum += exams.get(i).getScore();
}
return (double) sum / exams.size();
}
//findHighestExamScore
public int findHighestExamScore(List<APExam> exams) {
int max = exams.get(0).getScore();
for(APExam ex : exams) {
if(ex.getScore() > max) {
max = ex.getScore();
}
}
return max;
}
//numberOfFives
public int numberOfFives(List<APExam> exams) {
int fiveCount = 0;
for(APExam ex : exams) {
if(ex.getScore() == 5) {
fiveCount++;
}
}
return fiveCount;
}
}
ArrayListTest:
public class ArrayListTest {
public static void main(String[] args) {
//instance variables
final String QUIT = "end";
Scanner sc = new Scanner(System.in);
ArrayList<APExam> myExams = new ArrayList<APExam>();
APStudent student = new APStudent();
String fname, lname, sub, input = "";
int score;
//prompt for info
System.out.print("Enter first name: ");
fname = sc.nextLine();
student.setFirstName(fname);
System.out.print("\nEnter last name: ");
lname = sc.nextLine();
student.setLastName(lname);
while(!input.equals(QUIT)) {
APExam ap = new APExam();
System.out.print("\nEnter exam subject or 'end' to quit: ");
input = sc.nextLine();
sub = input;
ap.setSubject(sub);
System.out.print("\nEnter exam score: ");
score = sc.nextInt();
ap.setScore(score);
student.addExam(ap);
sc.nextLine();
}
//display information
System.out.println(student.getExams());
System.out.println("Name: " + student.getFirstName() + " " + student.getLastName());
System.out.println("Exam average score: " + student.computeExamAverage(myExams));
System.out.println("Highest score: " + student.findHighestExamScore(myExams));
System.out.println("Number of fives: " + student.numberOfFives(myExams));
System.out.println();
for(int i = 0; i < myExams.size(); i++) {
System.out.println(myExams.get(i));
}
//prompt for search
System.out.println("1 sequential search"
+ "\n2 binary search"
+ "\n3 exit");
input = sc.nextLine();
while(!((input.equals("1") || input.equals("2") || input.equals("3")))) {
switch(input) {
case "1":
sequentialSearch(myExams, 3);
break;
case "2":
binarySearch(myExams, 2);
break;
case "3":
break;
}
}
}
}
For some reason in the ArrayListTest class it doesn't create an APExam object with the inputted scores and subjects. Is there something wrong with the while loop? Or is something else wrong?
Your problem is that you are for some reason passing variable List<APExam> exams into your functions. When you are doing that you are passing a empty ArrayList<APExam> and that's why it throws a IndexOutOfBoundsException.
You shouldn't pass anything and just use the APStudent's myExams list.
public double computeExamAverage() {
double sum = 0;
for (APExam myExam : myExams) {
sum += myExam.getScore();
}
return sum / myExams.size();
}
public int findHighestExamScore() {
int max = 0;
for(APExam exam : myExams) {
if(exam.getScore() > max) max = exam.getScore();
}
return max;
}
public int numberOfFives() {
return (int) myExams.stream().filter(apExam -> apExam.getScore() == 5).count();
}
EDIT: I would like to comment on your main method too. You should use the parametrized constructors instead of default one and setters. And you should check on the input being "end" before you ask for grade.
public static void main(String[] args) {
final String QUIT = "end"; // not really necessary, but ok
Scanner sc = new Scanner(System.in);
String firstName, lastName, subject;
int score;
//prompt for info
System.out.print("Enter first name: ");
firstName = sc.nextLine();
System.out.print("\nEnter last name: ");
lastName = sc.nextLine();
APStudent student = new APStudent(firstName, lastName); // use of parametrized constructor
while(true) {
System.out.print("\nEnter exam subject or 'end' to quit: ");
subject = sc.nextLine();
if (subject.equals(QUIT)) break; // check if user wants to end it
System.out.print("\nEnter exam score: ");
score = sc.nextInt();
student.addExam(new APExam(subject, score)); // use of parametrized constructor
sc.nextLine();
}
sc.close(); // never forget to close Scanner
//display information etc.
}
Related
I am a student and looking for help with an assignment. Here is the task: Create a CollegeCourse class. The class contains fields for the course ID (for example, “CIS 210”), credit hours (for example, 3), and a letter grade (for example, ‘A’).
Include get() and set()methods for each field. Create a Student class containing an ID number and an array of five CollegeCourse objects. Create a get() and set() method for the Student ID number. Also create a get() method that returns one of the Student’s CollegeCourses; the method takes an integer argument and returns the CollegeCourse in that position (0 through 4). Next, create a set() method that sets the value of one of the Student’s CollegeCourses; the method takes two arguments—a CollegeCourse and an integer representing the CollegeCourse’s position (0 through 4).
I am getting runtime errors on the second for loop where I am trying to get the data into the course array. It is asking for both the CourseID and Hours in the same line and regardless of what I respond with it I am getting an error, it almost seems like it is trying to get all the arrays variables at the same time. Here is my code which includes three classes. Any help to send me in the right direction is appreciated as I have spent a ton of time already researching to resolve.
public class CollegeCourse {
private String courseId;
private int creditHours;
private char grade;
public CollegeCourse(String id, int hours, char grade)
{
courseId=id;
creditHours = hours;
this.grade = grade;
}
public void setCourseId(String id)
{
courseId = id;//Assign course id to local variable
}
public String getCourseId()
{
return courseId;//Provide access to course id
}
public void setHours(int hours)
{
creditHours = hours;//Assign course id to local variable
}
public int getHours()
{
return creditHours;//Provide access to course id
}
public void setGrade(char grade)
{
this.grade = grade;//Assign course id to local variable
}
public char getGrade()
{
return grade;//Provide access to course id
}
}
Student Class
public class Student {
final int NUM_COURSES = 5;
private int studentId;
private CollegeCourse courseAdd;//Declares a course object
private CollegeCourse[] courses = new CollegeCourse[NUM_COURSES];
//constructor using user input
public Student(int studentId)
{
this.studentId=studentId;
}
public void setStudentId(int id)
{
studentId = id;//Assign course id to local variable
}
public int getStudentId()
{
return studentId;//Provide access to course id
}
public void setCourse(int index, CollegeCourse course)
{
courses[index] = course;
}
public CollegeCourse getCourse(int index)
{
return courses[index];
//do I need code to return the courseId hours, grade
}
}
InputGrades Class
import java.util.Scanner;
public class InputGrades {
public static void main(String[] args) {
final int NUM_STUDENTS = 2;
final int NUM_COURSES = 3;
Student[] students = new Student[NUM_STUDENTS];
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
//String gradeInput;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + (s+1) + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
csIndex=c;
System.out.print("Enter course ID #" + (c+1) + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
System.out.println();
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}
After input.nextInt() you need to add one more input.nextLine(); and than you can read grade.
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
Why it is needed? See this question: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
You should add a very simple length validation when you input the grade:
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
so the full main class code:
import java.util.Scanner;
/**
* Created by dkis on 2016.10.22..
*/
public class App {
public static void main(String[] args) {
final int NUM_STUDENTS = 10;
final int NUM_COURSES = 5;
Student[] students = new Student[NUM_STUDENTS];
//String name;
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + s+1 + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
//CollegeCourse course = students[s].getCourse(c);
csIndex=c;
System.out.print("Enter course ID#" + c+1 + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}
So, basically I have an assignment that requires for me to Write a java program to help maintain a class roll. The program must contain four classes: Student, Exams, ClassRoll and Assignment4(Main).
I have developed all the classes but the ClassRoll constructor it s not performing correctly. When I run the program I am prompted with the file name option, once i enter the file name I see null then the options to modify and / or display the list, but when I enter a command, it does not work, it gives me an error.
The Output should be
Expected input/output:
Assuming that the file data.txt contains:
COP2210
John Doe 50 60 70
Marco Boyle 50 60 73
Eric Munzon 45 100 90
Marry Able 95 100 100
Jack Smith 100 100 100
Elizabeth Gomez 100 100 100
The following is a sample input output run:
What is the name of input file: data.txt
Enter one of the following commands
a or add to add a student in the class roll
sa or average to sort the students based on their average
sn or names to sort the students based on their last names
r or remove to remove a student from the class roll
s or save to save the list of students back to the datafile
Here are my classes;
public class Student {
private String fName = "";
private String lName = "";
private Exam scores;
public Student(String f, String l){
fName=f;
lName=l;
scores = new Exam();
}
public void setScore1(int score) {
scores.setScore1(score);
}
public void setScore2(int score) {
scores.setScore2(score);
}
public void setScore3(int score) {
scores.setScore3(score);
}
public String toString() {
return lName + "\t" + fName + "\t" +
scores.toString();
}
public double getAverage() {
return (scores.getScore1() + scores.getScore2() +
scores.getScore3())/3.0;
}
public boolean equals(String f, String l) {
return f.equals(fName) && l.equals(lName);
}
public int compareTo(Student s){
if (lName.compareTo(s.lName) > 0)
return 1;
else if (lName.compareTo(s.lName) < 0)
return -1;
else if (fName.compareTo(s.fName) > 0)
return 1;
else if (fName.compareTo(s.fName) < 0)
return -1;
else return 0;
}}
public class Exam {
private int score1;
private int score2;
private int score3;
public Exam(){
score1=0;
score2=0;
score3=0;
}
public void setScore1(int score) {
score1=score;
}
public int getScore1() {
return score1;
}
public void setScore2(int score) {
score2=score;
}
public int getScore2() {
return score2;
}
public void setScore3(int score) {
score3=score;
}
public int getScore3() {
return score3;
}
public String toString() {
return Integer.toString(score1) + "\t"
+Integer.toString(score2)
+ "\t" + Integer.toString(score3) + "\t";
}}
public class ClassRoll {
ArrayList students = new ArrayList();
String title;
String fileName;
public ClassRoll(String f) throws IOException {
Scanner fileScan, lineScan;
String line;
fileName = f;
fileScan = new Scanner(new File(f));
title = fileScan.nextLine();
System.out.println("Title =" + title);
while (fileScan.hasNext()) {
line = fileScan.nextLine();
lineScan = new Scanner(line);
lineScan.useDelimiter("\t");
String lastName = lineScan.next();
String firstName = lineScan.next();
Student s = new Student(firstName, lastName);
s.setScore1(lineScan.nextInt());
s.setScore2(lineScan.nextInt());
s.setScore3(lineScan.nextInt());
students.add(s);
//display(students);
ClassRoll c = new ClassRoll();
c.display();
}
}
void display() {
DecimalFormat fmt = new DecimalFormat("0.00");
System.out.println("\t\t\t" + title);
double classAverage = 0.0;
for (int i = 0; i < students.size(); i++) {
Student s = (Student) students.get(i);
System.out.print(s.toString());
System.out.println("\t" + fmt.format(s.getAverage()));
classAverage = classAverage + s.getAverage();
}
System.out.println("\t\t\t" + fmt.format(classAverage /
students.size()));
}
public void insert() {
Scanner input = new Scanner(System.in);
System.out.print("First Name -> ");
String firstName = input.next();
System.out.print("Last Name -> ");
String lastName = input.next();
System.out.print("Score 1 -> ");
int score1 = input.nextInt();
System.out.print("Score 2 -> ");
int score2 = input.nextInt();
System.out.print("Score 3 -> ");
int score3 = input.nextInt();
Student s = new Student(firstName, lastName);
s.setScore1(score1);
s.setScore2(score2);
s.setScore3(score3);
students.add(s);
}
private int search(String f, String l) {
int i = 0;
while (i < students.size()) {
Student s = (Student) students.get(i);
if (s.equals(f, l)) {
return i;
} else {
i++;
}
}
return -1;
}
public Student find() {
Scanner input = new Scanner(System.in);
System.out.print("First Name -> ");
String firstName = input.next();
System.out.print("Last Name -> ");
String lastName = input.next();
int i = search(firstName, lastName);
if (i >= 0) {
return (Student) students.get(i);
} else {
return null;
}}
public void delete() {
Scanner input = new Scanner(System.in);
System.out.print("First Name -> ");
String firstName = input.next();
System.out.print("Last Name -> ");
String lastName = input.next();
int i = search(firstName, lastName);
if (i >= 0) {
students.remove(i);
} else {
System.out.println("Student not found");
}
}
public void sortLastNames() {
for (int i = 0; i < students.size() - 1; i++) {
for (int j = i + 1; j < students.size(); j++) {
Student s1 = (Student) students.get(i);
Student s2 = (Student) students.get(j);
if (s1.compareTo(s2) > 0) {
students.set(i, s2);
students.set(j, s1);
}
}
}}
public void sortAverage() {
for (int i = 0; i < students.size() - 1; i++) {
for (int j = i + 1; j < students.size(); j++) {
Student s1 = (Student) students.get(i);
Student s2 = (Student) students.get(j);
if (s1.getAverage() < s2.getAverage()) {
students.set(i, s2);
students.set(j, s1);
}
}}}
public void save() throws IOException {
PrintWriter out = new PrintWriter(fileName);
out.println(title);
for (int i = 0; i < students.size(); i++) {
Student s = (Student) students.get(i);
out.println(s.toString());
}
out.close();
}}
public class Assignment4bis {
public static void main(String[] args) throws IOException {
Scanner input=new Scanner(System.in);
System.out.print("Enter the name of the input file ->");
String fileName=input.next();
ClassRoll c = new ClassRoll();
c.display();
prompt();
System.out.print("Enter a command --> ");
String ans=input.next();
while (!(ans.equalsIgnoreCase("q") || ans.equalsIgnoreCase("quit")))
{
if(!(ans.equalsIgnoreCase("i") ||ans.equalsIgnoreCase("insert") ||
ans.equalsIgnoreCase("a") || ans.equalsIgnoreCase("average") ||
ans.equalsIgnoreCase("n") || ans.equalsIgnoreCase("names") ||
ans.equalsIgnoreCase("r") || ans.equalsIgnoreCase("remove") ||
ans.equalsIgnoreCase("f") || ans.equalsIgnoreCase("find") ||
ans.equalsIgnoreCase("d") || ans.equalsIgnoreCase("display")))
System.out.println("Bad Command");
else
switch (ans.charAt(0))
{
case 'i': c.insert();
break;
case 'a': c.sortAverage();
c.display();
break;
case 'n': c.sortLastNames();
c.display();
break;
case 'r': c.delete();
c.display();
break;
case 'f': Student s=c.find();
if (s == null)
System.out.println("Student not found");
else System.out.println(s.toString());
break;
case 'd': c.display();
break;
}
prompt();
System.out.print("Enter a command --> ");
ans=input.next();
}
c.save();
System.out.println("Thank you for using this program");
}
public static void prompt(){
System.out.println("Enter one of the following commands");
System.out.println("i or insert to insert a student in the class
roll");
System.out.println("a or average to sort the students based on
their average");
System.out.println("n or names to sort the students based on their
last names");
System.out.println("r or remove to remove a student from the class
roll");
System.out.println("f or find to find a student in the class
roll");
System.out.println("d or display to display the class roll");
System.out.println("q or quit to exit the program");
}}
Errors that I m still getting...
run:
Enter the name of the input file ->data.txt
Title =COP2210
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at assignment4bis.ClassRoll.<init>(ClassRoll.java:40)
at assignment4bis.Assignment4bis.main(Assignment4bis.java:28)
Java Result: 1
Your ClassRoll "constructor" is a "pseudo-constructor":
public class ClassRoll {
ArrayList students = new ArrayList();
String title;
String fileName;
public void ClassRoll(String f) throws IOException {
Constructors have no return type, so get rid of the void:
public class ClassRoll {
ArrayList students = new ArrayList();
String title;
String fileName;
public ClassRoll(String f) throws IOException {
As a bit of side recommendations:
You look to be mixing user interface with one of your "model" or logical classes, ClassRoll, something you probably shouldn't do. I'd keep all user interface code, including use of a Scanner and File I/O separate from ClassRoll, which likely should just have code to create the collection, to allow other classes to add or remove from the collection, and to allow other classes to query the collection.
Take care to learn and follow Java code formatting rules. You've got some deviations from the standard, including have your class declaration lines indented the same as the method body and variable declaration lines, bunching up of end braces,... This makes your code hard for other Java coders to read and understand.
Q. Create a class named Participant with fields for a name, age, and street address. Include a constructor that assigns parameter values to each field and a toString() method that returns a String containing all the values.
Also include an equals() method that determines two Participants are equal if they have the same values in all three fields.
Create an application with two arrays of at least 5 Participants each--one holds the Participants in the mini-marathon and the other holds Participants in the diving competition. Prompt the user for Participants who are in both events save the files as Participant.java and TwoEventParticipants.java.*/
Here is my code so far. How do I display the value of Participants who are in both events ?
import javax.swing.JOptionPane;
import java.util.*;
public class TwoEventParticipants {
private static Participant mini[] = new Participant[2];
private static Participant diving[] = new Participant[2];
public static void main(String[] args) {
String name="";;
String add="";
int age=0;
Participant p=new Participant(name, age, add);
Participant p1=new Participant(name, age, add);
setParticipant();
setParticipant1();
displayDetail();
displayDetail1();
//Arrays.sort(p1);
if (p.equals(p1)){
System.out.println(p);
}else{
System.out.println(p1);
}
}
public static void setParticipant(){
for (int x = 0; x < mini.length; x++) {
System.out.println("Enter loan details for customer " + (x + 1) + "...");
//Character loanType=getLoanType();
//String loanType=getLoanType();
String name=getName();
String add=getAdd();
int age=getAge();
System.out.println();
mini[x] = new Participant(name, age, add); //<--- Create the object with the data you collected and put it into your array.
}
}
public static void setParticipant1(){
for (int y = 0; y < diving.length; y++) {
System.out.println("Enter loan details for customer " + (y + 1) + "...");
String name=getName();
String add=getAdd();
int age=getAge();
System.out.println();
diving[y] = new Participant(name, age, add);
}
}
// Participant p=new Participant(name,age,add);
//displayDetails();
// System.out.println( p.toString());
public static void displayDetail() {
// for (int y = 0; y < diving.length; y++) {
System.out.println("Name \tAge \tAddress");
//Participant p=new Participant(name,age,add);
for (int x = 0; x < mini.length; x++) {
System.out.println(mini[x].toString());
// System.out.println(diving[y].toString());
}
}
public static void displayDetail1() {
System.out.println("Name \tAge \tAddress");
for (int y = 0; y < diving.length; y++) {
System.out.println(diving[y].toString());
}
}
public static String getName() {
Scanner sc = new Scanner(System.in);
String name;
System.out.print(" Participant name: ");
return name = sc.next();
}
// System.out.print(" Participant name: ");
// name = sc.next();
public static int getAge() {
int age;
System.out.print(" Enter age ");
Scanner sc=new Scanner(System.in);;
return age= sc.nextInt();
}
public static String getAdd() {
String add;
Scanner sc=new Scanner(System.in);;
System.out.print("Enter Address: ");
return add=sc.next();
}
}
Participant with fields for a name, age, and street address
//
public class Participant {
private String name;
private int age;
private String address;
public Participant(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
#Override
public String toString() {
return name + " " + age + " " + address ;
}
// include an equals() method that determines two Participants are equal
public boolean equals(Participant[] name,Participant[] age,Participant[] add) {
if (this.name.equals(name) && this.address.equals(address)&& age == age){
return true;
}
else{
return false;
}
}
}
This will work for you:
for(Participant p : mini){
if(diving.contain(p)){
System.out.pringtln(p.toString()) ;
}
}
Im trying to get different variables from loan but none of them ever get to loan.java. My inheritance goes from Loan.Java > BusinessLoan.java > CreateLoan.java. I can get a variable from CreateLoan to display in business but when I set it in business I can't grab it. And I know some of this stuff is stupid but this is my final so some of the stuff was required. Heres my code
Loan.java
package Construction;
public class Loan implements LoanConstant{
public static int loanNumber;
public static String lastName;
public static int loanAmount;
public static int interestRate;
public static int term;
public int primeRate;
public int getLoanNumber() { return loanNumber; }
public void setLoanNumber(int n) { n = loanNumber; }
public String getLastName() { return lastName; }
public void setLastName(String s) { s = lastName; }
public int getLoanAmount() { return loanAmount; }
public void setLoanAmount(int n) {
n = loanAmount;
if (loanAmount > MAX_LOAN_AMOUNT)
loanAmount = MAX_LOAN_AMOUNT;
}
public int getTerm() { return term; }
public void setTerm(int n) {
n = term;
if (term == 1) {
term = SHORT_TERM;
} else if (term == 3) {
term = MEDIUM_TERM;
} else if(term == 5) {
term = LONG_TERM;
} else
term = SHORT_TERM;
}
public int getInterestRate() { return interestRate; }
public void setInterestRate(int i) { i = interestRate; }
public static void displayAll() {
System.out.println("The Company's Name is " + COMPANY_NAME);
System.out.println("The loan number is " + loanNumber);
System.out.println("The last name on the loan is " + lastName);
System.out.println("The loan amount is " + loanAmount);
System.out.println("The interest rate on the loan is " + interestRate);
System.out.println("The term on the account is " + term);
}
}
PersonalLoan.java
package Construction;
public class PersonalLoan extends Loan{
public PersonalLoan(int ln, String last, int la, int term) {
setLoanNumber(ln);
setLastName(last);
setLoanAmount(la);
setTerm(term);
interestRate = (int)((primeRate * 0.02) + primeRate);
setInterestRate(interestRate);
}
}
BusinessLoan.java
package Construction;
public class BusinessLoan extends Loan{
public BusinessLoan(int ln, String last, int la, int term) {
setLoanNumber(ln);
setLastName(last);
setLoanAmount(la);
setTerm(term);
interestRate = (int)((primeRate * 0.01) + primeRate);
setInterestRate(interestRate);
}
}
CreateLoan.java
package Construction;
import java.util.Scanner;
public class CreateLoan {
public static void main(String[] args) {
int x = 0;
int primeRate;
String type;
Scanner input = new Scanner(System.in);
Loan[] loans = new Loan[5];
System.out.println("Please enter the prime interest rate");
primeRate = input.nextInt();
primeRate = primeRate/100;
input.nextLine();
for(x = 0; x < 6; ++x) {
System.out.println("Please enter a loan type. Choose either Business or Personal. If you don't type it like that you'll get an error.");
type = input.nextLine();
if (type.equalsIgnoreCase("Business")) {
System.out.println("What is the account number on the loan?");
int ln = input.nextInt();
System.out.println("What is the last name on the account?");
String last = input.nextLine();
input.nextLine();
System.out.println("What is the loan amount? If you put more then 100k it'll only accept up to 100k");
int la = input.nextInt();
System.out.println("What is the term on the account? If you enter something other then 1, 3, or 5 it will default to a short term.");
int term = input.nextInt();
loans[x] = new BusinessLoan(ln, last, la, term);
System.out.println("The Company's Name is " + Loan.COMPANY_NAME);
System.out.println("The loan number is " + loans[x].getLoanNumber());
System.out.println("The last name on the loan is " + loans[x].getLastName());
System.out.println("The loan amount is " + loans[x].getLoanAmount());
System.out.println("The interest rate on the loan is " + loans[x].getInterestRate());
System.out.println("The term on the account is " + loans[x].getTerm());
}
else if (type.equalsIgnoreCase("Personal")) {
System.out.println("What is the account number on the loan?");
int ln = input.nextInt();
System.out.println("What is the last name on the account?");
String last = input.nextLine();
input.nextLine();
System.out.println("What is the loan amount? If you put more then 100k it'll only accept up to 100k");
int la = input.nextInt();
System.out.println("What is the term on the account? If you enter something other then 1, 3, or 5 it will default to a short term.");
int term = input.nextInt();
loans[x] = new PersonalLoan(ln, last, la, term);
System.out.println("The Company's Name is " + Loan.COMPANY_NAME);
System.out.println("The loan number is " + loans[x].getLoanNumber());
System.out.println("The last name on the loan is " + loans[x].getLastName());
System.out.println("The loan amount is " + loans[x].getLoanAmount());
System.out.println("The interest rate on the loan is " + loans[x].getInterestRate());
System.out.println("The term on the account is " + loans[x].getTerm());
} else {
System.out.println("You've entered an invalid type. Please restart and try again.");
System.exit(0);
}
}
}
}
LoanConstants.java
package Construction;
public interface LoanConstant {
public final static int SHORT_TERM = 1;
public final static int MEDIUM_TERM = 3;
public final static int LONG_TERM = 5;
public final static String COMPANY_NAME = "Sanchez Construction";
public final static int MAX_LOAN_AMOUNT = 100000;
}
In addition to the Loan fields being static (remove the static). You should also update your setters.
public void setLoanNumber(int n) { n = loanNumber; }
public void setLastName(String s) { s = lastName; }
You are assigning the value to the passed in variable (not the field). Should be
public void setLoanNumber(int n) { loanNumber = n; }
public void setLastName(String s) { lastName = s; }
and
public void setTerm(int n) {
// n = term;
if (n == 1) {
term = SHORT_TERM;
} else if (n == 3) {
term = MEDIUM_TERM;
} else if (n == 5) {
term = LONG_TERM;
} else
term = SHORT_TERM;
}
public void setInterestRate(int i) { interestRate = i; }
QUESTION: I'm trying to find the win percentage (the formula for win percentage is wins/(wins + loses)). How do I take the values from wins and loses the user enters and add them to my Sysout function. Every time I run the program it displays:
East W L PCT
Braves 45 66 0.000000
Cubs 87 77 0.000000
So what I'm trying to do is get the actual values instead of it saying "0.0000000"
public class Team {
// Data fields...
private int wins;
private int loses;
private String teamName;
private String city;
private String division;
private double winPercentage;
// Getters and setters...
public int getWins() {
return wins;
}
public void setWins(int wins) {
this.wins = wins;
}
public int getLoses() {
return loses;
}
public void setLoses(int loses) {
this.loses = loses;
}
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
public double getWinPercentage() {
return wins/(wins + loses);
}
public void setWinPercentage(double winPercentage) {
this.winPercentage = winPercentage;
}
}
public class PlayoffSelectorClass extends Team{
public static void main(String[] args) {
List<Team> teams = new ArrayList<Team>();
for (int i = 0; i < 6; i++) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter team name: ");
String name = input.nextLine();
System.out.println("\nPlease enter the city " + name + " played in: ");
String city = input.nextLine();
System.out.println("\nPlease enter the division " + name + " play in: ");
String division = input.nextLine();
System.out.println("\nPlease enter the number of wins " + name + " has: ");
Integer wins = input.nextInt();
System.out.println("\nPlease enter the number of losses " + name + " has: ");
Integer loses = input.nextInt();
if (i < 5) {
System.out.println("\nEnter your next team...\n");
}
Team team = new Team();
team.setTeamName(name);
team.setCity(city);
team.setDivision(division);
team.setWins(wins);
team.setLoses(loses);
team.setWinPercentage(wins / (wins + loses));
teams.add(team);
}
System.out.println("East W L PCT\n");
for (Team team : teams) {
System.out.printf("%s\t%s\t%s\t%f\n",team.getTeamName() + " ", team.getWins() + " " , team.getLoses(), team.getWinPercentage());
}
}
}
The problem is here :
public double getWinPercentage() {
return wins/(wins + loses);
}
You are doing integer division, i.e only keep the int part of the result, and implicitly cast it to a double. So for example if:
wins = 10;
loses = 20;
then winPercentage == 10/30 == 0.33.. and you only keep the 0 and the cast it to double. Hence the 0.0000... etc What you can do instead is:
public double getWinPercentage() {
return wins/(double) (wins + loses);
}