JAVA - array error with string args[0] - java

/* 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

Related

Conflicting Packages PersonManager App Java

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().

Using toString() method in Java

I am trying to utilize the toString() in a class I have called Employee(). I have a 1D array of type Employee, which stores Employee Data, which include the Employee ID, Employee Name, Employee Address, and Employee Hire Date. I want the user to specify the amount of employees, and then enter the relevant data for however many employees the user wants. I then want to print the result for the user with the information entered. I keep getting some results that are null. I tried using an If statement that printed output if it didn't equal null, but that didn't work. I know the output works if I print out a single variable, such as address, but I want all variables to print out. Thank you for any help.
public class Address
{
public String address;
public void getAddress(String a)
{
address = a;
}
public String toString()
{
return address;
}
}
public class Name
{
String name;
public void getName(String n)
{
name = n;
}
public String toString()
{
return name;
}
}
public class Date
{
public String date;
public String date1;
public void getDate(int d, int m, int y)
{
date1 = (m + "/" + d + "/" + y);
}
public String toString()
{
return date1;
}
}
import java.util.Scanner;
public class Employee
{
private int number;
private Name name1 = new Name();
private Address address1 = new Address();
private Date hireDate = new Date();
String number1;
public void getDate1(int d, int m, int y)
{
hireDate.getDate(d, m, y);
}
public void getID(int x)
{
number = x;
}
public void setName( String n)
{
name1.getName(n);
}
public void getAddress(String a)
{
address1.address = a;
}
String z;
public String toString()
{
number1 = String.valueOf(number);
String name2 = String.valueOf(name1);
String address2 = String.valueOf(address1);
String hireDate2 = String.valueOf(hireDate);
z = number1 + " " + name2 + " " + address2 + " " + hireDate2;
return z;
}
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter amount of Employees: ");
int input1 = input.nextInt();
input.nextLine();
for (int i = 0; i < input1; i++)
{
Employee [] employees = new Employee[4];
System.out.println("Please enter the employee ID: ");
int employeeID = input.nextInt();
input.nextLine();
employees[0] = new Employee();
employees[0].getID(employeeID);
System.out.println("Please enter the employees Name: ");
String name2 = input.nextLine();
employees[1] = new Employee();
employees[1].setName(name2);
System.out.println("Please enter the employee's address: ");
String address2 = input.nextLine();
employees[2] = new Employee();
employees[2].getAddress(address2);
System.out.println("please enter hire date, day (1-31),");
System.out.print("month (1-12), year (1901 - 2019) in order on seperate");
System.out.print(" lines: ");
int input2 = input.nextInt();
int input3 = input.nextInt();
int input4 = input.nextInt();
employees[3] = new Employee();
employees[3].getDate1(input2, input3, input4);
for (int p = 0; p < employees.length; p++)
{
System.out.println(employees[p]);
}
}
}
}
I have create classes which were needed. You can change them but you are creating employee object every time. I have corrected the code debug it and you will know what was wrong.
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
class Name {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
public class Employee {
private int number;
private Name name1 = new Name();
private Address address1 = new Address();
private Date hireDate = new Date();
String number1;
public void getDate1(int d, int m, int y) {
Calendar calendar = Calendar.getInstance();
calendar.set(y, m, d);
hireDate = calendar.getTime();
}
public void getID(int x) {
number = x;
}
public void setName(String n) {
name1.setName(n);
}
public void getAddress(String a) {
address1.setAddress(a);
}
String z;
public String toString() {
number1 = String.valueOf(number);
String name2 = name1.getName();
String address2 = address1.getAddress();
String hireDate2 = String.valueOf(hireDate);
z = number1 + " " + name2 + " " + address2 + " " + hireDate2;
return z;
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter amount of Employees: ");
int input1 = input.nextInt();
input.nextLine();
Employee[] employees = new Employee[input1];
for (int i = 0; i < input1; i++) {
System.out.println("Please enter the employee ID: ");
int employeeID = input.nextInt();
input.nextLine();
employees[i] = new Employee();
employees[i].getID(employeeID);
System.out.println("Please enter the employees Name: ");
String name2 = input.nextLine();
employees[i].setName(name2);
System.out.println("Please enter the employee's address: ");
String address2 = input.nextLine();
employees[i].getAddress(address2);
System.out.println("please enter hire date, day (1-31),");
System.out.print("month (1-12), year (1901 - 2019) in order on seperate");
System.out.print(" lines: ");
int input2 = input.nextInt();
int input3 = input.nextInt();
int input4 = input.nextInt();
employees[i].getDate1(input2, input3, input4);
System.out.println(employees[i]);
}
}
}

ArrayLists (Removing and Changing Elements)

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();

Inheritance code returns no value

I created a super class called Employee, with a subclass called ProductionWorker and a driver called ProductionWorkerDriver. The program takes my entered info and returns the String values from the Employee class, but not the double and int values from the ProductionWorker class. The program I'm using said I had to initialize the values of those as 0, and I'm thinking that's why they show up as zero when compiled. However, the program won't compile without that, so I'm not sure what to do.
public class Employee {
private String name;
private String employeeNumber;
private String hireDate;
public Employee(String n, String num, String date) {
name = n;
employeeNumber = num;
hireDate = date;
}
public Employee() {
name = "";
employeeNumber = "";
hireDate = "";
}
public void setName(String n) {
name = n;
}
public void setEmployeeNumber(String e) {
employeeNumber = e;
}
public void setHireDate(String h) {
hireDate = h;
}
public String getName() {
return name;
}
public String getEmployeeNumber() {
return employeeNumber;
}
public String getHireDate() {
return hireDate;
}
public String toString() {
String str = "Employee Name: " + name
+ "\nEmployee #: " + employeeNumber
+ "\nHire Date: " + hireDate;
return str;
}
} //end of Employee class
//beginning of ProductionWorker class
import java.text.DecimalFormat;
public class ProductionWorker extends Employee {
private int shift;
private double payRate;
public int DAY_SHIFT = 1;
public int NIGHT_SHIFT = 2;
public ProductionWorker(String n, String num, String date, int sh, double rate) {
super(n, num, date);
shift = sh;
payRate = rate;
}
public ProductionWorker() {
}
public void setShift(int s) {
shift = s;
}
public void setPayRate(double p) {
payRate = p;
}
public int getShift() {
return shift;
}
public double getPayRate() {
return payRate;
}
public String toString() {
DecimalFormat dollar = new DecimalFormat("#,##0.00");
String str = super.toString() + "\nShift: " + shift
+ "\nPay Rate: $" + dollar.format(payRate);
return str;
}
}//end of ProductionWorker class
//beginning of ProductionWorkerDriver
import java.util.Scanner;
public class ProductionWorkerDriver {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String name = null;
String employeeNumber = null;
String hireDate = null;
int shift = 0;
double payRate = 0;
int DAY_SHIFT = 1;
int NIGHT_SHIFT = 2;
Employee info = new Employee(name, employeeNumber, hireDate);
System.out.println("Employee Name:");
name = keyboard.nextLine();
System.out.println("Employee #:");
employeeNumber = keyboard.nextLine();
System.out.println("Hire Date:");
hireDate = keyboard.nextLine();
ProductionWorker info2 = new ProductionWorker(name, employeeNumber, hireDate, shift, payRate);
System.out.println("Shift 1 or 2:");
shift = keyboard.nextInt();
System.out.println("Pay Rate:");
payRate = keyboard.nextDouble();
System.out.println(info2.toString());
}
}//end of ProductionWorkerDriver
You're not doing anything with the data you've entered:
System.out.println("Shift 1 or 2:");
shift = keyboard.nextInt();
System.out.println("Pay Rate:");
payRate = keyboard.nextDouble();
... the shift and payRate variables aren't used again. Changing the values of these local variables doesn't change the values in the instance that you created earlier using the same variables.
You should either be calling:
info2.setShift(shift);
info2.setPayRate(payRate);
... or better, wait until after you've asked those questions before you construct the instance. You're also not using your info variable at all. Your entire main method can be improved to:
Scanner keyboard = new Scanner(System.in);
System.out.println("Employee Name:");
String name = keyboard.nextLine();
System.out.println("Employee #:");
String employeeNumber = keyboard.nextLine();
System.out.println("Hire Date:");
String hireDate = keyboard.nextLine();
System.out.println("Shift 1 or 2:");
int shift = keyboard.nextInt();
System.out.println("Pay Rate:");
double payRate = keyboard.nextDouble();
ProductionWorker worker =
new ProductionWorker(name, employeeNumber, hireDate, shift, payRate);
System.out.println(worker);
Notice how in each case we don't declare a variable until we need it.
Note that the fact that your employee number and your hire date are both String values is a bit of a worry, and it's a bad idea to use double for currency values - get into the habit of using BigDecimal, or use an integer to represent a number of cents/pennies/whatever.
This:
System.out.println("Shift 1 or 2:");
shift = keyboard.nextInt();
System.out.println("Pay Rate:");
payRate = keyboard.nextDouble();
Will update the shift and payRate of your main method:
public static void main(String[] args)
{
//...
int shift = 0;
double payRate = 0;
Because you're outputting the values from the ProductionWorker, and those values are never updated, it will always output 0. Simply because you initialize ProductionWorker with those variables does not mean that the reference shift in the main method will point to the same place in memory as the reference shift inside ProductionWorker.

Java: Scanner is not being recognized when it's run

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 ());

Categories