java print statements clashing when user enters values - java

Im solving a question on java and im having some problems, im a beginner so plse help , my print statements(name and department) clash with each other when taking values from the user.
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 netSal;
double bonus;
double commission;
double nssf;
public void SetPayrollDetail()
{
System.out.println("Enter ID: ");
empID = myScanner.nextInt();
System.out.println("Enter Name: ");
empName = myScanner.nextLine();
System.out.println("Enter Department (Marketing or Other): ");
empDept = myScanner.nextLine();
System.out.println("Enter Designation (Manager, Executive or Other):");
designation = myScanner.nextLine();
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()
{
netSal=(basicSalary + commission + bonus) - nssf;
}
public void GetPayroll()
{
System.out.println("\n\n\n\t\tPayroll Details \n____________________________________________________\n");
System.out.println("Employee Id : " + empID + "\t\t Bonus : " + bonus);
System.out.println("Name : " + empName + "\t\t\t\t Commission : " + commission);
System.out.println("Department : " + empDept + "\t\t NSSF : " + nssf);
System.out.println("Designation : " + designation + "\t\t NetSalary : " + netSal);
System.out.println("Basic Salary : " + basicSalary + "\n");
}
}

Edit on:
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();
}
myScanner.next();

Related

how do I pass a user inputted integer through methods?

Essentially i've isolated the issue, the int numpersons begins as 0. I take a user input to make it a particular number which is the array size, when the second method begins it takes the 0 again and then the array has an out of bounds exception. I want to pass it from one method to the next, or make them more successive, idk how to do this
thanks in advance
import java.util.Scanner;
public class BankApp {
Scanner input = new Scanner(System.in);
int numpersons = 0;
private SavingsAccount[] clients = new SavingsAccount[numpersons];
public BankApp() {
while (numpersons < 1) {
System.out.println("How many people are there?");
numpersons = input.nextInt();
if (numpersons < 1 || 2147483647 < numpersons) {
System.out.println("invalid number, please enter again");
}
}
input.nextLine();
}
public void addClients() {
int i = 0;
while (i < numpersons) {
System.out.println("enter account id " + (i + 1));
String AccountID = input.nextLine();
System.out.println("enter account name " + (i + 1));
String AccountName = input.nextLine();
System.out.println("enter account balance " + (i + 1));
Double AccountBalance = input.nextDouble();
clients[i] = new SavingsAccount(AccountID, AccountName, AccountBalance);
input.nextLine();
i++;
}
}
public void displayClients() {
int i = 0;
while (i < numpersons) {
System.out.println("======================================");
System.out.println("Account ID " + (i + 1) + ": " + clients[i].getID());
System.out.println("Account Name " + (i + 1) + ": " + clients[i].getName());
System.out.println("Account Balance " + (i + 1) + ": " + clients[i].getBalance());
System.out.println("======================================");
i++;
}
}
public static void main(String args[]) {
BankApp ba = new BankApp();
ba.addClients();
ba.displayClients();
}
}

Unable to get total amount payable [duplicate]

