method not printing all values in java - java

i have 2 java programs , the first one takes all information about the employee(id , name , department etc)from the user and prints it , the second program lets the user choose how many number of employees are there then it takes the values like(employ id, name etc), this program uses an array to store the values , it should print all values of different employees , but when i run the program the second set of values overrides the first set of values and prints the second set of values twice , im a beginner so plse help
This is the first program
import java.util.Scanner;
public class payroll2
{
public static void main(String args[])
{
payroll2 payroll = new payroll2();
payroll.SetPayrollDetail();
payroll.SetBonus();
payroll.SetCommission();
payroll.SetNssf();
payroll.SetNetSalary();
payroll.GetPayroll();
}
Scanner myScanner=new Scanner(System.in);
int empID;
String empName;
String empDept;
String designation;
int basicSalary;
double bonus;
double commission;
double nssf;
double netSalary;
public void SetPayrollDetail()
{
System.out.println("Enter ID: ");
empID = myScanner.nextInt();
System.out.println("Enter Name: ");
empName = myScanner.next();
System.out.println("Enter Department (Marketing or Other): ");
empDept = myScanner.next();
System.out.println("Enter Designation (Manager, Executive or Other): ");
designation = myScanner.next();
System.out.println("Enter Basic Salary: ");
basicSalary = myScanner.nextInt();
}
public void SetBonus()
{
if(basicSalary < 1500){
bonus = 0.0;
}
else if(basicSalary>=1500 && basicSalary<3000){
bonus = basicSalary * (12.0/100.0);
}
else if(basicSalary>=3000 && basicSalary<5000){
bonus = basicSalary * (15.0/100.0);
}
else{
bonus = basicSalary * (25.0/100.0);
}
}
public void SetCommission()
{
if( empDept.equalsIgnoreCase("other") ){
commission = 0.0;
}
else if( empDept.equalsIgnoreCase("marketing") && designation.equalsIgnoreCase("manager") ){
commission = basicSalary * (30.0/100.0);
}
else if( empDept.equalsIgnoreCase("marketing") && designation.equalsIgnoreCase("executive") ){
commission = basicSalary * (15.0/100.0);
}
else if( empDept.equalsIgnoreCase("marketing") && designation.equalsIgnoreCase("other") ){
commission = basicSalary * (10.0/100.0);
}
else{
commission = 0.0;
}
}
public void SetNssf()
{
if(basicSalary < 1500){
nssf = basicSalary * (5.0/100.0);
}
else if(basicSalary>=1500 && basicSalary<3000){
nssf = basicSalary * (8.0/100.0);
}
else if(basicSalary>=3000 && basicSalary<5000){
nssf = basicSalary * (12.0/100.0);
}
else if(basicSalary>=5000 && basicSalary<7000){
nssf = basicSalary * (15.0/100.0);
}
else if(basicSalary>=7000 && basicSalary<10000){
nssf = basicSalary * (20.0/100.0);
}
else{
nssf = basicSalary * (25.0/100.0);
}
}
public void SetNetSalary()
{
netSalary = ( basicSalary + commission + bonus ) - nssf;
}
public void GetPayroll()
{
System.out.println("\n\nPayroll Details \n _____________________");
System.out.println("ID:\t\t" + empID);
System.out.println("name:\t\t" + empName);
System.out.println("Bonus:\t\t" + bonus);
System.out.println("Commission:\t"+commission);
System.out.println("NSSF:\t\t"+nssf);
System.out.println("Net Salary:\t"+netSalary);
}
}
This is the second program
import java.util.Scanner;
public class display{
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
int counter;
int limit;
System.out.println("How many employess do u want to enter?\n Enter here: ");
limit = scan.nextInt();
int[] a = new int[limit];
payroll2 payroll = new payroll2();
for(counter=1; counter<=limit; counter++){
System.out.println("\n\nEnter employee "+counter+" details\n");
payroll.SetPayrollDetail();
payroll.SetBonus();
payroll.SetCommission();
payroll.SetNssf();
payroll.SetNetSalary();
}
for(counter=1; counter<=limit; counter++){
payroll.GetPayroll();
//System.out.println(a);
}
}
}

