I have written the code this expected output:
Sample input :
Enter the passenger name:
Priya
Enter the gender(M or F / m or f):
F
Enter the age:
61
Enter the ticket no:
140
Enter the ticket price:
500.0
Sample Output 1 :
Ticket no:143
Passenger Name:Priya
Price of a ticket : 500.0
Total Amount : 375.0
I have to change the total amount value based on the age and gender for which I have written function.
My code:
Person.java
public class Person {
private String name;
private char gender;
private int age;
public void setName(String name ){
this.name = name;
}
public void setGender(char gender){
this.gender = gender ;
}
public void setAge(int age ){
this.age = age;
}
public String getName(){
return this.name;
}
public char getGender(){
return this.gender;
}
public int getAge(){
return this.age;
}
}
BusTicket.java
public class BusTicket {
private int ticketNo;
private float ticketPrice;
private float totalAmount;
Person person = new Person();
int age = person.getAge();
char g = person.getGender();
public void setTicketNo(int ticketNo){
this.ticketNo = ticketNo;
}
public void setTicketPrice(float ticketPrice){
this.ticketPrice = ticketPrice;
}
public void setTotalAmount(float totalAmount){
this.totalAmount = totalAmount;
}
public void calculateTotal()
{
if(age<16)
{
totalAmount = ticketPrice/2;
setTotalAmount(totalAmount);
}
else if(age>=60)
{
totalAmount = 3*(ticketPrice/4);
setTotalAmount(totalAmount);
}
else if(g == 'f'|| g== 'F')
{
totalAmount = 9*(ticketPrice/10);
setTotalAmount(totalAmount);
}
else{
setTotalAmount(ticketPrice);
}
}
public int getTicketNo(){
return this.ticketNo;
}
public float getTicketPrice(){
return this.ticketPrice;
}
public float getTotalAmount(){
return this.totalAmount;
}
}
TestMain.java
import java.util.Scanner;
public class TestMain {
public static BusTicket getTicketDetails()
{
Scanner sc = new Scanner(System.in);
BusTicket bt = new BusTicket();
System.out.println("Enter the ticket no:");
bt.setTicketNo(sc.nextInt());
System.out.println("Enter the ticket price:");
bt.setTicketPrice(sc.nextFloat());
return bt;
}
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
Person p = new Person();
BusTicket bt;
System.out.println("Enter the passenger name:");
p.setName(sc.nextLine());
System.out.println("Enter the gender(M or F/ m or f):");
p.setGender(sc.next().charAt(0));
System.out.println("Enter the age:");
p.setAge(sc.nextInt());
bt = getTicketDetails();
System.out.println("Ticket no:"+bt.getTicketNo());
System.out.println("Passenger Name:"+p.getName());
System.out.println("Price of a ticket : "+bt.getTicketPrice());
System.out.println("Total Amount : "+bt.getTotalAmount());
}
}
But my TotalAmount value is always coming 0.0, it is not getting updated.
And some test cases are failed please help to resolve them:
Fail 1 -
Incorrect access specifier/modifier for person -Should be a [private]
Fail 2 -
Check whether the signature(Returntype/Argument/AccessSpecifier/MethodName) of the method setPerson is correct
Fail 3-
Check whether the signature(Returntype/Argument/AccessSpecifier/MethodName) of the method getPerson is correct
Please Help
Thanks
You need to call calculateTotal to update totalAmount. Otherwise, it will be always 0.0.
...
System.out.println("Price of a ticket : "+bt.getTicketPrice());
bt.calculateTotal(); // Add this line
System.out.println("Total Amount : "+bt.getTotalAmount());
In your BusTicket class a new Person object is assigned to Person attribute and then you are trying to get age and gender details from that newly created Person object, but at this moment Person's age and gender are not populated yet.
Person person = new Person();
int age = person.getAge();
That's why you are getting 0. What should ideally happen is, you should pass the person object created using the input details to the BusTicket class and populate the BusTicket's person attribute with that person.For now I ll tell just that. :)
Give a try :)
In your BusTicket class, create a getter and setter for the Person object, and set the value from the main method.
Related
Im currently learning java and im trying to create an Employee management program that stores employee records into an array and allow management to manipulate the array and print any employee reports. So I create a menu and ten employee objects which got stored in an array...now what I want to do is allow the user to input employee details through the menu and that information will be stored inside the objects and I want the user to be able to search for an employee by their title and also display only male of female employees.
I first started with my employee class where has my modifers
public class Employee{
int emp_id=0;
String fname="pebbles";
String lname=null;
String dob=null;
String gender=null;
String address=null;
String title=null;
String dateHired=null;
String department=null;
int hoursWorked=0;
double rateOfpay=0.0;
int leaveDays=0;
double carAllowance=0.0;
double monthlyGratuity=0.0;
double taxRate=0.0;
public Employee(){}
public Employee(int emp_id,String fname,String lname,String dob,String gender,String address,String title,String dateHired,String
department,int hoursWorked,double rateOfpay,int leaveDays,double carAllowance,double monthlyGratuity,double taxRate){
this.emp_id=emp_id;
this.fname=fname;
this.lname=lname;
this.dob=dob;
this.gender=gender;
this.address=address;
this.title=title;
this.dateHired=dateHired;
this.department=department;
this.hoursWorked=hoursWorked;
this.rateOfpay=rateOfpay;
this.leaveDays=leaveDays;
this.carAllowance=carAllowance;
this.monthlyGratuity=monthlyGratuity;
this.taxRate=taxRate;
}
public Employee(int emp_id,String fname,String lname){
this.emp_id=emp_id;
this.fname=fname;
this.lname=lname;
}
public void setEmployeeId(int emp_id){
this.emp_id=emp_id;
}
public void setFirstName(String fname){
this.fname=fname;
}
public void setLastName(String lname){
this.lname=lname;
}
public void setDateOfBirth(String dob){
this.dob=dob;
}
public void setGender(String gender){
this.gender=gender;
}
public void setAddress(String address){
this.address=address;
}
public void setTitle(String title){
this.title=title;
}
public void setDateHired(String dateHired){
this.dateHired=dateHired;
}
public void setDepartment(String department){
this.department=department;
}
public void setHoursWorked(int hoursWorked){
this.hoursWorked=hoursWorked;
}
public void setRateOfPay(double rateOfpay){
this.rateOfpay=rateOfpay;
}
public void setLeaveDays(int leaveDays){
this.leaveDays=leaveDays;
}
public void setCarAllowance(double carAllowance){
this.carAllowance=carAllowance;
}
public void setMonthlyGratuity(double monthlyGratuity){
this.monthlyGratuity=monthlyGratuity;
}
public void setTaxRate(double taxRate){
this.taxRate=taxRate;
}
public int getEmployeeId(){
return emp_id;
}
public String getFirstName(){
return fname;
}
public String getLastName(){
return lname;
}
public String getDateOfBirth(){
return dob;
}
public String getGender(){
return gender;
}
public String getAddress(){
return address;
}
public String getTitle(){
return title;
}
public String getDateHired(){
return dateHired;
}
public String getDepartment(){
return department;
}
public int getHoursWorked(){
return hoursWorked;
}
public double getRateOfPay(){
return rateOfpay;
}
public int getLeaveDays(){
return leaveDays;
}
public double getCarAllowance(){
return carAllowance;
}
public double getMonthlyGratuity(){
return monthlyGratuity;
}
public double getTaxRate(){
return taxRate;
}
}
Then created the objects and arrays in the class below
import java.util.Scanner;
public class employeeArray extends Employee{
private static Employee employees[] = new Employee[10];
static Scanner input=null;
String fname="pebbles";
String lname=null;
String dob=null;
String gender=null;
int emp_id=0;
String address=null;
String title=null;
String dateHired=null;
String department=null;
int hoursWorked=0;
double rateOfpay=0.0;
int leaveDays=0;
double carAllowance=0.0;
double monthlyGratuity=0.0;
double taxRate=0.0;
public static Employee e1=new Employee(12345,"Aobakwe","Mothabi","26/07/1990","Male","Private 009 Masunga","CEO",
"06/02/2008","Finance",500,50.0,10,100.0,1500,5.1);
public static Employee e2=new Employee();
public static Employee e3=new Employee();
public static Employee e4=new Employee();
public static Employee e5=new Employee();
public static Employee e6=new Employee();
public static Employee e7=new Employee();
public static Employee e8=new Employee();
public static Employee e9=new Employee();
public static Employee e10=new Employee();
public static void main(String args[]){
input=new Scanner(System.in);
Employee e1=new Employee(12345," ","Mothabi","26/07/1990","Male","Private 009 Masunga","CEO",
"06/02/2008","Finance",500,50.0,10,100.0,1500,5.1);
Employee e2=new Employee();
Employee e3=new Employee();
Employee e4=new Employee();
Employee e5=new Employee();
Employee e6=new Employee();
Employee e7=new Employee();
Employee e8=new Employee();
Employee e9=new Employee();
Employee e10=new Employee();
employees[0]=e1;
employees[1]=e2;
employees[2]=e3;
employees[3]=e4;
employees[4]=e5;
employees[5]=e6;
employees[6]=e7;
employees[7]=e8;
employees[8]=e9;
employees[9]=e10;
//ENTER NAME
System.out.println("Enter name");
String fname=input.next();
e2.setFirstName(fname);
//ENTER LAST NAME
System.out.println("Enter surname");
String lname=input.next();
e2.setLastName(lname);
//ENTER DATE OF BIRTH
System.out.println("Enter date of birth");
String dob=input.next();
e2.setDateOfBirth(dob);
//ENTER GENDER
System.out.println("Enter Gender");
String gender=input.next();
e2.setGender(gender);
//ENTER EMPLOYEE ID
System.out.println("Enter Employee Id");
int emp_id=input.nextInt();
e2.setEmployeeId(emp_id);
//ENTER ADDRESS
System.out.println("Enter Address");
String address=input.next();
e2.setAddress(address);
//ENTER TITLE
System.out.println("Enter Employee Title");
String title=input.next();
e2.setTitle(title);
//ENTER DATE HIRED
System.out.println("Enter Date Hired");
String dateHired=input.next();
e2.setDateHired(dateHired);
//ENTER DEPARTMENT
System.out.println("Enter Department");
String department=input.next();
e2.setDepartment(department);
//ENTER HOURS WORKED
System.out.println("Enter Hours Worked");
int hoursWorked=input.nextInt();
e2.setHoursWorked(hoursWorked);
//ENTER RATE OF PAY
System.out.println("Enter Rate Of Pay");
double rateOfpay=input.nextDouble();
e2.setRateOfPay(rateOfpay);
//ENTER LEAVE DAYS
System.out.println("Enter Leave Days");
int leaveDays=input.nextInt();
e2.setLeaveDays(leaveDays);
//ENTER CAR ALLOWANCE
System.out.println("Enter Car Allowance");
double carAllowance=input.nextDouble();
e2.setCarAllowance(carAllowance);
//ENTER MONTHLY GRATUITY
System.out.println("Enter Monthly Gratuity");
double monthlyGratuity=input.nextDouble();
e2.setMonthlyGratuity(monthlyGratuity);
//ENTER TAX RATE
System.out.println("Enter Tax Rate");
double taxRate=input.nextDouble();
e2.setTaxRate(taxRate);
//DISPLAY RESULTS
System.out.println(e2.getFirstName());
System.out.println(e2.getLastName());
System.out.println(e2.getDateOfBirth());
System.out.println(e2.getGender());
System.out.println(e2.getEmployeeId());
System.out.println(e2.getAddress());
System.out.println(e2.getTitle());
System.out.println(e2.getDateHired());
System.out.println(e2.getDepartment());
System.out.println(e2.getHoursWorked());
System.out.println(e2.getRateOfPay());
System.out.println(e2.getLeaveDays());
System.out.println(e2.getCarAllowance());
System.out.println(e2.getMonthlyGratuity());
System.out.println(e2.getTaxRate());*/
}
static void mainMenu(){
System.out.println(
"Select an option\n"+
"1)Add Employee Records\n"+
"2) display only male of female employees\n"+
"3) display all employees and their gross salaries\n"+
"4) search for an employee and display salary calculated.\n");
}
}
and lastly here is my tester class which displays the menu and allows the user to select an option
import java.util.Scanner;
public class empTester extends employeeArray{
static Scanner input=null;
public static void main(String args[]){
input=new Scanner(System.in);
mainMenu();
int choice=input.nextInt();
if(choice==1){
menuAdd();
int option=input.nextInt();
if(option==1){EmployeeCreation();}
else if(option==2){System.out.println("It works number 2");}
else if(option==3){mainMenu();}
}
else if(choice==2){
menuDisplay();
int option=input.nextInt();
if(option==1){System.out.println("It works number 1");}
else if(option==2){System.out.println("It works number 2");}
else if(option==3){System.out.println("It works number 3");}
else if(option==4){System.out.println("It works number 4");}
else if(option==5){mainMenu();}
}
else if(choice==3){
menuSearch();
int option=input.nextInt();
if(option==1){System.out.println("It works number 1");}
else if(option==2){System.out.println("It works number 2");}
else if(option==3){mainMenu();}
}
else if(choice==4){
System.out.println("This is the About Section");
}
else if(choice==5){
System.out.println("Ending Program");
System.exit(0);
}
}
}
Yeah so I managed to find a way to enable the user to add an employee record and display details added. Im having trouble creating methods for other functions stated in the menu without having to create new objects.
I think you need a static list.
public static List<Employee> employees = new ArrayList<>();`
public void addEmployee() {
Employee employee = new Employee();
input=new Scanner(System.in);
String fname=input.next();
employee.setFirstName(fname);
.
.
. and others setters...
eployees.add(employee);
}
And read about toString() method to display object details.
toString(), ArrayList, static variable
Here are a few suggestions. The Employee class seems ok. Note that you do not need to supply default values for variables if they are the same as the type's default value. Ex:
String lname=null;
int hoursWorked=0;
double rateOfpay=0.0;
Is the same as
String lname;
int hoursWorked;
double rateOfpay;
You might consider adding a function to the class to read data from a Scanner:
class Employee {
....
boolean readFromIn(Scanner input)
{
//ENTER NAME
System.out.println("Enter name");
fname = input.next();
//ENTER LAST NAME
System.out.println("Enter surname");
lname = input.next();
etc....
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(lname);
....fill in rest
return sb.toString();
}
....
}
The entire employeeArray class seems necessary. But if you want that, there's no need for the temporary variables e1, e2, etc. You have the array, you can add directly to it. A loop helps here:
public class EmployeeArray /* extends Employee - does not extend Employee */
{
private static Employee employees[] = new Employee[10]; // why static?
public static void createEmployees()
{
Scanner in = new Scanner(System.in);
for (int i = 0; i < employees.length; i++) {
employees[i] = new Employee();
employees[i].readFromIn(in);
}
}
public static Employee getEmployee(int index)
{
if (index < 0 || index >= employees.length) {
throw new ArrayIndexOutOfBoundsException();
}
return employees[i];
}
}
I'm working on a little project, but I'm having trouble. It has to do with creating classes, constructors, etc. For the class, all data fields have to be private. I must also have two constructors, one default and one parameterized. Here's the class:
public class PetInfo {
private String petName = "na";
private boolean petType = true;
private String petBreed = "na";
private double petAge = 0;
private double petWeight = 0;
private String ownerName = "na";
public PetInfo(){}
public PetInfo(String name, boolean type, String breed, double age, double weight, String owner){
this.petName = name;
this.petType = type;
this.petBreed = breed;
this.petAge = age;
this.petWeight = weight;
this.ownerName = owner;
}
public String getName (){
return petName;
}
public void setName(String name){
petName = name;
}
public boolean getType(){
return petType;
}
public void setType(boolean type){
petType = type;
}
public String getBreed(){
return petBreed;
}
public void setBreed(String breed){
petBreed = breed;
}
public double getAge(){
return petAge;
}
public void setAge(double age){
petAge = age;
}
public double getWeight(){
return petWeight;
}
public void setWeight(double weight){
petWeight = weight;
}
public String getOwner(){
return ownerName;
}
public void setOwner(String owner){
ownerName = owner;
}
}
Here is what I have in my main function:
import java.util.Scanner;
public class Pp1_C00019540 {
public static void main(String[] args) {
PetInfo[] info = new PetInfo[5];
collectInfo(info);
}
public static void collectInfo(PetInfo[] info){
Scanner input = new Scanner(System.in);
for(int i = 0; i < info.length;i++){
System.out.print("Enter pet name: ");
}
}
}
So it prints "Enter pet name: ", but it won't let me input a name. I tried to do:
info[i] = new PetInfo(input.nextLine());
But it tells me "constructor PetInfo.PetInfo(String, boolean, String, double,double, String) is not applicable. Actual and formal arguments differ in length." Is there something wrong with my class that I'm not catching? I tested it and it seemed to work correctly.
And I'm not looking for a definite answer, I could more than likely figure it out myself. I'm just not sure what's going on, especially when it seemed to me like this would work when I passed the constructor the correct parameters.
Basically, your code is trying to call the PetInfo constructor that takes a single string as input. But based on the code you have, no such constructor exists. You just have the large multi-parameter constructor for PetInfo. You need to call the scanner for input several times before you call the constructor. See the code below:
private static void collectInfo(PetInfo[] info) {
Scanner input = new Scanner(System.in);
try {
for (int i = 0; i < info.length; i++) {
System.out.print("Enter pet name: ");
String petName = input.nextLine();
System.out.print("Enter pet type: ");
boolean petType = input.nextBoolean();
input.nextLine();
System.out.print("Enter pet breed: ");
String petBreed = input.nextLine();
System.out.print("Enter pet age: ");
double petAge = input.nextDouble();
input.nextLine();
System.out.print("Enter pet weight: ");
double petWeight = input.nextDouble();
input.nextLine();
System.out.print("Enter pet owner: ");
String petOwner = input.nextLine();
info[i] = new PetInfo(petName, petType, petBreed, petAge, petWeight, petOwner);
}
}
finally {
input.close();
}
}
Hopefully the code above gives you a good illustration of what I'm talking about. Also, don't forget to call input.nextLine() after calls to nextBoolean() and nextDouble(). Lastly, don't forget to close your input scanner to avoid a resource leak.
Hope that helps.
Well it's simple, when you input using scanner. It takes input in a string, since there is no such constructor which takes string as a parameter it is giving you an error.
You need to take the input from scanner in respective datatypes, store them in variables and then call the constructor. I think what you are trying to do is to call the constructor while taking comma separated input from the scanner, that's not possible.
I have been trying to create a small program that prompts the user for input that takes an employee name and salary adds it to an arrayList, then displays options on the screen(e.g 0: quit, 1: add, 2: display), reads the input then proceeds based on the input.Displaying would just be(e.g Last Name: Smith Salary: £14000. Just need some help to point me in the right direction. I currently have 3 classes Employee, Employee List and Employee Test.
This class prompts the user input.
import java.util.Scanner;
public class Employee {
private String Last_Name;
private int Salary;
public Employee(){
Scanner inputValues = new Scanner(System.in);
System.out.print("Enter employee last name: ");
Last_Name = inputValues.next();
System.out.print("Enter Employee Salary: " + "£");
Salary = inputValues.nextInt();
}
public void Display(){
System.out.printf("Name: " + Last_Name + " " + "Salary: " + Salary);
System.out.println("\n");
}
}
This class is supposed to be adding the employees to an arraylist but im not sure if im doing it correctly.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class EmployeeList extends Employee{
private List <Employee> employee = new ArrayList<Employee>();
public EmployeeList(Employee person) {
employee.add(person);
}
public void DisplayEmployees(){
System.out.println("Employee:" + employee.size());
displayList(employee);
}
public static void displayList(List employee) {
}
}
This is where the main method is
import java.util.Scanner;
public class EmployeeTest {
public static void main(String[] args) {
Employee employee = new Employee();
employee.Display();
EmployeeList empList = new EmployeeList(employee);
empList.DisplayEmployees();
Scanner scanner = new Scanner(System.in);
System.out.println("0: quit, 1: add, 2: display");
String employees = scanner.next();
/* if (employees.equals("1")){
//not sure how to go back to displaying the user prompts
break;
} */
}
}
Few tips I can think of:
EmployeeList should not extend Employee. The main rule of OOP is that class A extends class B if B is a A. This is clearly not the case here - employeeList is not an employee, it's a list of employees (In my mind you don't need a class for this, just List<Employee>)
I'd separate the logic from the data. meaning - Employee class should only hold the employee's data, not deal with scanning and getting the input from the user. the constructor should be simple in my mind, something like:
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
The logic of getting the data should be outside of this class, either in an EmployeeHandler or in the main itself. Since you put it inside the employee, you are having troubles continuing when some of the logic is in the employee and some in the main.
the high-level code should be something like (I'll leave the details to you):
show the menu options to the user
if he wants to add user, get input for both variables, create the employee object and add it to the list
if he wants to display, go over the list and print (the printing can be done overriding toString in Employee class)
if he wants to quit, finish
continue this loop until he wants to quit
public class Employee {
private String Last_Name;
private int Salary;
public Employee(){
public String getLName(){
return Last_Name;
}
public void setLName(){
this.Last_Name = Last_Name;
}
public int getSalary(){
return salary;
}
public void setSalary(){
this.salary = salary;
}
}
}
then in your main method you can create the employee object.
public static void main(String[] args){
Employee employee = new Employee();
Scanner scanner = new Scanner(System.in);
employee.setLName = scanner.next();
employee.setSalary = scanner.nextInt();
}
If i were you I would just make an arraylist to hold all employees. I would prompt the input option for x amount of times and add to the end of the arraylist. the arraylist would be created as so
ArrayList<Employee> employeeList = new ArrayList<Employee>();
to add to it use add
employeeList.add(employee);
This should be able to get you started
EDIT:
OOPS, made several mistakes. edit with the following. Note that it is employee.setLastName(value) because the method setLastName is part of the employee class and it must be passed a value because we have defined that in the employee class.
Employee employee = new Employee();
Scanner scanner = new Scanner(System.in);
String tempName = scanner.next();
int tempSalary = scanner.nextInt();
employee.setLastName(tempName);
employee.setSalary(tempSalary);
EDIT 2:
try to print arraylists as follows. didnt test it. let me know how it works.
for (int i = 0; i< employeelist.size(); i++){
Employee temp = values.get(i);
System.out.println("Last Name: " + temp.getLname() + "Salary: " + temp.getSalary());
}
I modified my employee class to look like this:
public class Employee {
public String lastName;
private int salary;
public Employee(){
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
#Override
public String toString(){
return "Employee Last Name: " + lastName + "\n" + "Employee Salary: " + salary;
}
}
I have modified my EmployeeTest class:
This is my EmployeeTest class:
import java.util.ArrayList;
import java.util.Scanner;
public class EmployeeTest {
static ArrayList<Employee> employeeList = new ArrayList<Employee>();
public static void main(String[] args) {
for(int i=0;i<5;i++){
addEmployees(employeeList);
}
System.out.println(employeeList.toArray());
}
public static void addEmployees(ArrayList<Employee> employeeList){
Scanner scanner = new Scanner(System.in);
System.out.println("0: quit, 1: add, 2: display");
String options = scanner.next();
if(options.equals("1")){
System.out.print("Enter employee last name: ");
String lastname = scanner.next();
System.out.print("Enter Employee Salary: " + "£");
int salary = scanner.nextInt();
Employee employee = new Employee();
EmployeeList.add(employee);
}
else if(options.equals("2")){
for (Employee employee : employeeList){
/*System.out.println("Name: " + employee.getLastName() + ", " + "Salary: " + employee.getSalary());*/
System.out.println(employee);
}
}
else{
System.exit(0);
}
}
}
However when i press 2 as my options it doesn't display what is in my arraylist.
I had read that a toString method is used to get those details so i could print them to the screen. And that using this for loop gets each item in the list to display them. Am i missing something here?. Apologies for this dragging on a bit, im just wanting this to work.
i was trying to make a program that asks the user to create a person or a group of persons and assign names and age to them. So I made a constructor "Try" and a method "AskUser".in AskUser() I use a do/while loop where user is asked to input a name, an age and if he likes to create another person. Now how do I take the input data each time the loop runs, and send it to constructor to create new objects with it? And how these new objects will be called?
import java.util.Scanner;
public class Try{
static String name;
static int age;
static Scanner a = new Scanner(System.in);
static Scanner b = new Scanner(System.in);
static Scanner c = new Scanner(System.in);
public Try(String name, int age){
this.name=name;
this.age= age;
System.out.println("this is "+name+", and he is "+age+" old.");
}
public static void AskUSer(){
int x=0;
do {System.out.print("what's the name of the person ?");
name= a.nextLine();
System.out.print("how old is he? ");
age= b.nextInt();
System.out.print("would u like to creat another person ");
String yes = c.nextLine();
if(!(yes.equals("yes"))){x++;}
} while(x==0);
}
public static void main (String[] args){
AskUSer();
System.out.print(age+ " "+ name);
}
}
You can construct the new object in AskUSer and return it as return value. So the code would look like:
public static YourObject AskUSer() {
...
}
aside from how you read from the user ,
it will be appropriate to make a class..
something like :
class Person {
private String name;
private int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
}
and before entering the loop
you could use an ArrayList to hold people
ArrayList<Person> people = new ArrayList<Person>();
and each time you read the inputs .. instantiate a Person object and add it to the ArrayList
something like :
Person pr=new Person(name,age);
people.add(pr);
I am relatively new to java and learning to program, this being my 8th week at uni. I have been fiddling around with my code for the past day and I have been searching for the past hour or two for a similar question that could help answer my problem but have not found one that helps my particular situation, at least not that I could understand.
For an assignment, I have been asked to write a program with 3 classes(an interface, a store and a product class) and I have been going ok until I need to display data on the interface that is held in the product class. At the moment the code will compile fine but when I run the program and try to use the writeOutput() method I get a stack overflow error. Anyway this is what I have so far:
This is the method I am trying to get to work in the interface class:
private void writeOutput()
{
int productChoice;
Scanner console = new Scanner(System.in);
System.out.println("Please choose a product (1),(2),(3)");
productChoice = console.nextInt();
System.out.println("The records of product " +productChoice+ " are:");
System.out.println("Name: "+matesStore.getName());
And this is one of the methods from the store class:
public String getName()
{
return getName();
}
Finally I'll include the getter and setter from the product class just in case:
public void setName(String newName)
{
name = newName;
}
public String getName()
{
return name;
}
Hopefully this is enough information for someone to be able to help me but if it is not, I am happy to upload all three classes in their entirety.
Cheers Cale.
Edit: I have decided to add all three classes to help people who wish to help me (just keep in mind that I am nowhere near finishing and my code is probably riddled with problems) Hopefully it's not too messy for you guys to understand. And sorry for not writing many comments, it's something i need to work on :)
import java.util.*;
public class MatesInterface
{
Store matesStore = new Store();
private void run()
{
showInterface();
chooseOption();
}
private void showInterface()
{
System.out.println("What would you like to do?:");
System.out.println("(1)Input data for the product");
System.out.println("(2)Show data from one product");
System.out.println("(3)Show the replenishment strategy for a product");
System.out.println("(0)Exit the program");
}
private void chooseOption()
{
int option;
boolean flag = false;
Scanner console = new Scanner(System.in);
System.out.print("Please choose an option: ");
option = console.nextInt();
if(option==1)
{
readInput();
}
else if(option==2)
{
writeOutput();
}
else if (option==3)
{
}
else if(option==0)
{
}
else
{
flag = true;
}
while (flag)
{
System.out.println("That is not a valid option.");
System.out.println("Please choose an option: ");
option = console.nextInt();
flag = false;
}
}
private void readInput()
{
Store matesStore = new Store();
String name;
int productChoice, demandRate;
double setupCost, unitCost, inventoryCost, sellingPrice;
Scanner console = new Scanner(System.in);
System.out.println("Please choose a product (1), (2) or (3): ");
productChoice = console.nextInt();
System.out.println("Please enter the product's name: ");
name = console.next();
System.out.println("Please enter the product's demand rate: ");
demandRate = console.nextInt();
System.out.println("Please enter the product's setup cost: ");
setupCost = console.nextDouble();
System.out.println("Please enter the product's unit cost: ");
unitCost = console.nextDouble();
System.out.println("Please enter the product's inventory cost: ");
inventoryCost = console.nextDouble();
System.out.println("Please enter the product's selling price: ");
sellingPrice = console.nextDouble();
matesStore.addData(productChoice, name, demandRate, setupCost, unitCost, inventoryCost, sellingPrice);
chooseOption();
}
private void writeOutput()
{
int productChoice;
Scanner console = new Scanner(System.in);
System.out.println("Please choose a product (1),(2),(3)");
productChoice = console.nextInt();
System.out.println("The records of product " +productChoice+ " are:");
System.out.println("Name: "+matesStore.getName());
}
public static void main (String[] args)
{
MatesInterface intFace = new MatesInterface();
intFace.run();
}
}
public class Store
{
// instance variables - replace the example below with your own
private Product product1, product2, product3;
public Store()
{
product1 = new Product();
product2 = new Product();
product3 = new Product();
}
public void addData(int option, String newName, int newDemand, double newSetup, double newUnit, double newInventory, double newPrice)
{
if (option==1) setData(product1, newName, newDemand, newSetup, newUnit, newInventory, newPrice);
else if (option==2) setData(product2, newName, newDemand, newSetup, newUnit, newInventory, newPrice);
else setData(product3, newName, newDemand, newSetup, newUnit, newInventory, newPrice);
}
private void setData(Product product, String name, int demandRate, double setupCost, double unitCost, double inventoryCost, double sellingPrice)
{
product.setName(name);
product.setDemand(demandRate);
product.setSetup(setupCost);
product.setUnit(unitCost);
product.setInventory(inventoryCost);
product.setPrice(sellingPrice);
}
public String getName()
{
return getName();
}
}
import static java.lang.Math.*;
public class Product
{
private String name;
private int demandRate;
//private final int REPLENISHMENTRATE=0;
private double setupCost;
private double unitCost;
private double inventoryCost;
private double sellingPrice;
//Constructors for the class Product
public Product()
{
name = "No name yet.";
demandRate = 0;
unitCost = 0;
setupCost = 0;
inventoryCost = 0;
sellingPrice = 0;
}
public Product(String newName, int newDemand, double newSetup, double newUnit, double newInventory, double newPrice)
{
name = newName;
demandRate = newDemand;
unitCost = newUnit;
setupCost = newSetup;
inventoryCost = newInventory;
sellingPrice = newPrice;
}
// Accessor and mutator methods to access and modify data on a Product object
public void setName(String newName)
{
name = newName;
}
public String getName()
{
return name;
}
public void setDemand(int newDemand)
{
demandRate = newDemand;
}
public int getDemand()
{
return demandRate;
}
public void setUnit(double newUnit)
{
unitCost = newUnit;
}
public double getUnit()
{
return unitCost;
}
public void setSetup(double newSetup)
{
setupCost = newSetup;
}
public double getSetup()
{
return setupCost;
}
public void setInventory(double newInventory)
{
inventoryCost = newInventory;
}
public double getInventory()
{
return inventoryCost;
}
public void setPrice(double newPrice)
{
sellingPrice = newPrice;
}
public double getPrice()
{
return sellingPrice;
}
}
The method from the store class is recursivelly calling itself with no terminating clause, this is leading to StackOverflowError :
public String getName()
{
return getName(); // calls itself
}
Instead return the value of name variable if it exists in Store class, or whatever variable you want to be returned as a name:
public String getName()
{
// determine the product name you want
return myProduct.getName();
}