This question already has answers here:
Unable to get total amount
(2 answers)
Closed 4 years ago.
I have designed a program which will rerun when the user enters "y" when asked if they wish to continue. The problem I am having is once the user enters "n" the program is supposed to display the total amount payable from all ticket options purchased. I have spent a couple of weeks stuck on this problem and am unsure of what to do next. I have only included the bottom part of my code. I have also included a photo to show my problem when the program is run.
here is my code:
package cse1pgx_a2;
import java.util.Scanner;
public class CSE1PGX_A2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int option, quantity, confirm;
float childTotal = 0;
float adultTotal = 0;
float seniorTotal = 0;
float finalTotal = 0;
final double childCost = 18;
final double adultCost = 36;
final double seniorCost = 32.50;
boolean continueLoop = true;
char resume;
Scanner input = new Scanner(System.in);
while (continueLoop) {
System.out.println("\t"+ "##### Welcome to Zoos Victoria #####");
System.out.println("\t" + "\t" + "MAIN MENU" + "\n");
System.out.println("\t" + "Zoo has the following ticketing options" + "\n");
System.out.println("\t" + "1 = Child (4-6 yrs)");
System.out.println("\t" + "2 = Adult (16+ yrs)");
System.out.println("\t" + "3 = Senior (60+ yrs)" + "\n");
System.out.println("Enter your option:" );
option=input.nextInt();
switch (option) {
case 1:
System.out.println("Enter total No of tickets for Child:" );
quantity=input.nextInt();
System.out.println("You are purchasing " + quantity + " child tickets at " + childCost + " each!");
System.out.println("Press 1 to confirm");
confirm=input.nextInt();
break;
case 2:
System.out.println("Enter total No of tickets for Adult:" );
quantity=input.nextInt();
System.out.println("You are purchasing " + quantity + " adult tickets at " + adultCost + " each!");
System.out.println("Press 1 to confirm");
confirm=input.nextInt();
break;
default:
System.out.println("Enter total No of tickets for Senior:" );
quantity=input.nextInt();
System.out.println("You are purchasing " + quantity + " senior tickets at " + seniorCost + " each!");
System.out.println("Press 1 to confirm");
confirm=input.nextInt();
break;
}
if (confirm !=1) {
System.out.println("Incorrect key!");
}
OUTER:
while (confirm == 1) {
switch (option) {
case 1:
childTotal=(int) ((double) quantity*childCost) ;
System.out.println("Total amount for child tickets: $" + childTotal);
break OUTER;
case 2:
adultTotal=(int) ((double) quantity*adultCost) ;
System.out.println("Total amount for adult tickets $" + adultTotal);
break OUTER;
default:
seniorTotal=(int) ((double) quantity*seniorCost);
System.out.println("Total amount for senior tickets $" + seniorTotal);
break OUTER;
}
}
System.out.println("Do you wish to continue? (Y/N) ");
resume = input.next().charAt(0);
if (resume == 'y' || resume == 'Y') {
} else {
continueLoop = false;
switch (option) {
case 1:
finalTotal=(float) ((double) childTotal+adultTotal+seniorTotal) ;
System.out.println("Total amount payable: $ " + finalTotal);
break;
default:
System.out.println("Error");
}
}
}
}
}
I have fixed issues and also updated code for better performance.
package test;
import java.util.Scanner;
public class CSE1PGX_A2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
final float childCost = 18;
final float adultCost = 36;
final float seniorCost = 32.50F;
boolean continueLoop = true;
Scanner input = new Scanner(System.in);
float childTotal = 0;
float adultTotal = 0;
float seniorTotal = 0;
while (continueLoop) {
int option, confirm=0;
System.out.println("\t ##### Welcome to Zoos Victoria #####");
System.out.println("\t \t MAIN MENU \n");
System.out.println("\t Zoo has the following ticketing options \n");
System.out.println("\t 1 = Child (4-6 yrs)");
System.out.println("\t 2 = Adult (16+ yrs)");
System.out.println("\t 3 = Senior (60+ yrs) \n");
System.out.println("Enter your option:");
option = input.nextInt();
switch (option) {
case 1: {
System.out.println("Enter total No of tickets for Child:");
int quantity = input.nextInt();
childTotal = quantity * childCost;
System.out.println("You are purchasing " + quantity + " child tickets at " + childCost + " each!");
System.out.println("Press 1 to confirm");
confirm = input.nextInt();
if (confirm == 1) {
System.out.println("Total amount for child tickets: $" + childTotal);
}
break;
}
case 2: {
System.out.println("Enter total No of tickets for Adult:");
int quantity = input.nextInt();
adultTotal = quantity * adultCost ;
System.out.println("You are purchasing " + quantity + " adult tickets at " + adultCost + " each!");
System.out.println("Press 1 to confirm");
confirm = input.nextInt();
if (confirm == 1) {
System.out.println("Total amount for adult tickets $" + adultTotal);
}
break;
}
case 3: {
System.out.println("Enter total No of tickets for Senior:");
int quantity = input.nextInt();
seniorTotal = quantity * seniorCost ;
System.out.println("You are purchasing " + quantity + " senior tickets at " + seniorCost + " each!");
System.out.println("Press 1 to confirm");
confirm = input.nextInt();
if (confirm == 1) {
System.out.println("Total amount for senior tickets $" + seniorTotal);
}
break;
}
}
if (confirm != 1) {
System.out.println("Incorrect key!");
}
System.out.println("Do you wish to continue? (Y/N) ");
char resume = input.next().charAt(0);
if (resume != 'y' && resume != 'Y') {
continueLoop = false;
System.out.println("Total amount for child tickets: $" + childTotal);
System.out.println("Total amount for senior tickets $" + seniorTotal);
System.out.println("Total amount for adult tickets $" + adultTotal);
float finalTotal = childTotal + adultTotal + seniorTotal ;
System.out.println("Total amount payable: $ " + finalTotal);
}
}
}
}
Try this code. I hope it helps.
public static void main(String[] args) {
int option, quantity, confirm; //minor change
float childTotal = 0;
float adultTotal = 0;
float seniorTotal = 0;
float finalTotal = 0; //minor change
final double childCost = 18;
final double adultCost = 36;
final double seniorCost = 32.50;
boolean continueLoop = true;
char resume;
System.out.println("Do you wish to continue? (Y/N) ");
resume = input.next().charAt(0);
if (resume == 'y' || resume == 'Y') {
}else{
continueLoop = false;
switch (option) {
case 1:
finalTotal+=(double) quantity*childTotal ; //minor change
System.out.println("Total amount payable: $" + childTotal);
break;
case 2:
finalTotal+=(double) quantity*adultTotal ; //minor change
System.out.println("Total amount payable $" + adultTotal);
break;
default:
finalTotal+=(double) quantity*seniorTotal; //minor change
System.out.println("Total amount payable $" + seniorTotal);
break;
}
}
}
}
}
I wished to play and did not fully understand the problem...so i developed from scratch the application. Suryakant was faster so please accept his answer (if it solves your problem). I simply post this here since i worked on it :-)
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean continueLoop = true;
Map<TicketType, Integer> purchases=new HashMap<>();
do {
TicketType type = printMenu(scan);
System.out.println("Enter number of tickets for " + type.label);
int quantity = scan.nextInt();
System.out.println("You are purchasing "+quantity + " "+ type.label+ " ticket at "+type.cost+" each. " +
"Press 1 to confirm?");
int confirm= scan.nextInt();
if (confirm!=1) continue;
if (purchases.containsKey(type)){
purchases.put(type,purchases.get(type)+quantity);
System.out.println("You now have " +purchases.get(type) +" "+type.label +" tickets in total");
}else {
purchases.put(type,quantity);
}
System.out.println("You have added " +quantity +" "+type.label +" tickets in your basket.");
System.out.println("Do you wish to continue (Y|N)?");
String resume=scan.next();
if (resume.startsWith("Y") || resume.startsWith("y")){
continueLoop=true;
}else {
continueLoop=false;
}
}while (continueLoop);
System.out.println("Purchases");
long total=0;
for (Map.Entry<TicketType, Integer> ticketTypeIntegerEntry : purchases.entrySet()) {
System.out.println(ticketTypeIntegerEntry.getKey().label+"("+ticketTypeIntegerEntry.getValue()+")");
total+=ticketTypeIntegerEntry.getKey().cost*ticketTypeIntegerEntry.getValue();
}
System.out.println("Total payable ammount: "+total);
}
private static TicketType printMenu(Scanner scan) {
System.out.println("Welcome");
TicketType type;
int k = -1;
do {
for (TicketType ticketType : TicketType.values()) {
System.out.println(ticketType.id + ". for " + ticketType.label);
}
System.out.println("Enter your option");
k = scan.nextInt();
} while ((type=TicketType.valuefromId(k))==null);
return type;
}
private enum TicketType {
CHILD(1, "Child", 18D),
ADULT(2, "Adult", 36D),
SENIOR(3, "Senior", 18.5D);
int id;
String label;
double cost;
private static Map<Integer,TicketType> map=new HashMap<Integer,TicketType>();
static {
for (TicketType ticketType : TicketType.values()) {
map.put(ticketType.id,ticketType);
}
}
TicketType(int id, String label, double cost) {
this.id = id;
this.label = label;
this.cost=cost;
}
public static TicketType valuefromId(int id){
return map.get(id);
}
}
}
improvements are in reading.. i would check first if what i read is character or not..