This is the area of code that there's a problem in:
for(counter=1; counter<=limit; counter++){
System.out.println("\n\nEnter employee "+counter+" details\n");
payroll.SetPayrollDetail();
payroll.SetBonus();
payroll.SetCommission();
payroll.SetNssf();
payroll.SetNetSalary();
}
for(counter=1; counter<=limit; counter++){
payroll.GetPayroll();
//System.out.println(a);
}
If you think about what this does. So a payroll2 object is a single entity. When you enter them in the first for loop, you create one person. Then if you loop through that a second or third time, you overwrite that person, since you are saving to the same variable.
Then when you loop through the second loop, you are printing the payroll entity, which holds the value of the last entered person. Since the other data gets overwritten, its no surprise that you get the same guy printed limit times.
What you will want to do is build an array of payroll entities. This code accomplishes this:
payroll2[] PayrollList = new payroll2[limit]; // establish the array with correct size
for(counter=0; counter<=limit - 1; counter++){ // bounds of the array are 0 to limit - 1
payroll = new payroll(); // hard reset of the variable to make sure data is cleared
System.out.println("\n\nEnter employee "+counter+" details\n");
payroll.SetPayrollDetail();
payroll.SetBonus();
payroll.SetCommission();
payroll.SetNssf();
payroll.SetNetSalary();
PayrollList[counter] = payroll; // adds it to the array at position counter
}
for(counter=0; counter<=limit - 1; counter++){
PayrollList[counter].GetPayroll(); // gets the payroll2 object from the array and calls its function
}
DISCLAIMER: I have not run the modified code through a compiler, so it may not be 100% syntax correct, but it is very close.

Related

Array storage Java

