Its been a ridiculous task especially to build the total of each vertical column & to show it on screen. Though, calculating the total of horizontal row never seemed to be a challenge.
The problem I'm having is three-fold.
How do I calculate the total of each vertical column ?
The index (id) is getting printed in descending order. How do I make it print in ascending order ?
Further, in the percentage column the value after the decimal point is being discarded. How do I get that displayed? For eg.. if
answer is supposed to be 78.25% it exhibits as 78.0%
P.S : (2 places after the decimal point is what I'm aiming at.)
POJO class -- StudentsProg.java
package com.students.marks;
import java.util.Arrays;
public class StudentsProg {
private int id = 0;
private String name;
private int english;
private int german;
private int french;
private int arabic;
private double percentage;
private int total_marks;
private int rowHighest;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getEnglish() {
return english;
}
public void setEnglish(int english) {
this.english = english;
}
public int getGerman() {
return german;
}
public void setGerman(int german) {
this.german = german;
}
public int getFrench() {
return french;
}
public void setFrench(int french) {
this.french = french;
}
public int getArabic() {
return arabic;
}
public void setArabic(int arabic) {
this.arabic = arabic;
}
public double getPercentage() {
return percentage;
}
public void setPercentage(double percentage) {
this.percentage = percentage;
}
public int getTotal_marks() {
return total_marks;
}
public void setTotal_marks(int total_marks) {
this.total_marks = total_marks;
}
public int getRowHighest() {
return rowHighest;
}
public void setRowHighest(int rowHighest) {
this.rowHighest = rowHighest;
}
public String toString() {
id = id+1;
return (id + "\t" +name+ "\t\t" +english+ "\t" + " " +german+ "\t" + " "+ french+ "\t" + " " +arabic+ "\t" +" " +total_marks+ "\t\t" + " " +percentage+ "\t\t" +rowHighest);
}
}
StudentsProgMain.java
import java.util.Scanner;
public class StudentsProgMain {
#SuppressWarnings("resource")
public static void main(String[] args) {
int count = 0;
StudentsProg[] stud = new StudentsProg[15];
int choice=0;
int max = 0;
Scanner scanner = new Scanner(System.in);
do{
System.out.println("1: Add new Student");
System.out.println("2: List Student");
System.out.println("3: List Student By Name.");
System.out.println("4: Delete Student");
System.out.println("5: Exit");
System.out.println("Please enter your choice \n\n");
choice=scanner.nextInt();
switch(choice){
case 1:
stud[count] = new StudentsProg();
System.out.println("Enter student name");
stud[count].setName(scanner.next());
System.out.println("Enter marks in English");
stud[count].setEnglish(scanner.nextInt());
System.out.println("Enter marks in German");
stud[count].setGerman(scanner.nextInt());
System.out.println("Enter marks in French");
stud[count].setFrench(scanner.nextInt());
System.out.println("Enter marks in Arabic");
stud[count].setArabic(scanner.nextInt());
count++;
break;
case 2:
System.out.println("ID\t" + "Name \t\t\t" + "English\t" + " " + "German\t"+ " " + "French\t" + " " + "Arabic\t"
+" "+ "Total Marks\t" + " " + "Percentage\t" + "Highest Marks(Row)\n" +
"------------------------------------------------------------------------"
+ "------------------------------------------- \n ");
for(int i=0; i<count; i++){
if(stud[i]!=null){
int total_marks = stud[i].getEnglish()+stud[i].getGerman()+ stud[i].getFrench()+stud[i].getArabic();
stud[i].setTotal_marks(total_marks);
double calc_per = ((total_marks*100)/400);
stud[i].setPercentage(calc_per);
int arrayListMarks [] = {stud[i].getEnglish(), stud[i].getFrench(), stud[i].getGerman(), stud[i].getArabic()};
max = arrayListMarks[0];
for (int j = 1; j < arrayListMarks.length; j++) {
if(arrayListMarks[j] > max)
max = arrayListMarks[j]; }
stud[i].setRowHighest(max);
System.out.println(stud[i].toString());
System.out.println("\n");}
}
System.out.println("--------------------------------------------------------------"
+ "----------------------------------------------------- \n");
System.out.println("\tTotal :" +"\n");
break;
case 3 :
System.out.println("Please enter your name");
String name = scanner.next();
System.out.println("\n" + "ID\t" + "Name \t\t\t" + "English\t" + " " + "German\t"+ " " + "French\t" + " " + "Arabic\t"
+" "+ "Total Marks\t" + " " + "Percentage\t" + "Highest Marks(Row)\n" +
"------------------------------------------------------------------------"
+ "------------------------------------------- \n ");
for(int i =0 ; i<count; i++){
if(stud[i]!=null && stud[i].getName().equals(name))
System.out.println(stud[i].toString()); }
System.out.println("--------------------------------------------------------------"
+ "----------------------------------------------------- \n");
break;
case 4 :
System.out.println("Please enter your name");
String naam = scanner.next();
for (int i = 0; i<count; i++) {
if(stud[i]!=null && stud[i].getName()==naam)
stud[i]=null;
}
break;
case 5:
System.exit(0);
System.out.println("You have exited successfully");
default :
System.out.println("Invalid choice");
}
}while(true);
}
}
The problem with the percentage calculation is that the line of code double calc_per = ((total_marks*100)/400); will do integer arithmetic and truncate each intermediate result as an integer. To fix this you need to include a floating point number somewhere in the calculation either by converting total_marks to double like so:
double calc_per = ((Integer.valueOf(total_marks).doubleValue()*100)/400);
Or using a float constant like so:
double calc_per = ((total_marks*100.0)/400);
Vertical totals should just be a matter of adding the row value to a variable inside your print loop.
I'm not really sure about your index order problem but the code in toString() that reads id = id+1; looks wrong. This will increment the Id each time you call toString(). Instead of that, your creation code should set the value of id just after creating the object, something like:
stud[count] = new StudentsProg();
// add the following line of code.
stud[count].setId(count);
System.out.println("Enter student name");
stud[count].setName(scanner.next());
Related
import java.util.Scanner;
public class MainBinaryTreeArray
{
public static void main(String[] args)
{
int choice;
Scanner scan= new Scanner(System.in);
BinaryTreeArray data = new BinaryTreeArray();
Listing l1 = new Listing("Carol", 4354, 3.2);
Listing l2 = new Listing("Timothy", 2353, 4.0);
Listing l3 = new Listing("Dean", 4544, 2.4);
Listing l4 = new Listing("Sue", 3445, 3.0);
data.insert(l1);
data.insert(l2);
data.insert(l3);
data.insert(l4);
do
{
// Choose which operation by entering a number
System.out.println("*****************(Menu Operations:)******************");
System.out.println(" (Press 1). Insert.");
System.out.println(" (Press 2). Fetch.");
System.out.println(" (Press 5). Output all student records.");
System.out.println(" (Press 6). Exit the program.");
System.out.println("Enter your choice: ");
choice = scan.nextInt();
switch(choice)
{
case 1:
System.out.println("Are students inserted: " + data.insert(l1));
break;
case 2:
System.out.println("The student's info that's fetched: ");
System.out.print(data.fetch("Timothy"));
break;
case 5:
System.out.print("Output all the student's records: ");
data.showAll();
}
}while(choice!=6);
}
}
public class BinaryTreeArray
{
private Listing[] data;
private int size;
public BinaryTreeArray()
{
size = 100;
data = new Listing[size];
}
public void showAll()
{
for(int i=0; i<size; i++)
System.out.print(data[i] + " ");
}
public boolean insert(Listing newListing)
{
int i = 0;
while(i < size && data[i]!= null)
{
if(data[i].getKey().compareTo(newListing.getKey()) > 0)
i = 2 * i + 1;
else
i = 2 * i + 2;
}
if(i >= size)
return false;
else
{
data[i] = newListing.deepCopy();
return true;
}
}
public Listing fetch(String targetKey)
{
int i= 0;
while(i< size && data[i]!= null && data[i].getKey()!=targetKey)
{
if(data[i].getKey().compareTo(targetKey) > 0)
i = 2 * i + 1;
else
i = 2 * i + 2;
}
if(i >= size || data[i] == null)
return null;
else
return data[i].deepCopy();
}
}
public class Listing implements Comparable<Listing>
{ private String name; // key field
private int ID;
private double GPA;
public Listing(String n, int id, double gpa)
{ name = n;
ID = id;
GPA = gpa;
}
public String toString()
{ return("Name is " + " " + name +
"\nID is" + " " + ID +
"\nGPA is" + " " + GPA + "\n");
}
public Listing deepCopy()
{ Listing clone = new Listing(name, ID, GPA);
return clone;
}
public int compareTo(Listing other)
{
return this.name.compareTo(other.getKey());
}
public String getKey()
{
return name;
}
}// end of class Listing
Hello All,
My java program compiles fine, but I am having a terrible and miserable time with getting my program to stop printing all those nulls when I output all student records in my BinaryTreeArray. Here is complete program. Any suggestions? Please do give any advice. So to make what I am saying clear, I need help with understanding why when I print out student records it includes a whole bunch of extra nulls that really have no purpose and just make my program look crazy. Any solutions to this problem?
When you initialize the BinaryTreeArray(), you set the field variable "size" to 100 and use this to initialize the data Listing[] array. When you print out the data, the loop uses the same "size" variable so you get all 100 entries, including the null entries. A simple solution would be to filter the data for null when you show all.
public class BinaryTreeArray
{
...
public void showAll()
{
for(int i=0; i<size; i++)
{
if (data[i] != null)
System.out.print(data[i] + " ");
}
}
...
}
An alternate solution would be to change your use of size to maxSize and then create a variable size that is incremented as you insert listings.
I'm having some problem with a household budget application.After I insert a new income or bill, checking the budget, the program add even the previous bill (or income) as commented in the Client code.
public class Client {
public static void main(String[] args) {
Budget bud = new Budget();
Bills[] expenses = new Bills[10];
Income[] salary = new Income[4];
boolean toContinue = true;
String input = "";
int menuItem = 0;
int counter = 0;
int salCount = 0;
float budget = 0;
while (toContinue) {
input = JOptionPane
.showInputDialog("(1) Add an expense\n(2) Add the salary\n(3) Display Current Budget\n(4) Exit");
menuItem = Integer.parseInt(input);
switch (menuItem) {
case 1: //Add expense
String name = JOptionPane.showInputDialog("Enter the name of the expense");
double amount = Double.parseDouble(JOptionPane.showInputDialog("Enter the amount for " + name));
expenses[counter++] = new Bills(name, amount);
break;
case 2: //Add salary
String checkSal = JOptionPane.showInputDialog("Enter salary details");
double checkAm = Double.parseDouble(JOptionPane.showInputDialog("Enter the amount of " + checkSal));
salary[salCount++] = new Income(checkSal, checkAm);
break;
case 3: // display current budget
try {
String expDisplay = "Expenditure\t Amount\n";
String salDisplay = "Salary\t Amount\n";
float expenseSum = 0;
float salarySum = 0;
for (int i = 0; i < salary.length; i++) {
if (salary[i] != null)
salarySum += salary[i].Total();
}
for (int e = 0; e < expenses.length; e++) {
if (expenses[e] != null)
expenseSum += expenses[e].Total();
}
for (Bills e : expenses) {
if (e != null)
expDisplay += e.toString() + "\n";
}
for (Income p : salary) {
if (p != null)
salDisplay += p.toString() + "\n";
}
File fileBudget = new File("C:budget.txt");
if (!fileBudget.exists()) { //creating new txt
bud.setBudget(budget);
fileBudget.createNewFile();
System.out.println("TEXT File Created");
FileWriter fw = new FileWriter(fileBudget, false);
fw.write(bud.getBud() + "");
fw.flush();
fw.close();
budget = salarySum - expenseSum; //calculating budget
JOptionPane.showMessageDialog(null, expDisplay + "\n\n" + salDisplay + "\n\n" + "You spent: "
+ expenseSum + "\n" + "Budget: " + budget);
} else {
BufferedReader re = new BufferedReader(new FileReader("C:budget.txt")); //reading budget on txt file
while (true) {
String line = re.readLine();
if (line == null) {
break;
} else {
float d = Float.valueOf(line);
bud.setBudget(d); //store the read value
}
}
re.close(); //end reading
float c = bud.getBud(); //taking budget value
// problem...there are even previous sum values!!
budget = salarySum - expenseSum + c; // error
FileWriter fw = new FileWriter(fileBudget, false);
fw.write(budget + "\n");
fw.flush();
fw.close();
JOptionPane.showMessageDialog(null, expDisplay + "\n\n" + salDisplay + "\n\n" + "You spent: "
+ expenseSum + "\n" + "Budget: " + budget);
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
break;
case 4: //close program
JOptionPane.showMessageDialog(null, "You closed the Budget Program!");
System.exit(0); }}}}
//budget object
public class Budget implements Serializable {
private static final long serialVersionUID = 1L;
public float bud;
Budget()
{
}
public float getBud() {
return bud;
}
public void setBudget(float bud) {
this.bud = bud; }}
//Bill class
public class Bills {
private double amount;
private String name;
public Bills(double amount) {
this.amount = amount;
}
public Bills(String name, double amount) {
this.name = name;
this.amount = amount;
}
public Bills() {
this("New Expense", 0); }
public String toString() {
return name + "\t " + "\t " + amount; }
public double Total() {
return amount; }}
//Income class
public class Income {
private double amount;
private String Salary;
public Income(String Salary, double amount) {
this.Salary = Salary;
this.amount = amount;
}
public String toString() {
return Salary + "\t " + "\t " + amount;
}
public double Total() {
return amount; }}
There are several problems with your code.
First of all here:
for (int i = 0; i < salary.length; i++)
{
if (salary[i] != null)
{
salarySum += salary[i].Total();
}
}
for (int e = 0; e < expenses.length; e++)
{
if (expenses[e] != null)
{
expenseSum += expenses[e].Total();
}
}
Each time your user enter [3] to see the details, these numbers added, and then the budget is calculated, this budget then is added to the file.
On the same session now, the user click again [3] and the above is repeated.
You should find a way to actually identify when the user have enter a new expense or a new salary, to avoid repeating the calculation of the budget and then the assignment to the file. (Boolean variable probably?)
Moreover here:
if (!fileBudget.exists()) { //creating new txt
bud.setBudget(budget);
fileBudget.createNewFile();
System.out.println("TEXT File Created");
FileWriter fw = new FileWriter(fileBudget, false);
fw.write(bud.getBud() + "");
fw.flush();
fw.close();
budget = salarySum - expenseSum; //calculating budget
JOptionPane.showMessageDialog(null, expDisplay + "\n\n" + salDisplay + "\n\n" + "You spent: "
+ expenseSum + "\n" + "Budget: " + budget);
}
You always assign a zero value to the file. Even if the file is going to be created, maybe the user have already provided some budget, and you will lose this number. I think you have to calculate the budget there as well.
Edit:
A possible solution, and to simplify things, is to actually add to the file whenever the user enter a new salary, and subtract from the file whenever user enter an expense, so these two actions will take place in the first two cases (1 and 2) of the select statement. (Both actions, require that you read the text value first and then you add the new salary or you then subtract the new expense). This way your file will contain the latest calculated budget, and in the 3rd case you will only read the value from the file, which will contain the latest calculated budget, rather than calculating the budget in the 3rd case every time!
my previous questions have been taken care of. However I'm having an issue with the accuracy of data I'm pulling from another class. I'm aware that currentScore.finalScore only updates when used. However, I have finalScore = currentScore.finalScore. The print line I have shows that it updates, but by seemingly random numbers and even when this number causes the while statement to become false, it continues infinitely.
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
String buddyName;
String userChoice;
int maxScore = 10;
int minScore = 0;
System.out.print("Nurse: The Patient's first name is ");
buddyName = keyboard.nextLine();
System.out.print("You: Let's see, I should (C)hange " + buddyName + "'s bandages," +
"(G)ive " + buddyName + " pain medication, " +
"(A)dd antibiotics to " + buddyName + "'s I.V," +
" or (D)ischarge " + buddyName + " ");
userChoice = keyboard.nextLine();
Buddy score = new Buddy(userChoice);
BuddyScore currentScore = new BuddyScore(score);
int finalScore;
do {
System.out.print("You: Let's see, I should (C)hange " + buddyName + "'s"
+ " bandages, (G)ive " + buddyName + " pain medication, " +
"(A)dd antibiotics to " + buddyName + "'s I.V," +
" or (D)ischarge " + buddyName + " ");
userChoice = keyboard.nextLine();
score.setUserChoice(userChoice);
finalScore = currentScore.getFinalScore();
System.out.println(currentScore.getFinalScore());
}while (currentScore.getFinalScore() < maxScore && currentScore.getFinalScore() >= minScore);
System.out.println("Curren score: " + currentScore.getFinalScore());
}
}
Below is my class that handles the finalScore, and is the class I'm suspect of.
public class BuddyScore {
private Buddy buddyScore;
public int finalScore;
public BuddyScore(Buddy buddyScore){
this.buddyScore = buddyScore;
this.finalScore = finalScore;
}
public void setFinalScore(int finalScore){
this.finalScore = finalScore;
}
public int getFinalScore(){
return finalScore += buddyScore.getBuddyScore();
}
}
Below is the class that handles the buddyScore that the finalScore pulls from.
public class Buddy {
private String userChoice;
public int buddyScore;
public Buddy(String userChoice){
this.userChoice = userChoice;
}
public void setUserChoice(String userChoice){
this.userChoice = userChoice;
}
public String getUserChoice(){
return userChoice;
}
public void setBuddyScore(int buddyScore){
this.buddyScore = buddyScore;
}
public int getBuddyScore(){
switch (userChoice){
case "C":
buddyScore = 1;
break;
case "G":
buddyScore = -2;
break;
case "A":
buddyScore = 3;
break;
case "D":
buddyScore = 7;
break;
default:
buddyScore = 0;
break;
};
return buddyScore;
}
Thank you in advance.
The side effect of your getFinalScore method is that it alters the finalScore with the return value of getBuddyScore before finally returning. As a result, each call to getFinalScore will increase the value. In your loop, I see you calling that method four times; if you step through the code, you should see four completely different values within the same iteration.
I am guessing you want to do this instead?
return finalScore + buddy.getBuddyScore();
your while loop is wrong,
the operator should be && not ||
while (currentScore.getFinalScore() < maxScore && currentScore.getFinalScore() >= minScore);
causes this to always be true with a value of 0 and above.
This is my code for STUDENT RECORD SYSTEM. I think it is on its 80% of completion. The problem here is that when i have many students and i update a specific student(subj & grade) the updated element is not being saved on that specific student. And when I display all of the results the updated values are given to other student. Please help me out with this issue. And btw this code has 2 classes Student and StudentGrade. I hope you'll help me fix this. Thanks in advance. :) and Advance Happy New Year!
public class Student
{
private String IDNumber;
private String firstName;
private String middleName;
private String lastName;
private String degree;
private int yearLevel;
public Student()
{
String IDNum;
String fName;
String mName;
String lName;
String deg;
int level;
}
public Student(String IDNum, String fName, String mName, String lName, String deg,int level )
{
this.IDNumber=IDNum;
this.firstName=fName;
this.middleName=mName;
this.lastName=lName;
this.degree=deg;
this.yearLevel=level;
}
public void setIdNumber(String IDNumber)
{
this.IDNumber = IDNumber;
}
public String getIdNumber()
{
return IDNumber;
}
public void setFirstName(String firstName)
{
this.firstName=firstName;
}
public String getFirstName()
{
return firstName;
}
public void setMiddleName(String middleName)
{
this.middleName=middleName;
}
public String getMiddleName()
{
return middleName;
}
public void setLastName(String lastName)
{
this.lastName=lastName;
}
public String getLastName()
{
return lastName;
}
public void setDegree(String degree)
{
this.degree=degree;
}
public String getDegree()
{
return degree;
}
public void setYearLevel(int yearLevel)
{
this.yearLevel=yearLevel;
}
public int getYearLevel()
{
return yearLevel;
}
}
public class StudentGrade
{
private String IDNumber;
private String subject;
private double grade;
private double average;
public StudentGrade()
{
String IDNum;
String sub;
double grad;
double ave;
}
public StudentGrade(String IDNum,String sub,double grad,double ave)
{
this.IDNumber=IDNum;
this.subject=sub;
this.grade=grad;
this.average=ave;
}
public void setSubject(String subject)
{
this.subject=subject;
}
public String getSubject()
{
return subject;
}
public void setGrade(double grade)
{
this.grade=grade;
}
public double getGrade()
{
return grade;
}
public String getIDNumber()
{
return IDNumber;
}
}
public class StudentGrade
{
private String IDNumber;
private String subject;
private double grade;
private double average;
public StudentGrade()
{
String IDNum;
String sub;
double grad;
double ave;
}
public StudentGrade(String IDNum,String sub,double grad,double ave)
{
this.IDNumber=IDNum;
this.subject=sub;
this.grade=grad;
this.average=ave;
}
public void setSubject(String subject)
{
this.subject=subject;
}
public String getSubject()
{
return subject;
}
public void setGrade(double grade)
{
this.grade=grade;
}
public double getGrade()
{
return grade;
}
public String getIDNumber()
{
return IDNumber;
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class test2 {
static ArrayList<Student> studentList = new ArrayList<Student>();
static ArrayList<StudentGrade> studentLists = new ArrayList<StudentGrade>();
public static void main(String[] args)
{
menu();
}
public static void menu()
{
Scanner in = new Scanner(System.in);
int choice = 0;
System.out.print("*********STUDENT RECORD SYSTEM*********\n\n");
System.out.println("\t MENU ");
System.out.println("[1]ADD STUDENT");
System.out.println("[2]DISPLAY ALL");
System.out.println("[3]DISPLAY SPECIFIC");
System.out.println("[4]UPDATE");
System.out.println("[5]AVERAGE");
System.out.println("[6]EXIT");
System.out.println("?");
choice = in.nextInt();
if (choice == 1)
{
add();
}
else if (choice == 2)
{
displayAll();
}
else if (choice == 3)
{
displaySpecific();
}
else if (choice == 4)
{
update();
}
else if (choice == 5)
{
average();
}
else if( choice == 6)
{
System.exit(0);
}
else
menu();
}
public static void add()
{
Scanner in = new Scanner(System.in);
char ans;
String temp;
int total;
do {
System.out.println("NUMBER OF STUDENTS YOU WANT TO INPUT: ");
total = in.nextInt();
Student[] student = new Student[total];
for (int index = 0; index < student.length; index++) {
student[index] = new Student();
System.out.print("**********STUDENT INFORMATION**********\n\n");
System.out.println("PRESS ENTER");
in.nextLine();
System.out.print("ID NUMBER: ");
student[index].setIdNumber(in.nextLine());
System.out.print("FIRST NAME: ");
student[index].setFirstName(in.nextLine());
System.out.print("MIDDLE NAME: ");
student[index].setMiddleName(in.nextLine());
System.out.print("LAST NAME: ");
student[index].setLastName(in.nextLine());
System.out.print("DEGREE: ");
student[index].setDegree(in.nextLine());
System.out.print("YEAR LEVEL: ");
student[index].setYearLevel(in.nextInt());
studentList.add(student[index]);
}
System.out.print("Would you like to enter in a new student (y/n)? ");
String answer = in.next();
ans = answer.charAt(0);
} while (ans == 'y');
/* // SEARCH and DISPLAY SPECIFIC
String id = new String();
in.nextLine();
System.out.print("Enter ID NUMBER: ");
id = in.nextLine();
for (int j = 0; j < studentList.size(); j++) {
if (id.equals(studentList.get(j).getIdNumber())) {
System.out.printf("STUDENT SEARCHED");
System.out.print("\nID NUMBER: "
+ studentList.get(j).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(j).getFirstName() + " "
+ studentList.get(j).getMiddleName() + " "
+ studentList.get(j).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(j).getDegree() + "-"
+ studentList.get(j).getYearLevel() + "\n\n");
System.out.println();
}
}
// DISPLAY ALL
for (int i = 0; i < studentList.size(); i++) {
System.out.printf("STUDENT[%d]", i + 1);
System.out
.print("\nID NUMBER: " + studentList.get(i).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(i).getFirstName() + " "
+ studentList.get(i).getMiddleName() + " "
+ studentList.get(i).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(i).getDegree() + "-"
+ studentList.get(i).getYearLevel());
System.out.println();
} */
menu();
}
public static void displayAll() {
Scanner in = new Scanner(System.in);
if(studentList.size() == 0)
{
System.out.print("EMPTY lageeeee!!! \nPLEASE INPUT FIRST\n\n");
in.nextLine();
}
else
{
if(studentLists.size() == 0){
System.out.print("************STUDENT RECORD*************");
for (int i = 0; i < studentList.size(); i++) {
System.out.printf("\nSTUDENT[%d]", i + 1);
System.out
.print("\nID NUMBER: " + studentList.get(i).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(i).getFirstName() + " "
+ studentList.get(i).getMiddleName() + " "
+ studentList.get(i).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(i).getDegree() + "-"
+ studentList.get(i).getYearLevel()/* +"\nGrade: "
+ studentLists.get(i).getGrade() */+"\n\n");
}
in.nextLine();
}
else{
System.out.print("************STUDENT RECORD*************");
for (int i = 0; i < studentList.size(); i++)
{
System.out.printf("\nSTUDENT[%d]", i + 1);
System.out
.print("\nID NUMBER: " + studentList.get(i).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(i).getFirstName() + " "
+ studentList.get(i).getMiddleName() + " "
+ studentList.get(i).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(i).getDegree() + "-"
+ studentList.get(i).getYearLevel()+"\n\n");
}
for(int xxx = 0 ; xxx < studentLists.size(); xxx++ )
{
System.out.printf("\nSUBJECT: "
+ studentLists.get(xxx).getSubject()+" Grade: "
+ studentLists.get(xxx).getGrade());
}
in.nextLine();
}
}
menu();
}
public static void displaySpecific() {
Scanner in = new Scanner(System.in);
if(studentList.size() == 0)
{
System.out.print("EMPTY oe!!! KALAGOT!\nPLEASE INPUT FIRST\n");
in.nextLine();
}
else
{
String id = new String();
/* in.nextLine(); */
System.out.print("Enter ID NUMBER: ");
id = in.nextLine();
if(studentLists.size()==0)
{
for (int j = 0; j < studentList.size(); j++)
{
if (id.equals(studentList.get(j).getIdNumber()))
{
System.out.printf("\n*************STUDENT SEARCHED*************");
System.out.print("\nID NUMBER: "
+ studentList.get(j).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(j).getFirstName() + " "
+ studentList.get(j).getMiddleName() + " "
+ studentList.get(j).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(j).getDegree() + "-"
+ studentList.get(j).getYearLevel() + /* "\nGrade: "
+ studentLists.get(j).getGrade()+ */"\n\n");
System.out.println();
in.nextLine();
}
/* else
{
System.out.print("STUDENT DOES NOT EXIST IN THIS WORLD!");
in.nextLine();
} */
}
}
else
{
for (int j = 0; j < studentList.size(); j++)
{
if (id.equals(studentList.get(j).getIdNumber()))
{
System.out.printf("\n*************STUDENT SEARCHED*************");
System.out.print("\nID NUMBER: "
+ studentList.get(j).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(j).getFirstName() + " "
+ studentList.get(j).getMiddleName() + " "
+ studentList.get(j).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(j).getDegree() + "-"
+ studentList.get(j).getYearLevel() +"\n\n");
System.out.println();
}
}
for(int xxx = 0 ; xxx < studentLists.size(); xxx++ )
{
System.out.printf("\nSUBJECT: "
+ studentLists.get(xxx).getSubject()+" Grade: "
+ studentLists.get(xxx).getGrade());
}
in.nextLine();
}
}
menu();
}
public static void update()
{
Scanner in = new Scanner(System.in);
String idnum = new String();
char answer;
in.nextLine();
System.out.print("Enter ID NUMBER: ");
idnum = in.nextLine();
int total;
for(int x=0;x<studentList.size();x++)
{
if(idnum.equals(studentList.get(x).getIdNumber()))
{
System.out.println("NUMBER OF SUJECTS YOU WANT TO INPUT: ");
total = in.nextInt();
do
{
StudentGrade[] update = new StudentGrade[total];
for(int y = 0;y<update.length;y++)
{
update[y] = new StudentGrade();
in.nextLine();
System.out.print("ENTER SUBJECT: ");
update[y].setSubject(in.nextLine());
System.out.print("ENTER GRADE: ");
update[y].setGrade(in.nextDouble());
studentLists.add(update[y]);
}
System.out.print("Enter another subject and grade? [y/n]");
String ans = in.next();
answer = ans.charAt(0);
}while(answer == 'y');
}
menu();
}
}
public static void average()
{
Scanner in = new Scanner(System.in);
double sum=0;
double average=0;
String ID = new String();
System.out.print("ENTER ID NUMBER: ");
ID = in.nextLine();
for(int xx=0;xx<studentList.size();xx++)
{
if(ID.equals(studentList.get(xx).getIdNumber()))
{
for(int ind=0;ind<studentLists.size();ind++)
{
sum += studentLists.get(ind).getGrade();
average=sum/studentLists.size();
}
System.out.print("ID NUMBER:"+studentList.get(xx).getIdNumber()+"\nNAME: "
+studentList.get(xx).getFirstName()+" "
+studentList.get(xx).getMiddleName()+" "
+studentList.get(xx).getLastName());
System.out.print("\nAVERAGE: "+average+"\n");
in.nextLine();
}
}
menu();
}
}
First of all I would change studentList to Map to be able to get the student by id directly and not to search for the matching student every time.
The access to the collections of all students is then like this:
for(Map.Entry<String, Student> entry : studentList.entrySet()){
String id = entry.getKey();
Student student = entry.getValue();
// ...
}
A a second step you should check your update method. I see, that you a searching for the student, but you don't updating this object. You are adding a new one at the end of the loop with studentList.add().
You have store the matching Student into the local variable and just modify this without modifying the collection of students.
You have two reader statements in update function
public static void update()
{
Scanner in = new Scanner(System.in);
String idnum = new String();
char answer;
Scanner in = new Scanner(System.in);
String idnum = new String();
char answer;
in.nextLine();//1
System.out.print("Enter ID NUMBER: ");
idnum = in.nextLine();//2
I think there should be only one as your just reading the id number and as #Vlad said your adding a new element to the array list rather than modifying the existing data .
also for your code you can use
arrayList.set(index i,String replaceElement);// this will help you replace the value at a particular index
it is better to use HashMap instead of array list so when you put an existing element into
a map the value is overwritten.
static Map <String,Student> studentList = new HashMap<String,Student>();
static Map<String, List<StudentGrade>> studentLists = new HashMap<String, List<StudentGrade>>();
Here the key will be the student idNumber
I have programed a Worker and MachineWorker class. It complies fine. but when i run it, after three consecutive statements the program stops. I cannot find the problem, and I dont know how and when to use 'instanceof'.
I am writing the question below and with all the classes...
Question:- (i)Declare an array that can store the references of up to 5 Worker or MachineWorker objects.
a)Allow user to enter the type of object and the data for that type of object(3 values for Worker and 4 values for MachineWorker).
b)Construct the appropriate object storing the reference in the common array.
ii)Now allow the users to enter the weekly data repeatedly. If it is Worker object user must enter ID and hours-worked. If it is a MachineWorker object user must enter ID,hoursWorked and pieces. Once these values read search through the array to locate the object with the given ID before calling the addWeekly().The number of arguments either(1 or 2) to be passed to addWeekly depends on the type of objects being referred. To determine the type of object being referred(Worker or MachineWorker)you may use the instanceof operator.
Please see my codes below:-
//Worker.java
public class Worker {
public final double bonus=100;
protected String name, workerID;
protected double hourlyRate, totalHoursWorked,tax,grossSalary,netSalary;
public Worker(){
}
public Worker(String name, String workerID, double hourlyRate){
this.name = name;
this.workerID = workerID;
this.hourlyRate = hourlyRate;
}
public void addWeekly(double hoursWorked){
this.totalHoursWorked = this.totalHoursWorked + hoursWorked;
}
public double gross(){
grossSalary = (totalHoursWorked*hourlyRate);
if(totalHoursWorked>=150){
grossSalary = grossSalary +100;
}
return grossSalary;
}
public double netAndTax(){
netSalary = grossSalary;
if(grossSalary>500){
tax = (grossSalary - 500) *0.3;
netSalary = (grossSalary - tax);
}
return netSalary;
}
public String getName(){
return this.name;
}
public String getWorkerID(){
return this.workerID;
}
public double getHourlyRate(){
return this.hourlyRate;
}
public double getTotalHours(){
return totalHoursWorked;
}
public double getGrossSalary(){
return grossSalary;
}
public void addToGross(double amt){
grossSalary = grossSalary + amt;
}
public void displaySalary(){
System.out.print("Name: " +getName() + "\nID :" + getWorkerID()
+ "\nHourly Rate: " + getHourlyRate()+ "\nTotalHours Worked" + getTotalHours() +
"\nGross pay" + getGrossSalary() + "\nTax: " + netAndTax() +
"\nNet Pay: " + netAndTax());
}
}
//MachineWorker.java
public class MachineWorker extends Worker{
private double targetAmount;
private double totalPieces, productivityBonus;
public MachineWorker(String workerName, String workerID, double hourlyRate, double targetAmount)
{
super(workerName, workerID, hourlyRate);
//this.productivityBonus = productivityBonus;
this.targetAmount = targetAmount;
}
public void addWeekly(double hoursWorked, double weeklyAmount)
{
totalHoursWorked = hoursWorked + totalHoursWorked;
totalPieces = weeklyAmount + totalPieces;
}
public double productivityBonus()
{
productivityBonus = 100 + (totalPieces - targetAmount);
return productivityBonus;
}
public double gross()
{
grossSalary = (totalHoursWorked * hourlyRate) + productivityBonus;
if(totalHoursWorked >= 150)
{
grossSalary = grossSalary + bonus;
}
return grossSalary;
}
public void addToGross(double amt)
{
amt = productivityBonus;
grossSalary = grossSalary + amt;
}
public void displaySalary()
{
System.out.println("Name " + super.name + "\nID " +
super.workerID + "\nHourly rate " + super.hourlyRate + "\nTotal Hours Worked " +
super.totalHoursWorked + "\nGross Pay $" + super.grossSalary + "\nTax $" + super.tax + "\nNetpay $" + super.netSalary);
System.out.println("Productivity Bonus " + productivityBonus);
}
}
//Polymorphism PolyWorker.java
import java.util.*;
public class PolyWorkers
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
Worker[] a = new Worker[5];
MachineWorker[] b = new MachineWorker[5];
char option = '0';
String choice;
boolean nChar = false;
for (int i = 0; i < 5; i++){
System.out.print("\tType of object " + (i+1) + " [W/M]: ");
choice = input.nextLine();
if (choice.length() == 1)
{
option = choice.charAt(0); //pick the first character
if (option == 'w' || option == 'W')
{
System.out.println("\n\tEnter name, ID and hours: ");
String name = input.nextLine();
System.out.print(" ");
String id = input.nextLine();
System.out.print(" ");
double hours = input.nextDouble();
a[i] = new Worker(name, id, hours);
System.out.println();
}
if (option == 'm' || option == 'M')
{
System.out.print("\n\tEnter name, ID, hours and pieces: ");
String name = input.nextLine();
System.out.print(" ");
String id = input.nextLine();
System.out.print(" ");
double hours = input.nextDouble();
System.out.print(" ");
double pieces = input.nextDouble();
b[i] = new MachineWorker(name, id, hours, pieces);
System.out.println();
}
System.out.print("\tType of object " + (i+1) + " [W/M]: ");
choice = input.nextLine();
}
a[i].displaySalary();
b[i].displaySalary();
b[i].productivityBonus();
}
}
}
You might want to use overriden methods readfromInput and displaySalary to distinguish between what Worker and Machinworker does.
The different behaviour should be implemented within the classes and not in the calling Polyworker class.
If Machineworker displaySalary shows the bonus this should be called in displaySalary of MachineWorker
see modified code below
//Worker.java
import java.util.Scanner;
/**
* a generic worker
*/
public class Worker {
public final double bonus = 100;
protected String name, workerID;
protected double hourlyRate, totalHoursWorked, tax, grossSalary, netSalary;
public void addWeekly(double hoursWorked) {
this.totalHoursWorked = this.totalHoursWorked + hoursWorked;
}
public double gross() {
grossSalary = (totalHoursWorked * hourlyRate);
if (totalHoursWorked >= 150) {
grossSalary = grossSalary + 100;
}
return grossSalary;
}
public double netAndTax() {
netSalary = grossSalary;
if (grossSalary > 500) {
tax = (grossSalary - 500) * 0.3;
netSalary = (grossSalary - tax);
}
return netSalary;
}
public String getName() {
return this.name;
}
public String getWorkerID() {
return this.workerID;
}
public double getHourlyRate() {
return this.hourlyRate;
}
public double getTotalHours() {
return totalHoursWorked;
}
public double getGrossSalary() {
return grossSalary;
}
public void addToGross(double amt) {
grossSalary = grossSalary + amt;
}
public void displaySalary() {
System.out.print("Name: " + getName() + "\nID :" + getWorkerID()
+ "\nHourly Rate: " + getHourlyRate() + "\nTotalHours Worked"
+ getTotalHours() + "\nGross pay" + getGrossSalary() + "\nTax: "
+ netAndTax() + "\nNet Pay: " + netAndTax());
}
public void readFromInput(Scanner input) {
name = input.nextLine();
System.out.print(" ");
this.workerID= input.nextLine();
System.out.print(" ");
this.totalHoursWorked = input.nextDouble();
System.out.println();
}
} // Worker
//MachineWorker.java
import java.util.Scanner;
public class MachineWorker extends Worker {
private double targetAmount;
private double totalPieces, productivityBonus;
public void addWeekly(double hoursWorked, double weeklyAmount) {
totalHoursWorked = hoursWorked + totalHoursWorked;
totalPieces = weeklyAmount + totalPieces;
}
public double productivityBonus() {
productivityBonus = 100 + (totalPieces - targetAmount);
return productivityBonus;
}
public double gross() {
grossSalary = (totalHoursWorked * hourlyRate) + productivityBonus;
if (totalHoursWorked >= 150) {
grossSalary = grossSalary + bonus;
}
return grossSalary;
}
public void addToGross(double amt) {
amt = productivityBonus;
grossSalary = grossSalary + amt;
}
#Override
public void displaySalary() {
super.displaySalary();
System.out.println("Productivity Bonus " + productivityBonus);
}
#Override
public void readFromInput(Scanner input) {
super.readFromInput(input);
this.totalPieces = input.nextDouble();
}
}
//Polymorphism PolyWorker.java
import java.util.*;
public class PolyWorkers {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
Worker[] workers = new Worker[5];
char option = '0';
String choice;
for (int i = 0; i < 5; i++) {
System.out.print("\tType of object " + (i + 1) + " [W/M]: ");
choice = input.nextLine();
if (choice.length() == 1) {
option = choice.toLowerCase().charAt(0); // pick the first character
switch (option) {
case 'w': {
workers[i] = new Worker();
System.out.println("\n\tEnter name, ID and hours: ");
}
break;
case 'm': {
System.out.print("\n\tEnter name, ID, hours and pieces: ");
}
break;
} // switch
workers[i].readFromInput(input);
}
workers[i].displaySalary();
}
}
}
Your question states that you have to store the references in a common array, where as you are storing them in 2 different arrays a and b. As you have different arrays for different type of objects, you don't have the need to use instanceOf operator. More about instanceOf is here.
Also, you do not check for null while printing salary or bonus. As at any point of the loop, only one type of object will be created, one of a[i] or b[i] will be definitely null, causing a NullPointerException.
You need another loop after the one you have already written that will allow the user to input the worker's hours. This will presumably be a while loop that will continually ask for input. You would then choose some sort of input that would quit the loop. Inside the loop you ask for hours and take either 2 or 3 arguments.
At the moment you are not storing your Workers/MachineWorkers. You need to create an array to store them in. You also need to create either a base class or an interface that they will both extend/implement. This will allow you to create a single array to store them all.
You then loop through your array of Workers/MachineWorkers and when you find a matching id you use your instanceof to work out whether you need to pass 1 or 2 arguments. If it is a MachineWorker you should cast it as such and then call the appropriate method with 2 arguments.