Java program....new to programming

this is my first question here, so here it goes, I have tried this for ages with no luck, I am new to Java (studying it) and I have an assignment and I cant get this to work (only the first part works)...thanks in advanced for any help you can give me! :)
**Write a program to read in a non-specified number of Employee Salaries from the user. After each Employee Salary is entered the program should then calculate the Bonus for each employee. The bonus is to be calculated as a percentage of the Salary, according to the table shown below:
Salary Bonus Rate
Less than €10,000 5%
Between €10,000 and less than €20,000 10%
Between €20,000 and less than €30,000 15%
€30,000 or more 20%
The Program should output the Bonus Rate, Bonus Amount, and Total Salary for each Employee after the salary is entered.
When the user has entered the details for all employees, the program should then output the following:
Overall Total Bonuses paid
Overall Total Salaries paid (including bonuses)
Average Bonus
Your program should let the user indicate that they have finished entering results.
Add extra checks to your program so that negative figures are rejected by the program along with a suitable error message.
Test your program thoroughly, so that it works under all possible conditions.
Input/Output from the program should be attractively displayed on the screen.
import java.util.Scanner;
class Salary
{
public static void main (String args [])
{
Scanner myInput = new Scanner (System.in);
double salary =0, bonusRate =0, bonusAmount=0, salaryTotal=0, totalBonus=0, averageBonus=0, totalSalaries=0;
int salaryCounter=0;
char response;
do
{
System.out.println("Press a to enter a salary or press 'q' to quit");
response=myInput.next().charAt(0);
switch(response)
{
case 'a':
do
{
System.out.println("Enter employee salary or press q to quit");
salary = myInput.nextDouble();
if (salary <=0)
{
System.out.println("Invalid entry please enter Salary again ");
}
else if (salary >0 && salary <=10000)
{
System.out.println("*************************************************************");
System.out.println("The bonus rate is 5%");
bonusRate = salary * .05;
System.out.println("The bonus is " + bonusRate);
salaryTotal= salary + bonusRate;
System.out.println("The Total salary " + salaryTotal);
salaryCounter=salaryCounter+1;
System.out.println("*************************************************************");
}
else if (salary >10000 && salary <=20000)
{
System.out.println("*************************************************************");
System.out.println("The bonus rate is 10%");
bonusRate = salary * .10;
System.out.println("The bonus is " + bonusRate);
salaryTotal= salary + bonusRate;
System.out.println("The Total salary " + salaryTotal);
salaryCounter=salaryCounter+1;
System.out.println("*************************************************************");
}
else if (salary >20000 && salary <=30000)
{
System.out.println("*************************************************************");
System.out.println("The bonus rate is 15%");
bonusRate = salary * .15;
System.out.println("The bonus is " + bonusRate);
salaryTotal= salary + bonusRate;
System.out.println("The Total salary " + salaryTotal);
salaryCounter=salaryCounter+1;
System.out.println("*************************************************************");
}
else if (salary >30000)
{
System.out.println("*************************************************************");
System.out.println("The bonus rate is 20%");
bonusRate = salary * .20;
System.out.println("The bonus is " + bonusRate);
salaryTotal= salary + bonusRate;
System.out.println("The Total salary " + salaryTotal);
salaryCounter=salaryCounter+1;
System.out.println("*************************************************************");
}
//else
//{ //do i need to get rid of this?
// System.out.println("");
//}
}while(salary <=0);{
break;
}case 'q':
salaryCounter = salaryCounter+1;
bonusAmount= salary*bonusRate;
salaryTotal=salary+bonusAmount;
totalBonus=totalBonus+bonusAmount;
totalSalaries=totalSalaries+salaryTotal;
averageBonus=totalBonus*salaryCounter;
System.out.printf("The Total Salaries paid including Bonus is %.2f " , totalSalaries);
System.out.println("Euro");
System.out.printf("The Total of Bonuses paid is %.2f ", totalBonus);
System.out.println("Euro");
System.out.printf("The Total of Average Bonuses paid is %.2f ", averageBonus);
System.out.println("Euro");
break;
}//end do
//end switch
}while (response != 'q');{
//do while loop to repeat until 'q' is entered.
} //end do while loop
}//end main
}//end class
You can create two different files for your requirements: one pojo class containing the attributes of the employee and second main app where the user interacts with the program.
Salary.java
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
public class Salary {
private static int count = 0;
private int empId;
private double salary;
private int bonusRate;
private double bonusAmount;
private double totalSalary;
//Getters and Setters
public int getEmpId() {
return empId;
}
public double getTotalSalary() {
return totalSalary;
}
public void setTotalSalary(double totalSalary) {
this.totalSalary = totalSalary;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getBonusRate() {
return bonusRate;
}
public void setBonusRate(int bonusRate) {
this.bonusRate = bonusRate;
}
public double getBonusAmount() {
return bonusAmount;
}
public void setBonusAmount(double bonusAmount) {
this.bonusAmount = bonusAmount;
}
//Constructors
public Salary(int empId, double salary, int bonusRate, double bonusAmount,
double totalSalary) {
super();
this.empId = empId;
this.salary = salary;
this.bonusRate = bonusRate;
this.bonusAmount = bonusAmount;
this.totalSalary = totalSalary;
}
public Salary() {
super();
count = count + 1;
this.empId = count;
}
//toString
#Override
public String toString() {
return "Salary [empId=" + empId + ", salary=" + salary + ", bonusRate="
+ bonusRate + ", bonusAmount=" + bonusAmount + ", totalSalary="
+ totalSalary + "]";
}
//calculation function
public void calculateBonus(){
double bonus;
if(this.getSalary()<10000){
this.setBonusRate(5);
bonus = this.getSalary() + 0.05*(this.getSalary());
}else if(this.getSalary()<20000){
this.setBonusRate(10);
bonus = this.getSalary() + 0.10*(this.getSalary());
}else if(this.getSalary()<30000){
this.setBonusRate(15);
bonus = this.getSalary() + 0.15*(this.getSalary());
}else{
this.setBonusRate(20);
bonus = this.getSalary() + 0.20*(this.getSalary());
}
this.setBonusAmount(bonus);
this.setTotalSalary(this.getSalary() + bonus);
}
}
MainApp.java
import java.util.ArrayList;
import java.util.Scanner;
public class MainApp {
public static void main(String[] args) {
ArrayList<Salary> salaries = new ArrayList<Salary>();
Scanner sc = new Scanner(System.in);
String op = "y";
do {
Salary salary = new Salary();
System.out.println("Please Enter Salary for User "
+ salary.getEmpId() + " :");
salary.setSalary(sc.nextDouble());
salary.calculateBonus();
System.out.println(salary);
salaries.add(salary);
System.out.println("Do you want to enter more salaries: ");
op = sc.next();
} while (op.equals("y"));
double totalSalaries = 0;
double totalBonus = 0;
double averageBonus = 0;
int numberOfSalaries = 0;
for (Salary salary : salaries) {
System.out.println("Empid: " + salary.getEmpId() + " Salary: "
+ salary.getSalary() + " Bonus Rate: "
+ salary.getBonusRate() + " Bonus Amount: "
+ salary.getBonusAmount() + " Total Salary: "
+ salary.getTotalSalary());
totalSalaries = totalSalaries + salary.getTotalSalary();
totalBonus = totalBonus + salary.getBonusAmount();
numberOfSalaries = numberOfSalaries + 1;
}
averageBonus = totalBonus / numberOfSalaries;
System.out.println("Total Salaries for all employees: " + totalSalaries
+ " Total Bonuses: " + totalBonus
+ " Average Bonuses for all employees: " + averageBonus);
}
}
The code shall suffice your requirements.

i have to make a project for my Programming course.This is my code

public class Project1{
public static void main(String[] args)
int noOfPhotocopy;
float totalprice;
String customer's_name;
customer's_name = JOptionPane.showInputDialog("Enter customer's name: ");
String type;
type = JOptionPane.showInputDialog("Choose type of photocopy: G/C");
if (type==G){
noOfPhotocopy = JOptionPane.showInputDialog("Enter no of photocopy: ");
if (noOfPhotocopy<10){
totalprice = noOfPhotocopy * 0.10;
JOptionPane.showMessageDialog(null, "Total price is RM" +totalprice);
} else if(noOfPhotocopy>=10) {
totalprice = noOfPhotocopy * 0.05;
JOptionPane.showMessageDialog(null, "Total price is RM" +totalprice);
}
else if (type==C){
noOfPhotocopy = JOptionPane.showInputDialog("Enter no of photocopy: ");
if (noOfPhotocopy<10){
totalprice = noOfPhotocopy * 0.20;
JOptionPane.showMessageDialog(null, "Total price is RM" +totalprice);
} else if(noOfPhotocopy>=10) {
totalprice = noOfPhotocopy * 0.10;
JOptionPane.showMessageDialog(null, "Total price is RM" +totalprice);
}
}
i have to make a project for my Programming course and my project is to help people to calculate total price of photocopying with different type of photocopy.
There are error, I fixed them.
like
if (type==G){// to compare use type.equals("G")
and
String customer = "s_name";// not String customer"s_name;
and
float totalprice; // to double totaleprice
Try this solution it's OK
import javax.swing.JOptionPane;
public class Project1 {
public static void main(String[] args) {
int noOfPhotocopy;
double totalprice;
String customer = "s_name";
customer = JOptionPane.showInputDialog("Enter customer's name: ");
String type = JOptionPane.showInputDialog("Choose type of photocopy: G/C").toUpperCase();
if (type.equals("G")) {
noOfPhotocopy = Integer.parseInt(JOptionPane
.showInputDialog("Enter no of photocopy: "));
if (noOfPhotocopy < 10) {
totalprice = noOfPhotocopy * 0.10;
JOptionPane.showMessageDialog(null, "Total price is RM"
+ totalprice);
} else if (noOfPhotocopy >= 10) {
totalprice = noOfPhotocopy * 0.05;
JOptionPane.showMessageDialog(null, "Total price is RM"
+ totalprice);
}
}
else if (type.equals("C")) {
noOfPhotocopy = Integer.parseInt(JOptionPane
.showInputDialog("Enter no of photocopy: "));
if (noOfPhotocopy < 10) {
totalprice = noOfPhotocopy * 0.20;
JOptionPane.showMessageDialog(null, "Total price is RM"
+ totalprice);
} else if (noOfPhotocopy >= 10) {
totalprice = noOfPhotocopy * 0.10;
JOptionPane.showMessageDialog(null, "Total price is RM"
+ totalprice);
}
}
}
}

Issue using methods and an array

My problem here is displaying the data using another method. I tried both of the methods but there was no output.
I think that objects in the ArrayList are gone when I made them as parameters on both methods or maybe not.
Please kindly help me with this problem of mine. There are still more options to be filled, I also need some help for it.
public class Student {
private String IDNumber;
private String firstName;
private String middleName;
private String lastName;
private String degree;
private int yearLevel;
public Student() {
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;
}
/* #Override
public String toString(){
return ("ID Number: "+this.getIdNumber()+
"\nName: "+ this.getFirstName()+
" "+ this.getMiddleName()+
" "+ this.getLastName()+
"\nDegree and YearLevel: "+ this.getDegree() +
" - " + this.getYearLevel());
} */
}
import java.util.ArrayList;
import java.util.Scanner;
public class test {
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) {
options();
}
else if (choice == 2) {
displayAll(student, studentList);
}
else if (choice == 3) {
displaySpecific(student, studentList);
}
}
public static void options() {
Scanner in = new Scanner(System.in);
ArrayList<Student> studentList = new ArrayList<Student>();
char ans;
String temp;
int total;
do {
System.out.println("TOTAL: ");
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(Student student,
ArrayList<Student> studentList) {
System.out.printf("STUDENT RECORD");
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();
}
}
public static void displaySpecific(Student student,
ArrayList<Student> studentList) {
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();
}
}
}
}
Move
ArrayList <Student> studentList = new ArrayList <Student>();
from options method to class field.
EDIT:
As you can see, now studentList is not a local variable of
public static void options()
but of the class.
Anyway i edited the args of some methods because you don't need to pass students as argument since now it's a field of the class.
import java.util.ArrayList;
import java.util.Scanner;
public class test {
static ArrayList<Student> studentList = new ArrayList<Student>();
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) {
options();
}
else if (choice == 2) {
displayAll();
}
else if (choice == 3) {
displaySpecific(student);// here you should ask to the user what studend he want to show - here it continues to give you error
}
}
public static void options() {
Scanner in = new Scanner(System.in);
char ans;
String temp;
int total;
do {
System.out.println("TOTAL: ");
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() {
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();
}
}
public static void displaySpecific(Student student) {
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();
}
}
}
}

Categories