I want my array of students to have their name and grade associated. So when I call on them after the fact I can display the top two performing students. This is homework So I don't need to have the whole code completed but I would like some help with making sure the inputs are properly stored. Right now my variables are x and i, x being the number of students, and i being the counter. Again my issues are with associating the grades of the students inputted with the names. I hope there is enough information.
import java.util.Scanner;
public class Q3 {
public static void main(String[] args) {
int x = 0;
double average = 0;
int i = 0;
Scanner in = new Scanner(System.in);
System.out.println("Please eneter how many students you have: ");
x = in.nextInt();
int students = 0;
int sum = 0;
int grades[] = new int[x];
String[] names = new String[x];
for(i = 0; i <= x; i++) {
System.out.println("Please enter student name: ");
String name = in.nextLine();
names[i] = name;
System.out.println("Grade: ");
int grade = in.nextInt();
grades[i] = grade;
students++;
sum += grade;
x++;
}
if(students>0) {
average = (double) sum/students;
}
System.out.println("The average is " + average);
System.out.println("There are " + students + " students");
System.out.println("The top two students are: " + grades);
}
}
The problem with your current code is that the for loop will never end, as you keep increasing the value of x, which is also used in the end condition.
Here are some suggestions:
Just store the number of students when you read it and remove the x variable:
int students = in.nextInt();
int grades[] = new int[students ];
String[] names = new String[students ];
Then read in this number of sudents:
for(i = 0; i < students; i++) {
To find the top two students you'd use the following logic (assumes 2 or more students)
if grade[0] >= grade[1]
max1 = 0
max2 = 1
else
max1 = 1
max2 = 0
for i from 2 to students-1
if grade[i] >= grade[max1]
max2 = max1
max1 = i
else if grade[i] > grade[max2]
max2 = i
The top two students are then at positions max1 and max2 in the names and grades array.
Probably overkill, but maybe someone will find it useful.
I store all the students in a TreeSet. I assume that each student has a unique name. I use a special Comparator to sort the students in the TreeSet according to their grades. A descending Iterator of the TreeSet will return the students from highest grade to lowest grade, so the first two items returned by this Iterator are the top two students.
import java.util.Comparator;
import java.util.Iterator;
import java.util.Scanner;
import java.util.TreeSet;
/**
* A student name and her grade.
*/
public class StudentGrade {
/** Name of student. */
private String studentName;
/** Grade for this student. */
private int studentGrade;
/**
* Creates and returns instance of this class.
*
* #param name - student name
* #param grade - student grade
*/
public StudentGrade(String name, int grade) {
studentName = name;
studentGrade = grade;
}
/**
* #return Student's name.
*/
public String getStudentName() {
return studentName;
}
/**
* #return Student's rgade.
*/
public int getStudentGrade() {
return studentGrade;
}
/**
* Two instances of this class are equal if they both have the same name.
*/
#Override // java.lang.Object
public boolean equals(Object obj) {
boolean isEqual = false;
if (obj != null) {
Class<?> objClass = obj.getClass();
if (objClass.equals(getClass())) {
StudentGrade other = (StudentGrade) obj;
isEqual = studentName.equals(other.getStudentName());
}
}
return isEqual;
}
#Override // java.lang.Object
public int hashCode() {
return studentName.hashCode();
}
#Override // java.lang.Object
public String toString() {
return String.format("%s [%d]", studentName, studentGrade);
}
/**
* Start here.
*/
public static void main(String[] args) {
// Stores all student grades, sorted by grade in ascending order.
TreeSet<StudentGrade> studentSet = new TreeSet<>(new StudentGradeComparator());
Scanner in = new Scanner(System.in);
System.out.print("Please enter how many students you have: ");
int students = in.nextInt();
int index = students;
int sum = 0;
while (index > 0) {
// make sure we consume the newline character since 'nextInt()' does not
in.nextLine();
System.out.print("Enter student name: ");
String name = in.nextLine();
System.out.printf("Enter grade for %s: ", name);
int grade = in.nextInt();
sum += grade;
StudentGrade sg = new StudentGrade(name, grade);
studentSet.add(sg);
index--;
}
double average;
if (students > 0) {
average = (double) sum / students;
}
else {
average = 0.0d;
}
System.out.println("The average is " + average);
String verb = students == 1 ? "is" : "are";
String plural = students == 1 ? "" : "s";
System.out.printf("There %s %d student%s.%n", verb, students, plural);
if (students > 1) {
Iterator<StudentGrade> iter = studentSet.descendingIterator();
System.out.printf("The top two students are: %s, %s%n", iter.next(), iter.next());
}
}
}
/**
* Compares 'StudentGrade' instances according to their grades.
*/
class StudentGradeComparator implements Comparator<StudentGrade> {
/**
* Returns a positive number if 'sg1' grade is larger than that of 'sg2'.
* Returns a negative number if 'sg1' grade is less than that of 'sg2'.
* Returns zero if 'sg1' grade is equal to 'sg2' grade.
*/
#Override
public int compare(StudentGrade sg1, StudentGrade sg2) {
if (sg1 == null) {
if (sg2 != null) {
return -1;
}
else {
return 0;
}
}
else {
if (sg2 == null) {
return 1;
}
else {
return sg1.getStudentGrade() - sg2.getStudentGrade();
}
}
}
}
Here is a sample run:
Please enter how many students you have: 3
Enter student name: George
Enter grade for George: 70
Enter student name: Diego
Enter grade for Diego: 90
Enter student name: Edson
Enter grade for Edson: 65
The average is 75.0
There are 3 students.
The top two students are: Diego [90], George [70]

scanner nextLine() skip and failed read

Not actually sure what's wrong, just that at line 81 my scan object is skipped and then the program continues with no clear attempt to read anything, thoughts on what's wrong? btw working in eclipse
import java.util.*;
public class Hospital
{
//--- Instance Variables
private Patient patient;
private Scanner scan;
private double totalPrivateRoomCharges;
private double totalSemiPrivateRoomCharges;
private double totalWardRoomCharges;
private double totalTelephoneCharges;
private double totalTelevisionCharges;
private double totalReceipts;
//--- Constructors
public Hospital()
{
scan = new Scanner(System.in);
totalPrivateRoomCharges = 0;
totalSemiPrivateRoomCharges = 0;
totalWardRoomCharges = 0;
totalTelephoneCharges = 0;
totalTelevisionCharges = 0;
totalReceipts = 0;
mainMenu();
}
//--- Methods
public void mainMenu()
{
int ans = 0;
do
{
System.out.println(" Community Hospital");
System.out.println();
System.out.println(" Main Menu");
System.out.println();
System.out.println("1) Enter Patient Billing Information");
System.out.println("2) Print Daily Summary Report");
System.out.println("3) Exit");
System.out.println();
System.out.print("Selection: ");
ans = scan.nextInt();
System.out.println();
if(ans == 1)
{
patientBillingInfo();
}
if(ans == 2)
{
printSummaryReport();
}
}
while(ans != 3);
}
// precondition: none
// postcondition: displays a menu that allows the user to enter a patient's
// billing info which includes the patient's name, the number of days the
// patient stayed in the hospital, and the type of room
// (private, semi-private, ward).
// Once the patient info is retrieved a patient object is created and a
// billing report is generated that includes the patient's name, length
// of stay, and the charges incurred including the bill total.
// The totals that are used to print the hospitals daily summary report
// are updated.
public void patientBillingInfo()
{
String name = "";
int days = 0;
String room = "";
System.out.println(" Community Hospital");
System.out.println();
System.out.println(" Patient Billing Query");
System.out.println();
System.out.println("Enter Patient Name: ");
here the scan object seems to be completely skipped and dose not read at all just moves to the next line and continues.
name = scan.nextLine(); //getting skiped
System.out.println("Enter number of days in Hospital: ");
days = scan.nextInt();
System.out.println("Enter Room type(P, S, W): ");
room = scan.next();
System.out.println();
System.out.println();
if(!((room.equalsIgnoreCase("P")) || (room.equalsIgnoreCase("S")) || (room.equalsIgnoreCase("W"))))
{
System.out.println("Incorect room information");
System.out.println("Please enter P, S, or W for room selection");
System.out.println();
patientBillingInfo();
}
else
{
if(room.equalsIgnoreCase("P"))
totalPrivateRoomCharges += 1*days;
if(room.equalsIgnoreCase("S"))
totalSemiPrivateRoomCharges += 1*days;
if(room.equalsIgnoreCase("W"))
totalWardRoomCharges += 1*days;
totalTelephoneCharges += 1*days;
totalTelevisionCharges += 1*days;
patient = new Patient(name, days,room);
}
System.out.println(" Community Hospital");
System.out.println();
System.out.println(" Patient Billing Statement");
System.out.println();
System.out.println("Patient's name: " + patient.getName());
System.out.println("Number of days in Hospital: " + patient.getDays());
System.out.println();
System.out.println("Room charge $ " + patient.getRoomCharge());
System.out.println("Telephone charge $ " + patient.getTelephoneCharge());
System.out.println("Television charge $ " + patient.getTelevisionCharge());
System.out.println();
System.out.println("Total charge $ " +patient.getTotalCharge());
System.out.println();
System.out.println();
mainMenu();
}
// precondition: none
// postcondition: a summary report is printed that includes the daily total
// room charges for each type of room, the daily total telephone charges,
// and the daily total television charges. The report also includes the
// total receipts for the day.
public void printSummaryReport()
{
double tPRC = 225.0*totalPrivateRoomCharges;
double tSPRC = 165.0*totalSemiPrivateRoomCharges;
double tWRC = 95.0*totalWardRoomCharges;
double tTpC = 1.75*totalTelephoneCharges;
double tTvC = 3.50*totalTelevisionCharges;
double tR = tPRC+tSPRC+tWRC+tTpC+tTvC;
System.out.println(" Community Hospital");
System.out.println();
System.out.println(" Daily Billing Summary");
System.out.println();
System.out.println("Room Charges");
System.out.println(" Private: $" + tPRC);
System.out.println(" Semi-Private: $" + tSPRC);
System.out.println(" Ward: $" + tWRC);
System.out.println("Telephone Charges: $" + tTpC);
System.out.println("Telvision Charges: $" + tTvC);
System.out.println();
System.out.println("Total Receipts: $" + tR);
System.out.println();
}
}
edit: so it just occurred to me that maybe just maybe the rest of the code that this goes with might be useful dunno why I didn't think about this sooner but here's the rest
the class that actually runs
public class Administrator
{
public static void main(String[] args)
{
Hospital hospital = new Hospital();
}
}
and the class that works the patient info
public class Patient
{
//--- Constants
public final double PRIVATE = 225.00;
public final double SEMI = 165.00;
public final double WARD = 95.00;
public final double TELEPHONE = 1.75;
public final double TELEVISION = 3.50;
//--- Instance Variables
private String name;
private String roomType;
private int days;
//--- Constructors
public Patient(String n, int d, String rT)
{
name = n;
days = d;
roomType = rT;
}
//--- Methods
// precondition: none
// postcondition: returns the patient name
public String getName()
{
return name;
}
// precondition: none
// postcondition: returns the length of stay in days
public int getDays()
{
return days;
}
// precondition: none
// postcondition: returns the room type ("P", "S", "W")
public String getRoomType()
{
return roomType;
}
// precondition: none
// postcondition: returns the room charge which is dependant upon
// the room type and the length of stay.
public double getRoomCharge()
{
double charge = 0;
if(getRoomType().equalsIgnoreCase("P"))
charge = 225.00*getDays();
if(getRoomType().equalsIgnoreCase("S"))
charge = 165.00*getDays();
if(getRoomType().equalsIgnoreCase("W"))
charge = 95.00*getDays();
return charge;
}
// precondition: none
// postcondition: returns the telephone charge which is dependant upon
// the length of stay
public double getTelephoneCharge()
{
double charge = 1.75*getDays();
return charge;
}
// precondition: none
// postcondition: returns the television charge which is dependant upon
// the length of stay
public double getTelevisionCharge()
{
double charge = 3.50*getDays();
return charge;
}
// precondition: none
// postcondition: returns the total charge which is the sum
// of the room charge, telephone charge, and television charge.
public double getTotalCharge()
{
double charge = getRoomCharge()*getTelephoneCharge()+getTelevisionCharge();
return charge;
}
}
really don't know why it didn't occur to me sooner to do this but whatever live and lern right
You could simply scan a line and then parse it as the integer for Integer values.
so for reading integers instead of
val=scan.nextInt()
you could use
String strVal = scan.nextLine();
try {
val = Integer.parseInt(strVal);
} catch (NumberFormatException e) {
//maybe try again, or break the code ... or proceed as you wish.
}
this is because the nextInt() does not take the "Enter" key into account, and when you press enter after the nextInt() the int is read into the variable expecting nextInt() and the "Return" Key is accepted by the nextLine() which results in an empty line being read into the variable.
In public void mainMenu() you need to add scan.nextLine(); after ans = scan.nextInt(); in order to clear the rest of the input buffer.
ans = scan.nextInt();
scan.nextLine(); // <----- Add this line here

Calling methods of an object that is already stored in an ArrayList

Everything works so far in my program but I'm having trouble with this section of my code:
else if(input.equals("2")) {
System.out.println("Enter the stock symbol:");
symbol2 = in.next();
System.out.println("Enter the number of shares you wish to sell:");
sellshares = in.nextInt();
String tempsymbol = "";
for(int i=0; i<array1.size(); i++) {
tempsymbol = (array1.get(i)).getSymbol();
if(symbol2.equals(tempsymbol)) {
System.out.println("The dollar cost averaged price per share (LIFO): " + (array1.get(i)).averageCost(sellshares));
System.out.println("The dollar cost averaged price per share (FIFO): " + (array2.get(i)).averageCost(sellshares));
}
}
}
It'll go through the loop but tempsymbol will always = "". Why doesn't array1 return anything?
Here's all my code. Apologies ahead of time if any parts are redundant or messy.
import java.util.*;
public class Whoop {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input = "";
String symbol = "";
String name = "";
int shares = 0;
double price = 0;
String symbol2 = "";
int sellshares = 0;
int rolling = 0;
stack theStack = null;
queue theQ = null;
String loopcheck = "1";
ArrayList<stack> array1 = new ArrayList<stack>();
ArrayList<queue> array2 = new ArrayList<queue>();
while(loopcheck.equals("1")) {
System.out.println("Press 1 to enter a new stock or press 2 to find the LIFO and FIFO dollar cost average for the number of shares sold");
input = in.next();
if(input.equals("1")) {
System.out.println("Enter the stock symbol:");
symbol = in.nextLine();
in.nextLine();
System.out.println("Enter the stock name:");
name = in.nextLine();
System.out.println("Enter the number of shares bought:");
shares = in.nextInt();
System.out.println("Enter the price per share when purchased");
price = in.nextDouble();
theStack = new stack(symbol,name,shares,price);
theQ = new queue(symbol,name,shares,price);
System.out.println("Press 1 to continue entering new shares or press 2 to finish input for " + theStack.getName());
rolling = in.nextInt();
while(rolling == 1) {
System.out.println("Enter the number of shares bought:");
shares = in.nextInt();
System.out.println("Enter the price per share when purchased");
price = in.nextDouble();
theStack.bigPush(shares, price);
theQ.bigAdd(shares, price);
System.out.println("Press 1 to continue entering new shares or press 2 to finish input for " + theStack.getName());
rolling = in.nextInt();
}
array1.add(theStack); //I added the objects after all the values were finalized
array2.add(theQ);
}
else if(input.equals("2")) {
System.out.println("Enter the stock symbol:");
symbol2 = in.next();
System.out.println("Enter the number of shares you wish to sell:");
sellshares = in.nextInt();
String tempsymbol = "";
for(int i=0; i<array1.size(); i++) {
tempsymbol = (array1.get(i)).getSymbol();
if(symbol2.equals(tempsymbol)) {
System.out.println("The dollar cost averaged price per share (LIFO): " + (array1.get(i)).averageCost(sellshares));
System.out.println("The dollar cost averaged price per share (FIFO): " + (array2.get(i)).averageCost(sellshares));
}
}
}
else {
System.out.println("Input invalid ):");
System.exit(0);
}
System.out.println("Press 1 to continue working with your stocks or press anything else to finish up");
loopcheck = in.next();
}
System.out.println("END");
}
}
This is my queue class which works perfectly fine.
import java.util.LinkedList;
public class queue<E> {
private LinkedList<Double> linklist;
private String symbol;
private String name;
private int shares;
private Double price;
public queue(String symbol2, String name2, int shares2, Double price2) {
linklist = new LinkedList<Double>();
shares = shares2;
price = price2;
symbol = symbol2;
name = name2;
bigAdd(shares, price);
}
public String getName() {
return name;
}
public String getSymbol() {
return symbol;
}
public void add(Double e) {
linklist.add(e);
}
public Double take() {
return linklist.poll();
}
public void bigAdd (int shares2, Double price2) {
while(shares2>0) {
linklist.add(price2);
shares2--;
}
}
public double averageCost(int shares2) {
double average = 0;
int sizer = 0;
while(sizer < shares2) {
average = average + linklist.poll();
sizer++;
}
average = average/shares2;
return average;
}
And this is my stack class which also works fine.
import java.util.*;
public class stack {
private ArrayList<Double> stackArray = new ArrayList<Double>();
private int top;
private String symbol;
private String name;
private int shares;
private Double price;
public stack(String symbol2, String name2, int shares2, Double price2) {
symbol = symbol2;
name = name2;
shares=shares2;
price=price2;
top = -1;
bigPush(shares, price);
}
public double averageCost(int shares2) {
double average = 0;
int sizer = shares2;
while(sizer > 0) {
average = average + stackArray.get(top--);
sizer--;
}
average = average/shares2;
return average;
}
public void push(Double value) {
stackArray.add(++top, value);
}
public Double pop() {
return stackArray.get(top--);
}
public String getName() {
return name;
}
public String getSymbol() {
return symbol;
}
public void bigPush(int shares2, Double price2) {
while(shares2>0) {
stackArray.add(++top, price2);
shares2--;
}
}
public static void main(String[] args) {
stack theStack = new stack("Dave", "Franco", 2,10.0);
theStack.bigPush(2,20.0);
System.out.println(theStack.getSymbol());
}
}
Also heres an example of my output:
Press 1 to enter a new stock or press 2 to find the LIFO and FIFO dollar cost average for the number of shares sold
1
Enter the stock symbol:
DAVE
Enter the stock name:
FRANCO
Enter the number of shares bought:
5
Enter the price per share when purchased
5
Press 1 to continue entering new shares or press 2 to finish input for FRANCO
2
Press 1 to continue working with your stocks or press anything else to finish up
1
Press 1 to enter a new stock or press 2 to find the LIFO and FIFO dollar cost average for the number of shares sold
2
Enter the stock symbol:
DAVE
Enter the number of shares you wish to sell:
1
//AND THEN NOTHING HERE WHEN IT SHOULD RETURN AVERAGECOST()
Press 1 to continue working with your stocks or press anything else to finish up
Following your long code,
tt looks like it all boils down to a wrong usage of the Scanner class :
while(loopcheck.equals("1")) {
System.out.println("Press 1 to enter a new stock or press 2 to find the LIFO and FIFO dollar cost average for the number of shares sold");
input = in.next();
if(input.equals("1")) {
System.out.println("Enter the stock symbol:");
symbol = in.nextLine(); // problem here
in.nextLine();
this assigns an empty String to symbol, because it consumes the end of line of the previous in.next().
If you change it to :
while(loopcheck.equals("1")) {
System.out.println("Press 1 to enter a new stock or press 2 to find the LIFO and FIFO dollar cost average for the number of shares sold");
input = in.next();
in.nextLine();
if(input.equals("1")) {
System.out.println("Enter the stock symbol:");
symbol = in.nextLine();
it will work.
Edit :
It looks like you are aware of the need to sometimes call in.nextLine() without using its returned value, but you put in.nextLine() in the wrong place.

java NullPointerException error. No Output [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
So I have a school assignment to do in Java, I have created the program but it does not give me an output. Im still a beginner so plz help me fix the problem. the first half of my code uses joptionpane but i want to display the output in the console. this is my code:
import java.util.Scanner;
import javax.swing.JOptionPane;
public class payroll2
{
public static void main(String args[])
{
new payroll2().SetPayrollDetail();
new payroll2().SetBonus();
new payroll2().SetCommission();
new payroll2().SetNssf();
new payroll2().SetNetSalary();
new payroll2().GetPayroll();
}
Scanner myScanner=new Scanner(System.in);
Double empID;
String empName;
String empDept;
String designation;
Double basicSalary;
Double bonus;
Double commission;
Double nssf;
Double netSalary;
public void SetPayrollDetail()
{
empID = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter ID: ", "ID",JOptionPane.QUESTION_MESSAGE));
empName = JOptionPane.showInputDialog(null, "Enter Name: ", "Name",JOptionPane.QUESTION_MESSAGE);
empDept = JOptionPane.showInputDialog(null, "Enter Department (Marketing or Other): ", "Department",JOptionPane.QUESTION_MESSAGE);
designation = JOptionPane.showInputDialog(null, "Enter Designation (Manager, Executive or Other): ", "Designation",JOptionPane.QUESTION_MESSAGE);
basicSalary = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter Basic Salary: ", "Basic Salary",JOptionPane.QUESTION_MESSAGE));
}
public void SetBonus()
{
if(basicSalary < 1500){
bonus = 0.0;
}
else if(basicSalary>=1500 && basicSalary<3000){
bonus = basicSalary * (12/100);
}
else if(basicSalary>=3000 && basicSalary<5000){
bonus = basicSalary * (15/100);
}
else{
bonus = basicSalary * (25/100);
}
System.out.println(bonus);
}
public void SetCommission()
{
if( empDept.equalsIgnoreCase("other") ){
commission = 0.0;
}
else if( empDept.equalsIgnoreCase("marketing") && designation.equalsIgnoreCase("manager") ){
commission = basicSalary * (30/100);
}
else if( empDept.equalsIgnoreCase("marketing") && designation.equalsIgnoreCase("executive") ){
commission = basicSalary * (15/100);
}
else if( empDept.equalsIgnoreCase("marketing") && designation.equalsIgnoreCase("other") ){
commission = basicSalary * (10/100);
}
else{
commission = 0.0;
}
System.out.println(commission);
}
public void SetNssf()
{
if(basicSalary < 1500){
nssf = basicSalary * (5/100);
}
else if(basicSalary>=1500 && basicSalary<3000){
nssf = basicSalary * (8/100);
}
else if(basicSalary>=3000 && basicSalary<5000){
nssf = basicSalary * (12/100);
}
else if(basicSalary>=5000 && basicSalary<7000){
nssf = basicSalary * (15/100);
}
else if(basicSalary>=7000 && basicSalary<10000){
nssf = basicSalary * (20/100);
}
else{
nssf = basicSalary * (25/100);
}
System.out.println(nssf);
}
public void SetNetSalary()
{
netSalary = ( basicSalary + commission + bonus ) - nssf;
System.out.println(netSalary);
}
public void GetPayroll()
{
System.out.println("Payroll Details \n _____________________");
System.out.println("ID:\t" + empID);
System.out.println("name:\t" + empName);
System.out.println(bonus);
System.out.println(commission);
System.out.println(nssf);
System.out.println(netSalary);
}
}
You have a bunch of values which aren't initialized to anything by default:
Double empID;
String empName;
String empDept;
// etc.
When you create an instance of the object, you call a method to initialize them:
new payroll2().SetPayrollDetail();
But then you don't keep that instance. You immediately create an entirely new instance and try to operate on it:
new payroll2().SetBonus();
This new instance never had its values initialized to anything. So it can't use those values. Instead, you want to keep that original instance so you can operate on that:
payroll2 instance = new payroll2();
instance.SetPayrollDetail();
instance.SetBonus();
// etc.
You are recreating your instance of payroll2 every time you make an operation. Use a single instance.
payroll2 p = new payroll2();
p.SetPayrollDetail();
p.SetBonus();
p.SetCommission();
p.SetNssf();
p.SetNetSalary();
p.GetPayroll();
Moreover, method should begin with a tiny letter, class name with a capital one.

Having trouble with array

I am currently trying to program a array based program. We have to make a employee class then a tester main class that holds a array of five user input employee names, salaries, and performance rating. The performance rating is used to determine a supplied raise amount. I have it basically done, but when i run the program, nothing happens even though java virtual machine is running. I have looked up and down for the error, anyone can point out what i am doing wrong?
Employee Class
public class Employee
{
private String employeeName;
private int salary;
private int performanceRating;
public Employee()
{
employeeName = "";
salary = 0;
performanceRating = 0;
}
public String getEmployeeName()
{
return employeeName;
}
public int getSalary()
{
return salary;
}
public int getPerformanceRating()
{
return performanceRating;
}
}
And this is the tester main class where the error comes in somewhere
import java.util.Scanner;
public class Tester
{
public static void main(String[] args)
{
Employee[] work = new Employee[5];
Scanner scanString = new Scanner(System.in);
Scanner scanInt = new Scanner(System.in);
String employeeName = "";
double salary = 0;
double performanceRating = 0;
String choice = scanString.nextLine();
while(choice.equals("yes"))
{
for(int i = 0; i < 5 ;i++)
{
System.out.println("What is the employee's name?");
employeeName = scanString.nextLine();
System.out.println("Enter Employee's salary");
salary = scanInt.nextInt();
System.out.println("Performance? 1 = excellent, 2 = good, 3 = poor");
performanceRating = scanInt.nextInt();
work[i] = new Employee();
}
for(int j = 0; j < 5; j ++)
if(work[j].getPerformanceRating() == 1)
{
salary = salary * 0.06;
System.out.println("Employee " + employeeName + " salary raised to " + salary);
}
else if(performanceRating == 2)
{
salary = salary * 0.04;
System.out.println("Employee " + employeeName + " salary raised to " + salary);
}
else if(performanceRating == 3)
{
salary = salary * 0.015;
System.out.println("Employee " + employeeName + " salary raised to " + salary);
}
else if(performanceRating < 5)
{
salary = salary;
System.out.println("Rating is off scale. No raise for emplyee " + employeeName);
}
System.out.println("Enter more employees? type 'yes' if you want to go again");
choice = scanString.nextLine();
}
System.out.println("Done");
}
}
The program reads from System.in. If you don't enter anything, nothing will happen.
Not sure why you have 2 Scanners instead of just one.
You have while(choice.equals("yes")) except you never prompt the user to make a choice. The program does do stuff (some of which may not all work properly), but you have to give the program input. What you can do is ask the user a question before the line String choice = scanString.nextLine();.
As a side note, you could use a switch in place of the if and else if's and it might be a little easier to read and understand.

Categories

Resources