So my problem is that when im trying to get a result for my Person manager app and for some reason after a bunch of trial and error i get a result like this
run:
Welcome to the Person Manager
Create customer or employee? (c/e): c
First name: Steve Last name: Trevor Customer number: M10963
You entered a new pkg8.pkg2.person.manager.Customer: Name: Steve
Trevor CustomerNumber: M10963
Continue? (y/n):
now everything is alright up until I get "You entered a new pkg8.pkg2.person.manager.Customer:"
The pkg8.pkg2.person.manager. shouldn't be there.
here is my code
PersonManager.java
package pkg8.pkg2.person.manager;
/**
*
* #author Zachary
*/
public class PersonManager {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Welcome to the Person Manager");
System.out.println("");
String choice = "y";
while (choice.equalsIgnoreCase("y")){
String type = Console.getString("Create customer or employee? (c/e): " , "c", "e");
System.out.println("");
String firstName = Console.getString("First name: ");
String lastName = Console.getString("Last name: ");
Person person;
if(type.equalsIgnoreCase("c")){
String customerNumber = Console.getString("Customer number: ");
person = new Customer(firstName, lastName, customerNumber);
}else{
String ssn = Console.getString("SSN: ");
person = new Employee(firstName, lastName, ssn);
}
Class c = person.getClass();
System.out.println("");
System.out.println("You entered a new " + c.getName() + ":");
System.out.println(person.toString());
System.out.println("");
System.out.println("");
choice = Console.getString("Continue? (y/n): ", "y", "n");
System.out.println();
}
}
}
Person.java
package pkg8.pkg2.person.manager;
/**
*
* #author Zachary
*/
public class Person {
private String firstName;
private String lastName;
public Person(String first, String last){
firstName = first;
lastName = last;
}
public String getFirstName(){
return firstName;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public String getLastName(){
return lastName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
#Override
public String toString(){
return "Name: " + firstName + " " + lastName;
}
}
Customer.java
package pkg8.pkg2.person.manager;
/**
*
* #author Zachary
*/
public class Customer extends Person {
private String customerNumber;
public Customer(String first, String last, String number) {
super(first, last);
this.customerNumber = number;
}
public void setCustomerNumber(String number){
this.customerNumber = number;
}
public String getCustomerNumber(){
return customerNumber;
}
#Override
public String toString(){
String name = super.toString();
return name + "\n" + "CustomerNumber: " + customerNumber;
}
}
Employee.java
package pkg8.pkg2.person.manager;
/**
*
* #author Zachary
*/
public class Employee extends Person {
private String ssn;
public Employee(String first, String last, String ssn){
super(first, last);
this.ssn = ssn;
}
public String getSsn(){
return "xxx-xx-" + ssn.substring(ssn.length() - 4);
}
public void setSsn(String ssn){
this.ssn = ssn;
}
#Override
public String toString() {
String name = super.toString();
return name + "\n" + "SSN: " + getSsn();
}
}
Console.java
package pkg8.pkg2.person.manager;
import java.util.*;
/**
*
* #author Zachary
*/
public class Console {
private static Scanner sc = new Scanner(System.in);
public static String getString(String prompt) {
String s = "";
boolean isValid = false;
while (!isValid) {
System.out.print(prompt);
s = sc.nextLine();
if (s.equals("")) {
System.out.println("Error! This entry is required. Try again.");
} else {
isValid = true;
}
}
return s;
}
public static String getString(String prompt, String s1, String s2) {
String s = "";
boolean isValid = false;
while (!isValid) {
s = getString(prompt);
if (!s.equalsIgnoreCase(s1) && !s.equalsIgnoreCase(s2)) {
System.out.println("Error! Entry must be '" + s1 + "' or '" +
s2 + "'. Try again.");
} else {
isValid = true;
}
}
return s;
}
public static int getInt(String prompt) {
int i = 0;
boolean isValid = false;
while (!isValid) {
System.out.print(prompt);
if (sc.hasNextInt()) {
i = sc.nextInt();
isValid = true;
} else {
System.out.println("Error! Invalid integer. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return i;
}
public static int getInt(String prompt, int min, int max) {
int i = 0;
boolean isValid = false;
while (!isValid) {
i = getInt(prompt);
if (i <= min) {
System.out.println(
"Error! Number must be greater than " + min + ".");
} else if (i >= max) {
System.out.println(
"Error! Number must be less than " + max + ".");
} else {
isValid = true;
}
}
return i;
}
public static double getDouble(String prompt) {
double d = 0;
boolean isValid = false;
while (!isValid) {
System.out.print(prompt);
if (sc.hasNextDouble()) {
d = sc.nextDouble();
isValid = true;
} else {
System.out.println("Error! Invalid number. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return d;
}
public static double getDouble(String prompt, double min, double max) {
double d = 0;
boolean isValid = false;
while (!isValid) {
d = getDouble(prompt);
if (d <= min) {
System.out.println(
"Error! Number must be greater than " + min + ".");
} else if (d >= max) {
System.out.println(
"Error! Number must be less than " + max + ".");
} else {
isValid = true;
}
}
return d;
}
}
I understand that it is a conflicting package I just don't know how to fix it.
Any help would be greatly appreciated.
If you read the documentation, then you'll find that the javadoc of getName() states:
If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by The Java™ Language Specification.
JLS 13.1. The Form of a Binary says:
The class or interface must be named by its binary name, which must meet the following constraints:
The binary name of a top level type (§7.6) is its canonical name (§6.7).
JLS 6.7. Fully Qualified Names and Canonical Names says:
For every primitive type, named package, top level class, and top level interface, the canonical name is the same as the fully qualified name.
The fully qualified name of a top level class or top level interface that is declared in a named package consists of the fully qualified name of the package, followed by ".", followed by the simple name of the class or interface.
In summary: getName() returns the fully qualified name of the class.
If you don't want that, call getSimpleName().
Related
/* Need help. There is an error with client class Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Client.main(Client.java:14)
I emphasized the line.
Driver d1 = new Driver(args[0], Integer.parseInt(args[1]), Integer.parseInt(args[2]), Double.parseDouble(args[3]));
I could not figure out what went wrong. */
/* Driver class */
public class Driver {
private String lastName;
private int age;
private int licenseNo;
private double yr;
private static int id=0;
public Driver() {
this.lastName = "No Name";
this.age = 16;
this.licenseNo = 11111;
this.yr = 0.5;
id++;
}
public Driver(String lastName, int age, int licenseNo, double yr) {
this.lastName = lastName;
this.age = age;
this.licenseNo = licenseNo;
this.yr = yr;
id++;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Driver other = (Driver) obj;
if (lastName.equals(other.lastName) && licenseNo==other.licenseNo)
return true;
else
return false;
}
#Override
public String toString() {
return "The name of the Driver is:" + lastName + ", The age is:" + age + ", The license no is:" + licenseNo + ", Duration of driving:" + yr ;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getLicenseNo() {
return licenseNo;
}
public void setLicenseNo(int licenseNo) {
this.licenseNo = licenseNo;
}
public double getYr() {
return yr;
}
public void setYr(double yr) {
this.yr = yr;
}
}
/* Client class */
import java.util.Scanner;
public class Client {
public static int licenseFee(Driver dr){
double fee=((dr.getAge()*dr.getLicenseNo())/100000)+50;
if(fee>100)
return 100;
else
return (int)fee;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Driver d1 = new Driver(args[0], Integer.parseInt(args[1]), Integer.parseInt(args[2]), Double.parseDouble(args[3]));
System.out.println(d1);
Scanner sc = new Scanner(System.in);
System.out.println("Enter driver's last name:");
String temp1 = sc.next();
System.out.println("Enter age:");
int temp2=sc.nextInt();
System.out.println("Enter license:");
int temp3=sc.nextInt();
System.out.println("Enter Years:");
double temp4=sc.nextDouble();
Driver d2= new Driver(temp1, temp2, temp3,temp4);
System.out.println(d1);
System.out.println("License fee:"+licenseFee(d1));
System.out.println(d2);
System.out.println("License fee:"+licenseFee(d2));
if(d1.equals(d2))
System.out.println("Command line object is equal to keyboard object");
else
System.out.println("Command line object is NOT equal to keyboard object");
}
}
There is nothing wrong with your code, but is very important that you validate all the params that you receive.
Try this in your main method.
public static void main(String[] args) {
if (args == null || args.length <4){
System.out.println("All params are required. lastname, age, licenseNo and year");
}else{
// TODO Auto-generated method stub
Driver d1 = new Driver(args[0], Integer.parseInt(args[1]), Integer.parseInt(args[2]), Double.parseDouble(args[3]));
System.out.println(d1);
Scanner sc = new Scanner(System.in);
System.out.println("Enter driver's last name:");
String temp1 = sc.next();
System.out.println("Enter age:");
int temp2=sc.nextInt();
System.out.println("Enter license:");
int temp3=sc.nextInt();
System.out.println("Enter Years:");
double temp4=sc.nextDouble();
Driver d2= new Driver(temp1, temp2, temp3,temp4);
System.out.println(d1);
System.out.println("License fee:"+licenseFee(d1));
System.out.println(d2);
System.out.println("License fee:"+licenseFee(d2));
if(d1.equals(d2))
System.out.println("Command line object is equal to keyboard object");
else
System.out.println("Command line object is NOT equal to keyboard object");
}
}
C:\Windows\system32>cd..
C:\Windows>cd..
C:>cd Users\qle2\Downloads
C:\Users\qle2\Downloads>java Client ali 32 55555 32.5
The name of the Driver is:ali, The age is:32, The license no is:55555, Duration of driving:32.5
Enter driver's last name:
Alibaba
Enter age:
50
Enter license:
1234567
Enter Years:
12
The name of the Driver is:ali, The age is:32, The license no is:55555, Duration of driving:32.5
License fee:67
The name of the Driver is:Alibaba, The age is:50, The license no is:1234567, Duration of driving:12.0
License fee:100
Command line object is NOT equal to keyboard object
args[0], args[1], etc. are the indexes of command line arguments that you pass to main method before executing your program. It seems that you didn't pass the correct amount of arguments (at least 4) or you forgot to pass all of them. Command line arguments are splitted with white spaces.
You might want to have a look at this link to see how to pass command line arguments through command prompt or in Eclipse or Netbeans:
http://java2career.com/2014/05/how-to-use-command-line-arguments-in.html
Hello everyone I am an amateur in Java and had some specific questions about a program using ArrayLists. The program is made up of several classes, and its purpose is to add, change, remove, and display friends from a Phone Book. I have the add and display methods done, but I'm having trouble with the remove and change method. I saw a similar case on this site, but it did not help me solve my problems. Any help at all would be much appreciated. This is what I have so far:
package bestfriends;
import java.util.Scanner;
import java.util.ArrayList;
public class BFFHelper
{
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
}
public void addABFF()
{
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();
System.out.println("Enter a nick name: ");
String nickName = keyboard.next();
System.out.println("Enter a phone number: ");
String cellPhone = keyboard.next();
BestFriends aBFF = new BestFriends(firstName, lastName, nickName, cellPhone);
myBFFs.add(aBFF);
}
public void changeABFF()
{
System.out.println("I am in changeBFF");
}
public void displayABFF()
{
System.out.println("My Best Friends Phonebook is: ");
System.out.println(myBFFs);
}
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
int i = 0;
boolean found = false;
while (i < myBFFs.size() && !found)
{
if(firstName.equalsIgnoreCase(myBFFs.get(i).getFirstName()) && lastName.equalsIgnoreCase(myBFFs.get(i).getLastName()))
{
found = true;
}
else
i++;
}
}
}
That was my Helper Class, for which I'm having trouble with the removeABFF method, and still need to create a changeABFF method from scratch. Next is my main class:
package bestfriends;
import java.util.Scanner;
public class BFFPhoneBook
{
public static void main(String args[])
{
int menuOption = 0;
Scanner keyboard = new Scanner(System.in);
BFFHelper myHelper = new BFFHelper();
do
{
System.out.println("1. Add a Friend");
System.out.println("2. Change a Friend");
System.out.println("3. Remove a Friend");
System.out.println("4. Display a Friend");
System.out.println("5. Exit");
System.out.print("Enter your selection: ");
menuOption = keyboard.nextInt();
switch (menuOption)
{
case 1:
myHelper.addABFF();
break;
case 2:
myHelper.changeABFF();
break;
case 3:
myHelper.removeABFF();
break;
case 4:
myHelper.displayABFF();
break;
case 5:
break;
default:
System.out.println("Invalid option. Enter 1 - 5");
}
} while (menuOption != 5);
}
}
This is my last class:
package bestfriends;
public class BestFriends {
private static int friendNumber = 0;
private int friendIdNumber;
String firstName;
private String lastName;
private String nickName;
private String cellPhoneNumber;
public BestFriends (String aFirstName, String aLastName, String aNickName, String aCellPhone)
{
firstName = aFirstName;
lastName = aLastName;
nickName = aNickName;
cellPhoneNumber = aCellPhone;
friendIdNumber = ++friendNumber;
// friendIdNumber = friendNumber++;
}
public boolean equals(Object aFriend)
{
if (aFriend instanceof BestFriends )
{
BestFriends myFriend = (BestFriends) aFriend;
if (lastName.equals(myFriend.lastName) && firstName.equals(myFriend.firstName))
return true;
else
return false;
}
else
return false;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getNickName()
{
return nickName;
}
public String getCellPhone()
{
return cellPhoneNumber;
}
public int getFriendId()
{
return friendIdNumber;
}
public String toString()
{
return friendIdNumber + ". " + firstName + " (" + nickName + ") " + lastName + "\n" + cellPhoneNumber + "\n";
}
}
To explore and manipulate a arraylist an iterator is used
the object lacks the Setters
declare variables
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
BestFriends best;
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
best= new BestFriends();
}
Delete
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
String name= keyboard.next().toLowerCase();// entry name to be removed
Iterator<BestFriends> nameIter = myBFFs.iterator(); //manipulate ArrayList
while (nameIter.hasNext()){
best = nameIter.next(); // obtained object list
if (best.getNickName().trim().toLowerCase().equals(name)){ // if equals name
nameIter.remove(best); // remove to arraylist
}
}
}
Update
public void changeABFF()
{
System.out.print("Enter a friend's name to be change: ");
String name= keyboard.next().toLowerCase().trim();//entry name to be update
Iterator<BestFriends> nameIter = myBFFs.iterator();
while (nameIter.hasNext()){
best = nameIter.next();
if (best.getNickName().trim().toLowerCase().equals(name)){// if equals name
best.setNickName("NEW DATE");//update data with new data Setters
....
}
}
}
In your remove method you do not accept any input of the values
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
int i = 0;
boolean found = false;
while (i < myBFFs.size() && !found)
....
As you are using firstNamer and lastName to find the object you needs these values
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();
I have another small class containing the main method that display the
invoice, but the toString method here is only displaying the last item
entered, not the three itemnames,quantities, prices and totalPrice.
I have doubts about addItemLine and toString.
Can someone see what I am missing here?
I was enable to past the lineItem class code.
import java.util.ArrayList;
import java.util.Scanner;
public class Transaction {
private ArrayList<lineItem> lineItems;
private int customerID;
private String customerName;
public Transaction (int customerID, String customerName){
this.customerID= customerID;
this.customerName= customerName;
this.lineItems= new ArrayList<>();
}
public int getcustomerID(){
return customerID;
}
public void setcustomerID(int customerID){
this.customerID = customerID;
}
public String getcustomerName(){
return customerName;
}
public void setcustomerName(String customerName){
this.customerName = customerName;
}
public ArrayList addItemLine(lineItem line){
Scanner mykey=new Scanner(System.in);
for (int i=0; i<2;i++){
String k= line.getItemName();
int m= line.getQuantity();
double d= line.getPrice();
System.out.println("enter item name:");
k = mykey.next();
line.setItemName(k);
System.out.println("enter quantity:");
m= mykey.nextInt();
line.setQuantity(m);
System.out.println("enter unit price:");
d= mykey.nextDouble();
line.setPrice(d);
line.getItemName(); line.getQuantity(); line.getPrice();
lineItems.add(new lineItem(k,m,d));
}
return this.lineItems;
}
public void updateItem(String item, int quant, double pri){
lineItem l= new lineItem(item, quant, pri);
int m=0;
m= l.getQuantity();
m=m+quant;
double tot=0;
}
public double getTotalPrice(){
double totalPrice = 0;
for (int i =0;i<2; i++){
lineItem item = lineItems.get(i);
totalPrice = totalPrice + item.getTotalPrice();
}
return totalPrice;
}
public String getLineItem( String s, int d, double k){
lineItem o= new lineItem(s,d,k);
for (int i =0;i<2; i++){
if (!s.equals(o.getItemName()))
System.out.println("item not found");
else
s= (o.getItemName() + o.getQuantity() + o.getPrice());
}
return s;
}
public String toString(lineItem lin) {
String a="", b="";
a=("Customer ID:" + this.getcustomerID() + "\n" + "Customer Name: " +
this.getcustomerName());
for (int i=0; i<2;i++){
b= ("\n\n" + lin.getItemName() + "\t" + "Qty" + lin.getQuantity() + "
"
+ "#" + lin.getPrice() + " "+ "\t" + "$" + lin.getTotalPrice());
}
return a + b;
}
TransactionTesting:
import java.util.Scanner;
public class TransactionTesting {
public static void main(String args[]) {
String m=""; int g=0; double r=0; int id=0; String name="";
Scanner mykey= new Scanner(System.in);
System.out.println("enter customer name:");
name= mykey.nextLine();
System.out.println("enter customer ID:");
id=mykey.nextInt();
Transaction mytrans= new Transaction(id, name);
lineItem line= new lineItem(m,g,r);
mytrans.addItemLine(line);
System.out.println(mytrans.toString(line));
}
}
Change your toString() method like this:
public String toString() {
String a="", b="";
a=("Customer ID:" + this.getcustomerID() + "\n" + "Customer Name: " +
this.getcustomerName());
for (lineItem item : this.lineItems)
b += ("\n\n" + item.getItemName() + "\t" + "Qty" + item.getQuantity() + " "
+ "#" + item.getPrice() + " "+ "\t" + "$" + item.getPrice());
return a + b;
}
and from your test class call this method as the following:
System.out.println(mytrans.toString());
You don't need any argument in order to print your entire list.
Try to refactor your code a bit. It works, but it can be written better and better ;)
1) The call
System.out.println(mytrans.toString(line));
is printing out the single lineitem that is passed to it. What you probably intended was for Transaction.toString() to iterate over its list Transaction.lineItems and print each item in turn.
In fact Transaction.toString() doesn't need to take in a lineItem argument, the method should merely print out the internals of the class instance.
2) There is a similar confusion in Transacton.addItemLine(). It accepts a lineItem, prompts the user for new values, updates lineItem.. then constructs a new lineItem to store in Transaction.lineItems. It isn't actually causing a bug that I can see but you should get rid of the lineItem argument entirely; addItemLine doesn't need it.
3) Incidentally:
for (int i=0; i<2;i++){ }
loops twice, not three times. I trust you would have caught that in testing.
4) There is also a line of code near the end of addItemLine that doesn't actually do anything! Maybe you can spot that one on your own.
There are some other issues but those are the ones that leapt out at me.
Just a quick non-tested solution that may work. Something is copied from your code, something is changed because your code was wrong.
// If you create this inside the method than you'll lose everything everytime you call addItemLine
private ArrayList<lineItem> lineItems;
public void addItemLine(lineItem line){
Scanner mykey=new Scanner(System.in);
for (int i=0; i<2;i++){
String k= line.getItemName();
int m= line.getQuantity();
double d= line.getPrice();
System.out.println("enter item name:");
k = mykey.next();
line.setItemName(k);
System.out.println("enter quantity:");
m= mykey.nextInt();
line.setQuantity(m);
System.out.println("enter unit price:");
d= mykey.nextDouble();
line.setPrice(d);
line.getItemName(); line.getQuantity(); line.getPrice();
lineItems.add(new lineItem(k,m,d));
// This doesn't have to return anything, it just adds to the list
}
// No parameteres, this should build the string for the current object
public String toString() {
// String concatenation is not the best idea, StringBuilder is better
StringBuilder sb = new StringBuilder();
// If you want to print all of them then you need to iterate over the list
for (lineItem item : lineItems){
sb.append("Customer ID:" + this.getcustomerID() + "\n" + "Customer Name: " + this.getcustomerName());
for (int i=0; i<2;i++){
// Copied from your code
sb.append("\n\n" + lin.getItemName() + "\t" + "Qty" + lin.getQuantity() + " "+ "#" + lin.getPrice() + " "+ "\t" + "$" + lin.getTotalPrice());
}
sb.append("\n);
}
return sb.toString();
}
It seems that you don't understand how to create a Java object, or how to keep your application model separate from your application view.
Here's a test run of your code, after I made some changes.
Enter customer name: Gilbert
Enter customer ID: 123
Enter item name: Spinach
Enter quantity: 5
Enter unit price: .89
Customer ID: 123
Customer Name: Gilbert
Spinach Qty 5 #0.89 $4.45
Enter item name: Corn
Enter quantity: 12
Enter unit price: .29
Customer ID: 123
Customer Name: Gilbert
Corn Qty 12 #0.29 $3.4799999999999995
Enter item name:
First, let's look at your Java objects. The first Java object which you didn't include, is LineItem. Note that Java class names start with a capital letter.
package com.ggl.transaction;
public class LineItem {
private String itemName;
private int quantity;
private double price;
public LineItem(String itemName, int quantity, double price) {
this.itemName = itemName;
this.quantity = quantity;
this.price = price;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public double getTotalPrice() {
return price * quantity;
}
}
A Java object consists of class fields, and getters and setters for the fields.
Next, here's your Transaction class.
package com.ggl.transaction;
import java.util.ArrayList;
import java.util.List;
public class Transaction {
private List<LineItem> lineItems;
private int customerID;
private String customerName;
public Transaction(int customerID, String customerName) {
this.customerID = customerID;
this.customerName = customerName;
this.lineItems = new ArrayList<>();
}
public int getcustomerID() {
return customerID;
}
public void setcustomerID(int customerID) {
this.customerID = customerID;
}
public String getcustomerName() {
return customerName;
}
public void setcustomerName(String customerName) {
this.customerName = customerName;
}
public void addItemLine(LineItem line) {
this.lineItems.add(line);
}
public void updateItem(String item, int quant, double pri) {
LineItem l = new LineItem(item, quant, pri);
int m = 0;
m = l.getQuantity();
m = m + quant;
l.setQuantity(m);
}
public double getTotalPrice() {
double totalPrice = 0;
for (int i = 0; i < 2; i++) {
LineItem item = lineItems.get(i);
totalPrice = totalPrice + item.getTotalPrice();
}
return totalPrice;
}
public String getLineItem(String s, int d, double k) {
LineItem o = new LineItem(s, d, k);
for (int i = 0; i < 2; i++) {
if (!s.equals(o.getItemName()))
System.out.println("item not found");
else
s = (o.getItemName() + o.getQuantity() + o.getPrice());
}
return s;
}
public String toItemString(LineItem lin) {
String b = "";
String a = ("Customer ID: " + this.getcustomerID() + "\n"
+ "Customer Name: " + this.getcustomerName());
for (int i = 0; i < 2; i++) {
b = ("\n\n" + lin.getItemName() + "\t" + "Qty " + lin.getQuantity()
+ " " + "#" + lin.getPrice() + " " + "\t" + "$"
+ lin.getTotalPrice() + "\n");
}
return a + b;
}
}
I simplified your addItemLine class. Code that receives input using the Scanner class belongs in your TransactionTesting class.
I renamed your toString method to toItemString. toString is a method of the Object class. Since your method has a parameter, I renamed it to lessen any confusion.
Finally, here's your TransactionTesting class. I fixed it up so it would work. You can specify any number of line items. To stop processing, just enter a blank item name.
package com.ggl.transaction;
import java.util.Scanner;
public class TransactionTesting {
public static void main(String args[]) {
Scanner mykey = new Scanner(System.in);
System.out.print("Enter customer name: ");
String name = mykey.nextLine().trim();
System.out.print("Enter customer ID: ");
int id = Integer.valueOf(mykey.nextLine().trim());
Transaction mytrans = new Transaction(id, name);
boolean processing = true;
while (processing) {
System.out.print("Enter item name: ");
String k = mykey.nextLine().trim();
if (k.equals("")) {
processing = false;
} else {
System.out.print("Enter quantity: ");
int m = Integer.valueOf(mykey.nextLine().trim());
System.out.print("Enter unit price: ");
double d = Double.valueOf(mykey.nextLine().trim());
LineItem lineItem = new LineItem(k, m, d);
mytrans.addItemLine(lineItem);
System.out.println("\n" + mytrans.toItemString(lineItem));
}
}
mykey.close();
}
}
Remember, keep your application model (LineItem & Transaction) separate from your application view (TransactionTesting).
Simply put, in your method "addItemLine" you take data from 1 lineItem, overwrite it with some keyboard input, and the put in the list 2 other lineItem instances.
Then in the test code you print the original lineItem, which is not even in the list.
The method itself iterates on nothing, just creates twice the same string "b".
I suggest you to look at some tutorials on arrays and for loops.
I'm a college student doing a Java homework. I've created this program that allows user to enter a job information.
The problem is that my program doesn't return information entered.
I look at my program for a while, but I know it's something simple I'm missing.
public class Employee
{
String name; // Employee name
String employeeNumber; // Employee number
String hireDate; // Employee hire date
int shift; // Employee shift
double payRate;
public void setEmployeeNumber(String e)
{
if (isValidEmpNum(e))
{
employeeNumber = e;
}
else
{
employeeNumber = "";
}
}
public Employee(String name, String e, String hireDate, double payRate, int shift)
{
this.name = name;
this.setEmployeeNumber(e);
this.hireDate = hireDate;
this.payRate = payRate;
this.shift = shift;
}
public Employee()
{
name = "";
employeeNumber = "";
hireDate = "";
}
public void setpayRate(double payRate)
{
this.payRate = payRate;
}
public double getpayRate()
{
return payRate;
}
public void setshift(int shift)
{
this.shift = shift;
}
public int getshift()
{
return shift;
}
public void setName(String name)
{
this.name = name;
}
public void setHireDate(String hireDate)
{
this.hireDate = hireDate;
}
public String getName()
{
return name;
}
public String getEmployeeNumber()
{
return employeeNumber;
}
public String getHireDate()
{
return hireDate;
}
private boolean isValidEmpNum(String e)
{
boolean status = true;
if (e.length() != 5)
status = false;
else
{
if ((!Character.isDigit(e.charAt(0))) ||
(!Character.isDigit(e.charAt(1))) ||
(!Character.isDigit(e.charAt(2))) ||
(e.charAt(3) != '-') ||
(!Character.isLetter(e.charAt(4))) ||
(!(e.charAt(4)>= 'A' && e.charAt(4)<= 'M')))
{
status = false;
}
}
return status;
}
public String toString()
{
String str = "Name: " + name + "\nEmployee Number: ";
if (employeeNumber == "")
{
str += "INVALID EMPLOYEE NUMBER";
}
else
{
str += employeeNumber;
}
str += ("\nHire Date: " + hireDate);
return str;
}
}
I declared this in another class.
import javax.swing.JOptionPane;
public class ProductionWorkerDemo extends Employee
{
public static void main(String[] args)
{
String name; // Employee name
String employeeNumber; // Employee number
String hireDate; // Employee hire date
int shift; // Employee shift
double payRate; // Employee pay
String str;
String str2;
name = JOptionPane.showInputDialog("Enter your name: ");
employeeNumber = JOptionPane.showInputDialog("Enter your employee number: ");
hireDate = JOptionPane.showInputDialog("Enter your hire date: ");
str = JOptionPane.showInputDialog("Enter your shift: ");
payRate = Double.parseDouble(str);
str2 = JOptionPane.showInputDialog("Enter your payrate: ");
payRate = Double.parseDouble(str2);
ProductionWorkerDemo pw = new ProductionWorkerDemo();
System.out.println();
System.out.println("Name: " + pw.getName());
System.out.println("Employee Number: " + pw.getEmployeeNumber());
System.out.println("Hire Date: " + pw.getHireDate());
System.out.println("Pay Rate: " + pw.getpayRate());
System.out.println("Shift: " + pw.getshift());
}
}
You need to use an appropiate constructor or the set* methods to set the fields on the object. Currently, all of them are empty, thus the get* methods return either nothing or default values.
Also, you shouldn't extend Employee with the class containing the main method, just use the Employee class directly (the idea behind inherting from a class is to extend it, in your case you just need it as an object so save data, so don't derive from it but use it):
import javax.swing.JOptionPane;
public class ProductionWorkerDemo
{
public static void main(String[] args)
{
String name; // Employee name
String employeeNumber; // Employee number
String hireDate; // Employee hire date
int shift; // Employee shift
double payRate; // Employee pay
String str;
String str2;
name = JOptionPane.showInputDialog("Enter your name: ");
employeeNumber = JOptionPane.showInputDialog("Enter your employee number: ");
hireDate = JOptionPane.showInputDialog("Enter your hire date: ");
str = JOptionPane.showInputDialog("Enter your shift: ");
payRate = Double.parseDouble(str);
str2 = JOptionPane.showInputDialog("Enter your payrate: ");
payRate = Double.parseDouble(str2);
Employee pw = new Employee(/*provide arguments here*/);
System.out.println();
System.out.println("Name: " + pw.getName());
System.out.println("Employee Number: " + pw.getEmployeeNumber());
System.out.println("Hire Date: " + pw.getHireDate());
System.out.println("Pay Rate: " + pw.getpayRate());
System.out.println("Shift: " + pw.getshift());
}
}
You are setting the employee information on local variables only. You are not passing them to the ProductionWorkerDemo nor it's super class Employee.
You don't need to extend the Employee with the ProductionWorkerDemo as the ProductionWorkerDemo is not an Employee. You can just remove the extends Employee text.
You're not passing the variables to the Employee. You've created a constructor in the Employee class that takes them all so you can use it
Employee pw = new Employee(name, employeeNumber, hireRate, payRate, shift);
Now you'll notice that you haven't asked for the shift.
First you need to add the constructor you the Demo Class:
public class ProductionWorkerDemo extends Employee{
public ProductionWorkerDemo(String name, String e, String hireDate, double payRate, nt shift){
{
super(name, e, hireDate, payRate, shift);
}
}
Then in your class you need to instantiate:
ProductionWorkerDemo pw = new ProductionWorkerDemo(name,
employeeNumber,
hireDate,
payRate,
shift);
You are declaring variables called name, employeenumber, etc in your main method. When you try to use them, it's going to use those, not your class variables.
why don't you try making a new ProductionWorkerDemo based on the constructor you defined in Employee class?
ProductionWorkerDemo pw = new ProductionWorkerDemo(name,employeeNumber,hireDate,payRate,shift);
And also, your payRate is being assigned twice, you should change the first one to shift, and use Integer.parseInt
You have local variables in main() whose values you are setting. You then create a ProductionWorkerDemo object, who has instance variables with the same names, but are all initially empty, due to the constructor setting them that way.
You never pass your local variables in to your ProductionWorkerDemo object, so when you call the getters they return the empty values.
I fix the problem with my program, thanks for the help everyone.
I was not passing the variables to the Employee.
I add this statement to ProductionWorkerDemo class.
Employee pw = new Employee(name, employeeNumber, hireRate, payRate, shift);
P.S. You can close this thread.
I am a first year student and learning setter and getter at school.
When I run it, it is ignoring the following statement:
String Origin = scan.nextLine();
and then it goes to the next line.
Here is the main:
import java.util.Scanner;
public class FlightTest
{
public static void main (String [] args)
{
Scanner scan = new Scanner (System.in);
Flight Flight1 = new Flight ();
System.out.print ("Airline Name: ");
String AirlineName = scan.nextLine ();
System.out.print ("Flight Number: ");
int FlightNumber = scan.nextInt ();
System.out.print ("Origin: ");
String Origin = scan.nextLine(); // There is a problem here
System.out.print ("Destination: ");
String Destination = scan.nextLine ();
}
}
This is the class
public class Flight
{
private String AirlineName;
private int FlightNumber;
private String Origin;
private String Destination;
public String setAirlineName()
{
String Name = AirlineName;
return Name;
}
public String getAirlineName()
{
return AirlineName;
}
public int setFlightNumber ()
{
int Number = FlightNumber;
return Number;
}
public int getFlightNumber ()
{
return FlightNumber;
}
public String setOrigin ()
{
String Orig = Origin;
return Orig;
}
public String getOrigin ()
{
return Origin;
}
public String setDestination ()
{
String Desti = Destination;
return Desti;
}
public String getDestination ()
{
return Destination;
}
public String toString ()
{
String result = AirlineName + " flight number "
+ FlightNumber + " leaves from " + Origin + " to "
+ Destination + ".";
return result;
}
}
because scan.nextInt() doesn't use the whole line, the next call to scan.nextLine() is returning the end of the line that the flight number was on, which is probably just a newline.
Add another call to scan.nextLine()
System.out.print ("Flight Number: ");
int FlightNumber = scan.nextInt ();
scan.nextLine(); // get rid of rest of line
System.out.print ("Origin: ");
String Origin = scan.nextLine();
and I think things will work.
and your setter is wrong, you should pass a parameter.
private String airlineName;
public String getAirlineName() {
return airlineName;
}
public void setAirlineName(String airlineName) {
this.airlineName = airlineName;
}
you can use setter like this
Flight f = new Flight ();
System.out.print ("Airline Name: ");
f.setAirlineName(scan.nextLine ());