Java StringTokenizer and storing Array - java

I have programmed a Worker class and the driverclass for Worker..
My working class is compiling fine and showing the desired output..
But in array and StringTokenizer I am facing the main problem... And in line 32 of TestWorker.java there is an error, and I donot know why is it giving
The question is...
(i)Declare an array that can store the references of up to 5 Worker objects constructed with the data(name,workerID and hourlyRate).
(ii)And now allow the users to enter workerID and hours repeatedly until user enter an empty string. Read these values and invoke the method addWeekly() on the appropriate object (by searching through the array to locate the object with the specified ID). If a nonexistent ID is entered, display an appropriate error message.
(iii)Compute and display the salary for all the workers
Please see my codes below.....
//Worker.java
public class Worker {
public final double bonus=100;
protected String name, workerID;
protected double hourlyRate, totalHoursWorked,tax,grossSalary,netSalary;
public Worker(){
}
public Worker(String name, String workerID, double hourlyRate){
this.name = name;
this.workerID = workerID;
this.hourlyRate = hourlyRate;
}
public void addWeekly(double hoursWorked){
this.totalHoursWorked = this.totalHoursWorked + hoursWorked;
}
public double gross(){
grossSalary = (totalHoursWorked*hourlyRate);
if(totalHoursWorked>=150){
grossSalary = grossSalary +100;
}
return grossSalary;
}
public double netAndTax(){
netSalary = grossSalary;
if(grossSalary>500){
tax = (grossSalary - 500) *0.3;
netSalary = (grossSalary - tax);
}
return netSalary;
}
public String getName(){
return this.name;
}
public String getWorkerID(){
return this.workerID;
}
public double getHourlyRate(){
return this.hourlyRate;
}
public double getTotalHours(){
return totalHoursWorked;
}
public double getGrossSalary(){
return grossSalary;
}
public void addToGross(double amt){
grossSalary = grossSalary + amt;
}
public void displaySalary(){
System.out.print("Name: " +getName() + "\nID :" + getWorkerID()
+ "\nHourly Rate: " + getHourlyRate()+ "\nTotalHours Worked" + getTotalHours() +
"\nGross pay" + getGrossSalary() + "\nTax: " + netAndTax() +
"\nNet Pay: " + netAndTax());
}
}
//TestWorker.java
import java.util.Scanner;
import java.util.StringTokenizer;
public class TestWorker {
public static void main(String args[]){
Worker e = new Worker("John Major","s123",15.0);
e.addWeekly(45);
e.addWeekly(40);
e.addWeekly(32);
e.addWeekly(38);
e.gross();
e.netAndTax();
e.displaySalary();
Worker[] worklist = new Worker[5];
worklist[0] = new Worker("Richard Cooper","s1235",20.0);
worklist[1] = new Worker("John Major","s1236",18.0);
worklist[2] = new Worker("Mary Thatcher","s1237",15.0);
worklist[3] = new Worker("David Benjamin","s1238",16.0);
worklist[4] = new Worker("Jack Soo","s1239",25.0);
Scanner input = new Scanner(System.in);
String name;
double hourly;
do{
System.out.println("\n");
System.out.print("Please Enter ID and hours-worked in a given week: ");
name = input.nextLine();
StringTokenizer string = new StringTokenizer(name,"+");
String[] array =new String[(string.countTokens)];
for(int i=0;i<=4;i++){
if(array[0].equals(worklist[0])){
e.getName();
e.getWorkerID();
e.addWeekly(Double.parseDouble(array[0]));
e.gross();
e.displaySalary();
}
else if(array[0].equals(worklist[1])){
e.getName();
e.getWorkerID();
e.addWeekly(Double.parseDouble(array[1]));
e.gross();
e.displaySalary();
}
else if(array[0].equals(worklist[2])){
e.getName();
e.getWorkerID();
e.addWeekly(Double.parseDouble(array[2]));
e.gross();
e.displaySalary();
}
else if(array[0].equals(worklist[3])){
e.getName();
e.getWorkerID();
e.addWeekly(Double.parseDouble(array[3]));
e.gross();
e.displaySalary();
}
else if(array[0].equals(worklist[4])){
e.getName();
e.getWorkerID();
e.getHourlyRate();
e.addWeekly(Double.parseDouble(array[4]));
e.gross();
e.displaySalary();
}
else{
System.out.println("Please Enter correct information");
}
}
System.out.println();
while(string.hasMoreElements()){
System.out.println(string.nextElement());
}
}
while(name.isEmpty()==false);
}
}

Firstly, you've specified countTokens as a field when it is actually a method on this line:
String[] array = new String[(string.countTokens)]; // Incorrect
String[] array = new String[(string.countTokens())]; // Correct
Now you seem to be splitting the input on a + sign? So you're expected input is something along the lines of s123+12 which would mean ID s123 worked 12 hours this week. So in order to solve something like you probably want a loop that looks like this:
Scanner input = new Scanner(System.in);
System.out.println("\n");
System.out.print("Please Enter ID and hours-worked in a given week: ");
String enteredString = input.nextLine();
while (!enteredString.isEmpty()) {
StringTokenizer stringtok = new StringTokenizer(enteredString, "+");
String id = stringtok.nextToken();
Double hours = Double.parseDouble(stringtok.nextToken());
for (int i = 0; i < 5; i++) {
if (worklist[i].getWorkerID().equals(id)) {
worklist[i].addWeekly(hours);
break;
}
}
System.out.println("\n");
System.out.print("Please Enter ID and hours-worked in a given week: ");
enteredString = input.nextLine();
}
for (int i = 0; i < 5; i++) {
worklist[i].gross();
worklist[i].netAndTax();
worklist[i].displaySalary();
}
Keep in mind that this is very rough and I'm not entirely clear from your instructions on what exactly you are trying to achieve.

Why not consider String.split() name.split("\\+") that will give you a string array

Related

Looping through an arraylist [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
Hi all I'm trying to loop through an array using a password of 4 letters and an ID of 4 int numbers.
Thus far I can create the two 'keys' BUT I can't get them to search for the account on the arraylist I have despite it's creation. I really don't know how to fix this problem since the only way seems to be to just call for an 'If' statement or switch.
Here is where I have the code set up:
int acctID;
int depositingAmount;
//System.out.println("Input your ID and then your password to deposit money.");
String inputID = JOptionPane.showInputDialog("Please input your ID to begin depositing money.");
acctID = Integer.parseInt(inputID);
String inputPassword = JOptionPane.showInputDialog("Please input your password to verify your account.");
// int depositAmount;
// do {
for (int i = 0; i < bankAccounts.size(); i++)//Loops through accounts in my arraylist.
{
if (acctID == bankAccounts.get(i).getAccountId() && inputPassword == bankAccounts.get(i).getPassword())//If ID and password work are true then it goes in here.
{
String depositAmount = JOptionPane.showInputDialog("Please input how much money you want to "
+ "input");//An here is where you would be able to spit out how much money to deposit.
depositingAmount = Integer.parseInt(depositAmount);
bankAccounts.get(i).deposit(depositingAmount);
break;
}
}
Like you can see the loop in theory is suppose to go "Oh okay lets me start going though all of the accounts in the list until I get to yours" and when it finds it "oh hey I found your account, here let me give you the deposit feature". Sorry if I tried to simplify it too much in this paragraph its just that this problem is frustrating me too no end because I know that if I can solve this then the rest of my project is done. I have a withdraw feature also but that's basically the same thing but playing with different methods on the same class.
EDIT: Here are the constructors
public BankAccount() {//ADDED TWO PARAMETERS
//NO ARGUMENT CONSTRUCTOR
accountId = (int) (Math.random() * 9000) + 999;
//RANDBETWEEN
setAccountBalance(0);
Random passcode = new Random();
//char charcs = (char)(passcode.nextInt(26) + 'a');
//Added string.
String chars = "abcdefghijklmnopqrstuvwxyz";
int length = chars.length();
for (int i = 0; i < 4; i ++){
password += chars.split("")[ (int) (Math.random() * (length - 1)) ];}
}
public BankAccount(double accountBalance) { // ONE ARGUMENT CONSTRUCTOR
accountId = (int) (Math.random() * 9000) + 1000;
setAccountBalance(accountBalance);
//Random passcode = new Random();
//password = (String) (passcode.nextInt(26)) + 'a';
//NEED A VARIABLE TO PASS IN
//4 Digit password
String chars = "abcdefghijklmnopqrstuvwxyz";
int length = chars.length();
for (int i = 0; i < 4; i ++){
password += chars.split("")[ (int) (Math.random() * (length - 1)) ];}
}
An here are the getters..
public int getAccountId() {
return accountId;
}
public String getPassword() {
return password;
}
Also here are the fields I created..
private int accountId;
private double accountBalance;
private static double annualInterestRate = 0.045;
private static java.util.Date dateCreated = new java.util.Date();
private String name;
private String password = "";
Here is where I stand with the If statement
if (acctID == bankAccounts.get(i).getAccountId() && inputPassword.equals(bankAccounts.get(i).getPassword()))
I've seen the other thread that's been posted has a similar question but their answer of just putting .equals() is not enough. Unless i'm stuppose to just take out bankAccounts from the line.
EDIT 2: The entire code.
import java.util.Random;
public class BankAccount {
private int accountId;
private double accountBalance;
private static double annualInterestRate = 0.045;
private static java.util.Date dateCreated = new java.util.Date();
private String name;
private String password = "";
public BankAccount() {//ADDED TWO PARAMETERS
//NO ARGUMENT CONSTRUCTOR
accountId = (int) (Math.random() * 9000) + 999;
//RANDBETWEEN
setAccountBalance(0);
Random passcode = new Random();
//char charcs = (char)(passcode.nextInt(26) + 'a');
//Added string.
String chars = "abcdefghijklmnopqrstuvwxyz";
int length = chars.length();
for (int i = 0; i < 4; i ++){
password += chars.split("")[ (int) (Math.random() * (length - 1)) ];}
}
public BankAccount(double accountBalance) { // ONE ARGUMENT CONSTRUCTOR
accountId = (int) (Math.random() * 9000) + 1000;
setAccountBalance(accountBalance);
//Random passcode = new Random();
//password = (String) (passcode.nextInt(26)) + 'a';
//NEED A VARIABLE TO PASS IN
//4 Digit password
String chars = "abcdefghijklmnopqrstuvwxyz";
int length = chars.length();
for (int i = 0; i < 4; i ++){
password += chars.split("")[ (int) (Math.random() * (length - 1)) ];}
}
public int getAccountId() {
return accountId;
}
public double getAccountBalance() {
return accountBalance;
}
public void setAccountBalance(double accountBalance) {
this.accountBalance = accountBalance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public void withdraw(double amountToWithdraw) {
if (amountToWithdraw > accountBalance) {
//putting together withdraw make sure to have a validation to stop ppl from going over.
System.out.println("Sorry you cannot exceed the amount you have in your balance.");
}
else {
accountBalance = accountBalance - amountToWithdraw;
}
}
public void deposit(double amountToDeposit) {
if (amountToDeposit < 0) {
//deposits cannot be negative
System.out.println("You cannot deposit a negative amount of dallars.");
}
else {
accountBalance = accountBalance + amountToDeposit;
}
}
public double getMonthlyInterestRate() {
int MonthsInAYear = 12;//method variable is small BUT just need to get results
double monthlyInterestRate = annualInterestRate / MonthsInAYear;
return monthlyInterestRate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String toString(){
String bankInfo = " Password: " + getPassword() + " Account ID: " + getAccountId();
return bankInfo;
}
}
public class CurrentAccount extends BankAccount{
private static float overdraftLimit = 100;
CurrentAccount(){
super();
}
public static float getOverdraftLimit() {
return overdraftLimit;
}
// MAKE A SETTER FOR THE OVERDRAFTLIMIT
public void withdraw(double amountToWithdraw){
if (amountToWithdraw <= getAccountBalance()+overdraftLimit) {
setAccountBalance(getAccountBalance() - amountToWithdraw);
}
else {
System.out.println("Error this transaction has been cancelled.");
}
}
}
public class SavingsAccount extends BankAccount{
private static double interest;
public SavingsAccount (){
super();
interest = 0;
}
public void addInterest(){
interest = getAccountBalance() * getMonthlyInterestRate(); //GETTING ZEROS FROM ACCOUNTBALANCE
//CHANGE getAccountBalance with some other initial payment.
super.deposit(interest);
}
public double getInterest() {
return interest;
}
public void setInterest(float interest) {
this.interest = interest;
}
}
public class Bank {
Scanner input = new Scanner(System.in);
Scanner Restart = new Scanner(System.in);
private static ArrayList<BankAccount> bankAccounts; // MADE THIS STATIC
public Bank() {
bankAccounts = new ArrayList<BankAccount>();
}
public void openAccount() {
Object[] possibilities = {"Regular Account", "Savings Account", "Checking Account"};
Object inputValue = JOptionPane.showInputDialog(null, "Please pick an option from this menu: ",
"input", JOptionPane.INFORMATION_MESSAGE, null, possibilities, possibilities [0]);
if (inputValue.equals("Regular Account")) {
// Make a regular acct
String inputName = JOptionPane.showInputDialog(null, "Please input your name");
BankAccount newBankAccount = new BankAccount();
newBankAccount.setName(inputName);
bankAccounts.add(newBankAccount);
JOptionPane.showMessageDialog(null, "Account ID: " + newBankAccount.getAccountId());
JOptionPane.showMessageDialog(null, "Account Password: " + newBankAccount.getPassword());
} else if (inputValue.equals("Savings Account")) {
// Make a savings acct
String inputNameSavings = JOptionPane.showInputDialog(null, "Please input your name");
BankAccount newBankAccount = new SavingsAccount();
newBankAccount.setName(inputNameSavings);
bankAccounts.add(newBankAccount);
JOptionPane.showMessageDialog(null, "Account ID: " + newBankAccount.getAccountId());
JOptionPane.showMessageDialog(null, "Account Password: " + newBankAccount.getPassword());
} else if (inputValue.equals("Checking Account")) {
// Make a checking acct
String inputNameChecking = JOptionPane.showInputDialog(null, "Please input your name");
BankAccount newBankAccount = new CurrentAccount();
newBankAccount.setName(inputNameChecking);
bankAccounts.add(newBankAccount);
JOptionPane.showMessageDialog(null, "Account ID: " + newBankAccount.getAccountId());
JOptionPane.showMessageDialog(null, "Account Password: " + newBankAccount.getPassword());
}
}
public static ArrayList<BankAccount> getBankAccounts() {
return bankAccounts;//Moving this into the Open.Account?
}
public void closeAccount() {
System.out.println("Hello give me the name of the" + " "
+ "account you would like to close.");
String userName = input.next();// Gets input for first choice.
// Ask for account id
System.out.println("Please input your account ID");
int userAccountId = input.nextInt();
for (int i = 0; i < bankAccounts.size(); i++) {
if (bankAccounts.get(i).getName().equals(userName)
&& bankAccounts.get(i).getAccountId() == userAccountId) {
bankAccounts.remove(i);
System.out.println("Account removed");
}
}
// anyway, you would set the name probably in the constructor function
// for that particular instantiation of the class
}
public void update() {
// UPDATES MY ACCOUNTS
for (int i = 0; i < bankAccounts.size(); i++) {
if (bankAccounts.get(i) instanceof SavingsAccount) {
((SavingsAccount) bankAccounts.get(i)).addInterest();
} else if (bankAccounts.get(i) instanceof CurrentAccount) {
if (bankAccounts.get(i).getAccountBalance() < 0) {
System.out.println("\nThe Account: " + bankAccounts.get(i).getName() + " has been OverDrafted.\n");
}
}
}
}// ends update
public void withdraw(){
System.out.println("Input your ID and then your password to withdraw money.");
int acctID = input.nextInt();
int withdrawAmount;
// do {
for (int i = 0; i < bankAccounts.size(); i++){
//input needed.
if (acctID == bankAccounts.get(i).getAccountId()){
System.out.println("We have found your account. Please input how much money you would like to withdraw.");
withdrawAmount = input.nextInt();
bankAccounts.get(i).withdraw(withdrawAmount);
break;
}
// } while (input != 1);
}
}
public void deposit(){
int acctID;
int depositingAmount;
//System.out.println("Input your ID and then your password to deposit money.");
String inputID = JOptionPane.showInputDialog("Please input your ID to begin depositing money.");
acctID = Integer.parseInt(inputID);
String inputPassword = JOptionPane.showInputDialog("Please input your password to verify your account.");
// int depositAmount;
// do {
for (int i = 0; i < bankAccounts.size(); i++)//Loops through accounts in my arraylist.
{
if (acctID == bankAccounts.get(i).getAccountId() && inputPassword.equals(bankAccounts.get(i).getPassword()))//If ID and password work are true then it goes in here.
{
String depositAmount = JOptionPane.showInputDialog("Please input how much money you want to "
+ "input");//An here is where you would be able to spit out how much money to deposit.
depositingAmount = Integer.parseInt(depositAmount);
bankAccounts.get(i).deposit(depositingAmount);
break;
}
}
}
}
An finally the class i'm running it on...
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class TestBankAccount {
public static void main(String[] args) {
// JOptionPane.showMessageDialog(null, "Hello User.");
Object[] menuPossibilities = {"Create a New Account", "Deposit", "Withdraw", "Display Balance", "Exit"};
Object menuValues = JOptionPane.showInputDialog(null, "Please pick an option from this menu: ",
"input", JOptionPane.INFORMATION_MESSAGE, null, menuPossibilities, menuPossibilities [0]);
while (!menuValues.equals("Exit")){
Bank newBank = new Bank();
// Bank newBank1 = new Bank();
// Bank newBank2 = new Bank(); Do the same thing as below but switch out
// bank1 and bank2 as a substitute.
ArrayList<BankAccount> bankList = newBank.getBankAccounts();
if (menuValues.equals("Create a New Account")){
newBank.openAccount();
}
else if (menuValues.equals("Deposit")){
newBank.deposit();
}
else if (menuValues.equals("Withdraw")){
newBank.withdraw();
}
else if (menuValues.equals("Display Balace")){
newBank.deposit();
}
else if (menuValues.equals("Exit")){
System.out.println("Thank you for using our service.");
}
menuValues = JOptionPane.showInputDialog(null, "Since you did not pick 5 please pick another option: ",
"input", JOptionPane.INFORMATION_MESSAGE, null, menuPossibilities, menuPossibilities [0]);
}
}
}
Use .equals method to check strings for equality.

Method to display records.

Hey guys just need help on how to finish this up.
Code Snippet:
import java.util.Scanner;
public class CreateLoans implements LoanConstants {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//set the program here
float prime;
float amountOfLoan = 0;
String customerFirstName;
String customerLastName;
String LoanType;
System.out.println("Please Enter the current prime interest rate");
prime = sc.nextInt() / 100f;
//ask for Personal or Business
System.out.println("are you after a business or personal loan? Type business or personal");
LoanType = sc.next();
//enter the Loan amount
System.out.println("Enter the amount of loan");
amountOfLoan = sc.nextInt();
//enter Customer Names
System.out.println("Enter First Name");
customerFirstName = sc.next();
System.out.println("Enter Last Name");
customerLastName = sc.next();
//enter the term
System.out.println("Enter the Type of Loan you want. 1 = short tem , 2 = medium term , 3 = long term");
int t = sc.nextInt();
}
}
I need to display the records I have asked and store the object into an array.
so this where I'm stuck. I need to do this in a loop 5 times and by the end display all records in an array, if that makes sense?
Try this way :
import java.util.Scanner;
public class CreateLoans {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Loan[] loans = new Loan[5];
for(int i=0;i<5;i++) {
loans[i] = new Loan();
System.out.println("Please Enter the current prime interest rate");
float prime = sc.nextInt();
prime = (float)(prime/100f);
loans[i].setPrime(prime);
//ask for Personal or Business
System.out.println("are you after a business or personal loan? Type business or personal");
String loanType = sc.next();
loans[i].setLoanType(loanType);
//enter the Loan amount
System.out.println("Enter the amount of loan");
float amountOfLoan = sc.nextFloat();
loans[i].setAmountOfLoan(amountOfLoan);
//enter Customer Names
System.out.println("Enter First Name");
String customerFirstName = sc.next();
loans[i].setCustomerFirstName(customerFirstName);
System.out.println("Enter Last Name");
String customerLastName = sc.next();
loans[i].setCustomerLastName(customerLastName);
}
//Display details
for(int i=0;i<5;i++) {
System.out.println(loans[i]);
}
}
}
class Loan {
private float prime;
private float amountOfLoan = 0;
private String customerFirstName;
private String customerLastName;
private String LoanType;
public float getPrime() {
return prime;
}
public void setPrime(float prime) {
this.prime = prime;
}
public float getAmountOfLoan() {
return amountOfLoan;
}
public void setAmountOfLoan(float amountOfLoan) {
this.amountOfLoan = amountOfLoan;
}
public String getCustomerFirstName() {
return customerFirstName;
}
public void setCustomerFirstName(String customerFirstName) {
this.customerFirstName = customerFirstName;
}
public String getCustomerLastName() {
return customerLastName;
}
public void setCustomerLastName(String customerLastName) {
this.customerLastName = customerLastName;
}
public String getLoanType() {
return LoanType;
}
public void setLoanType(String loanType) {
LoanType = loanType;
}
#Override
public String toString() {
return "First Name : " + customerFirstName + "\n" +
"Last Name : " + customerLastName + "\n" +
"Amount of Loan : " + amountOfLoan + "\n" +
"Loan type : " + LoanType + "\n" +
"Prime : " + prime + "\n\n";
}
}
Create a Loan class and put all necessary details as private members into it and override toString() method.
Make a ArrayList and add all the variables inside that list
ArrayList arrlist = new ArrayList();
arrlist.add(prime);
arrlist.add(LoanType);
arrlist.add(amountOfLoan);
arrlist.add(customerFirstName );
arrlist.add(customerLastName);
arrlist.add(t);
and display the ArrayList
System.out.println(arrlist);
Example of a loop
int[] nums = new int[5];
String[] names = new String[5];
Scanner input = new Scanner(System.in);
for (int i = 0; i < 5; i++){
System.out.println("Enter a number: ");
int number = input.nextInt();
// insert into array
nums[i] = number;
System.out.println("Enter a name: ");
String name = input.nextLne();
// insert into array
names[i] = name;
}
Everything you want to be looped 5 times, you can put inside the loop. Whatever values you want to store, you can do that in the loop also.

StringTokenizer and Array Java

I am completed the whole program, and it is working fine. But, I am having trouble with the StringTokenizer. I have class named Worker.java and a test class named TestWorker.java...
In the test class I have calculated and printed out the total hoursworked, grossSalary and etc..
But I am stuck in 1 position, that is I have to store name,id, and hourly rate in array, and then using the StringTokenizer, I have to prompt the user to enter worker ID and hourly rate.
When the user enter the user worker name and ID, the program output will show the user the hourly rate of the worker...
or in other words...
Allow the user to enter worker-ID and Hours repeatedly until user enter and empty string. Read the values and invoke the methods addWeekly() on the appropriate object(by searching through the array to locate the object with the specified ID). If a nonexistent ID is entered display an appropriate error message.
Please see my codings below and modify as your needs....
//Worker.java
public class Worker {
public final double bonus=100;
protected String name;
protected String workerID;
protected double hourlyRate;
protected double hoursWorked;
protected double weekHour;
protected double tax;
protected double grossSalary;
protected double netSalary;
public Worker() {
}
public Worker(String name,String workerID,double hourlyRate){
this.name = name;
this.workerID = workerID;
this.hourlyRate = hourlyRate;
}
public void addWeekly(double weekHour){
hoursWorked = hoursWorked + weekHour;
}
public double gross()
{
grossSalary = (hoursWorked*hourlyRate);
if(hoursWorked>=150)
{
grossSalary = grossSalary +100;
}
return grossSalary;
}
public double taxAndNet()
{
tax = (grossSalary - 500) * 0.3;
netSalary = (grossSalary-tax);
return netSalary;
}
public String getName()
{
return name;
}
public String getWorkerID()
{
return workerID;
}
public double getHourly()
{
return hourlyRate;
}
public double getTotalHours()
{
return hoursWorked;
}
public double getGrossSalary()
{
return grossSalary;
}
public void addToGross(double amt)
{
grossSalary = grossSalary + amt;
}
public void displaySalary()
{
System.out.println("Name :" + name + "\nID :" + workerID +"\nHourly rate : "+ hourlyRate +"\nTotal Hours Worked " + hoursWorked +"\nGross Pay: "+getGrossSalary()+ "\nTax : "+tax +"\nNetpay :" +netSalary);
}
}
//TestWorker.java
import java.util.StringTokenizer;
import java.util.Scanner;
public class TestWorker {
public static void main(String args[]) {
Worker e = new Worker("John Major","s123",15.0);
e.addWeekly(45);
e.addWeekly(40);
e.addWeekly(32);
e.addWeekly(38);
e.gross();
e.taxAndNet();
e.displaySalary();
Worker[] worklist = new Worker[5];
worklist[0] = new Worker("Richard Cooper","s1235",20.0);
worklist[1] = new Worker("John Major","s1236",18.0);
worklist[2] = new Worker("Mary Thatcher","s1237",15.0);
worklist[3] = new Worker("David Benjamin","s1238",16.0);
worklist[4] = new Worker("Jack Soo","s1239",25.0);
Scanner input = new Scanner(System.in);
String name;
do{
System.out.print("Please enter your name and worker ID: ");
name = input.nextLine();
StringTokenizer string = new StringTokenizer(name,"+");
System.out.println("******|||||*******");
while(string.hasMoreElements()){
System.out.println(string.nextElement());
}
}
while(name.isEmpty()==false);
String s = "Five+Three=Nine-One";
String arr[];
//declare it with 3 tokens as seen above:
StringTokenizer st = new StringTokenizer(s, "+=-");
//the array size is the number of tokens in the String:
arr = new String[st.countTokens()];
//when there are still more tokens, place it in the array:
int i = 0;
while(st.hasMoreTokens()){
arr[i] = st.nextToken();
i++;
}
//determine the word with the largest length:
int indexMax = 0;
for( i = 1; i < arr.length; i++){
if(arr[i].length() > arr[indexMax].length())
indexMax = i;
}
System.out.println("The largest element is in index: "
+ indexMax);
} //main
} //class
Please tell us your java version. Since jdk 1.4.2 you should use String.split(...) instead of the old Stringtokenizer. Check out this tutorial TIP: A little tutorial about String.split();

Can't get this to compile, what am I doing wrong?

OK so I can see the "setUniqueType" on line 33 and the "ItemDetails" on line 50 are what need to be corrected, but I can't figure out what's wrong with it and how to fix it. Please help so I can move in with my program...
MAIN
package inventory4;
import java.util.Scanner;
import java.util.Arrays;
import javax.swing.JOptionPane;
public class RunApp
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
ItemDetails theItem = new ItemDetails();
int number;
String Name = "";
String Type = "";
String sNumber = JOptionPane.showInputDialog(null,"How many items are to be put into inventory count?: ");
number = Integer.parseInt(sNumber);
ItemDetails[] inv = new ItemDetails[number];
for (int count = 0; count < inv.length; ++count)
{
Name = JOptionPane.showInputDialog(null,"What is item " + (count + 1) + "'s name?");
theItem.setName(Name);
Type = JOptionPane.showInputDialog(null,"Enter " + Name + "'s product type");
theItem.setUniqueType(Type);
String spNumber = JOptionPane.showInputDialog(null,"Enter " + Name + "'s product number");
double pNumber = Double.parseDouble(spNumber);
theItem.setpNumber(pNumber);
String sUnits = JOptionPane.showInputDialog(null,"How many " + Name + "s are there in inventory?");
double Units = Double.parseDouble(sUnits);
theItem.setUnits(Units);
String sPrice = JOptionPane.showInputDialog(null,Name + "'s cost");
double Price = Double.parseDouble(sPrice);
theItem.setPrice(Price);
inv[count] = new ItemDetails(Name, Price, Units, pNumber, Type);
}
for (int i = 0; i < inv.length; ++i)
{
JOptionPane.showMessageDialog(null, "Product Name" + inv[i].getName());
JOptionPane.showMessageDialog(null, "Product Type" + inv[i].getUniqueType());
JOptionPane.showMessageDialog(null, "Product Number" + inv[i].getpNumber());
JOptionPane.showMessageDialog(null, "Amount of Units in Stock" + inv[i].getUnits());
JOptionPane.showMessageDialog(null, "Price per Unit" + inv[i].getPrice());
JOptionPane.showMessageDialog(null, String.format("Total cost for %s in stock: $%.2f", inv[i].getName(), inv[i].calculateTotalPrice()));
JOptionPane.showMessageDialog(null,String.format("Restocking fee for %s is $%.2f", inv[i].getName(), inv[i].calculateRestock()));
String combinedData = inv[i].toString();
if(i == (inv.length -1)){
String lastItem = String.format("\nTotal Cost for all items entered: $%.2f\n", Items.getCombinedCost(inv));
combinedData = combinedData + lastItem;
JOptionPane.showMessageDialog(null, combinedData);
}else{
JOptionPane.showMessageDialog(null, combinedData);
}
} //end for
} //end main
} //end class
ITEMS
package inventory4;
public class Items implements Comparable
{
private String Name;
public double pNumber, Units, Price;
String allInfo;
public Items()
{
Name = "";
pNumber = 0.0;
Units = 0.0;
Price = 0.0;
}
public int compareTo(Object item)
{
Items tmp = (Items)item;
return this.getName().compareTo(tmp.getName());
} // end compareTo method
public Items(String productName, double productNumber, double unitsInStock, double unitPrice)
{
Name = productName;
pNumber = productNumber;
Units = unitsInStock;
Price = unitPrice;
}
public String toString()
{
StringBuffer allInfo = new StringBuffer();
allInfo.append(String.format("Name: %s\n pNumber: %.0f \n Units: %.0f \n Price: %.2f\n",
getName(),getpNumber(),getUnits(),getPrice()));
return allInfo.toString();
}
//setter methods
public void setName(String n)
{
Name = n;
}
public void setpNumber(double no)
{
pNumber = no;
}
public void setUnits(double u)
{
Units = u;
}
public void setPrice(double p)
{
Price = p;
}
//getter methods
public String getName()
{
return Name;
}
public double getpNumber()
{
return pNumber;
}
public double getUnits()
{
return Units;
}
public double getPrice()
{
return Price;
}
public double calculateTotalPrice()
{
return (Units * Price);
}
public static double getCombinedCost(Items[] item)
{
double combined = 0;
for (int i = 0; i < item.length; ++i)
{
combined = combined + item[i].calculateTotalPrice();
} //end loop
return combined;
} //end method
} //end class
ITEM DETAILS
package inventory4;
public class ItemDetails extends Items
{
private String UniqueType;
public ItemDetails()
{
super();
}
public String enterUniqueType()
{
return UniqueType;
}
public String getUniqueType()
{
return UniqueType;
}
public double calculateRestock() //setting up to calculate the restocking fee at 5%
{
return (Price * .05);
}
}
Compile errors:
RunApp.java:31: cannot find symbol
symbol : method setUniqueType(java.lang.String)
location: class ItemDetails
theItem.setUniqueType(Type);
^
RunApp.java:48: cannot find symbol
symbol : constructor ItemDetails(java.lang.String,double,double,double,java.lan
g.String)
location: class ItemDetails
inv[count] = new ItemDetails(Name, Price, Units, pNumber, Type);
^
2 errors
Your ItemDetails class has no setUniqueType method. You should add one.
The constructor you're using at :48 is "String, double, double, double, String" but your constructor is really only "String double double double" Either remove Type or add a String parameter to the end of your Item constructor, or make an ItemDEtails constructor with the five parameters.
Your ItemDetails has no constructor that matches that argument. If you want to chain the constructor, declare it in ItemDetails
Chaining the constructor:
public ItemDetails(String productName, double productNumber, double unitsInStock, double unitPrice
super(productName,productNumber,unitsInStock,unitPrice);
}
Regarding ItemDetails: it looks like your ItemDetails constructor, inherited from Items, takes only 4 args and you're passing it 5.

Why is my data mixed up when I compile?

There are a few things I would like some help on. First and foremost, when I compile, my product number and price get mixed up. Why? Secondly, why does the product type always return null? I would also like to combine all the message boxes but every attempt I have made fails. If someone could lead me in the right direction, I would appreciate it. Here is my code:
MAIN
package inventory4;
import java.util.Scanner;
import java.util.Arrays; //Needed to include data for arrays
import javax.swing.JOptionPane; //JOptionPane import tool
public class RunApp
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
ItemDetails theItem = new ItemDetails();
int number;
String Name = "";
String Type = "";
String sNumber = JOptionPane.showInputDialog(null,"How many items are to be put into inventory count?: ");
number = Integer.parseInt(sNumber);
ItemDetails[] inv = new ItemDetails[number];
for (int count = 0; count < inv.length; ++count)
{
Name = JOptionPane.showInputDialog(null,"What is item " + (count + 1) + "'s name?");
theItem.setName(Name);
Type = JOptionPane.showInputDialog(null,"Enter " + Name + "'s product type");
String spNumber = JOptionPane.showInputDialog(null,"Enter " + Name + "'s product number");
double pNumber = Double.parseDouble(spNumber);
theItem.setpNumber(pNumber);
String sUnits = JOptionPane.showInputDialog(null,"How many " + Name + "s are there in inventory?");
double Units = Double.parseDouble(sUnits);
theItem.setUnits(Units);
String sPrice = JOptionPane.showInputDialog(null,Name + "'s cost");
double Price = Double.parseDouble(sPrice);
theItem.setPrice(Price);
inv[count] = new ItemDetails(Name, Price, Units, pNumber);
}
for (int i = 0; i < inv.length; ++i)
{
JOptionPane.showMessageDialog(null, "Product Name: " + inv[i].getName());
//Why can't I use this instead of having multiple boxes?:
//JOptionPane.showMessageDialog(null, "Product Name: \nProduct Type: \nProduct Number: \nUnits in Stock: \nPrice Per Unit: " + inv[i].getName() + inv[i].getUniqueType() + inv[i].getpNumber() + inv[i].getUnits(), + inv[i].getPrice());
JOptionPane.showMessageDialog(null, "Product Type: " + inv[i].getUniqueType());
JOptionPane.showMessageDialog(null, "Product Number: " + inv[i].getpNumber());
JOptionPane.showMessageDialog(null, "Amount of Units in Stock: " + inv[i].getUnits());
JOptionPane.showMessageDialog(null, "Price per Unit: " + inv[i].getPrice());
JOptionPane.showMessageDialog(null, String.format("Total cost for %s in stock: $%.2f", inv[i].getName(), inv[i].calculateTotalPrice()));
JOptionPane.showMessageDialog(null,String.format("Restocking fee for %s is $%.2f", inv[i].getName(), inv[i].calculateRestock()));
String combinedData = inv[i].toString();
if(i == (inv.length -1)){
String lastItem = String.format("\nTotal Cost for all items entered: $%.2f\n", Items.getCombinedCost(inv));
combinedData = combinedData + lastItem; //combine total value to the end of the last object output
JOptionPane.showMessageDialog(null, combinedData); //Show Message
}else{
JOptionPane.showMessageDialog(null, combinedData); //Show Message
}
} //end for
} //end main
} //end class
ITEMS
package inventory4;
public class Items implements Comparable
{
private String Name;
public double pNumber, Units, Price;
String allInfo;
public Items()
{
Name = "";
pNumber = 0.0;
Units = 0.0;
Price = 0.0;
}
public int compareTo(Object item)
{
Items tmp = (Items)item;
return this.getName().compareTo(tmp.getName());
} // end compareTo method
public Items(String productName, double productNumber, double unitsInStock, double unitPrice)
{
Name = productName;
pNumber = productNumber;
Units = unitsInStock;
Price = unitPrice;
}
public String toString()
{
StringBuffer allInfo = new StringBuffer();
allInfo.append(String.format("Name: %s\n pNumber: %.0f \n Units: %.0f \n Price: %.2f\n",
getName(),getpNumber(),getUnits(),getPrice()));
return allInfo.toString();
}
//setter methods
public void setName(String n)
{
Name = n;
}
public void setpNumber(double no)
{
pNumber = no;
}
public void setUnits(double u)
{
Units = u;
}
public void setPrice(double p)
{
Price = p;
}
//getter methods
public String getName()
{
return Name;
}
public double getpNumber()
{
return pNumber;
}
public double getUnits()
{
return Units;
}
public double getPrice()
{
return Price;
}
public double calculateTotalPrice()
{
return (Units * Price);
}
public static double getCombinedCost(Items[] item) //This is used to set up the method
{
double combined = 0; //Loops through array after array is complete
for (int i = 0; i < item.length; ++i)
{
combined = combined + item[i].calculateTotalPrice(); //Sets up to combine all TotalPrice
//calculations in array
} //end loop
return combined;
} //end method
} //end class
ITEM DETAILS
package inventory4;
public class ItemDetails extends Items
{
private String UniqueType;
public ItemDetails()
{
super();
}
public ItemDetails(String productName, double productNumber, double unitsInStock, double unitPrice)
{
super(productName,productNumber,unitsInStock,unitPrice);
}
public String enterUniqueType()
{
return UniqueType;
}
public String setUniqueType()
{
return UniqueType;
}
public String getUniqueType()
{
return UniqueType;
}
public double calculateRestock() //setting up to calculate the restocking fee at 5%
{
return (Price * .05);
}
}
// getter???
public String setUniqueType() {
return UniqueType;
}
should be:
//setter
public void setUniqueType(String type) {
UniqueType = type;
}
and
inv[count] = new ItemDetails(Name, Price, Units, pNumber);
should be:
inv[count] = new ItemDetails(Name, pNumber, Units,Price );//look at the order
inv[count].setUniqueType(Type);//you have not set it.
I would also like to combine all the message boxes…
As an example, see JOptionPaneTest.
First and foremost, when I compile, my product number and price get mixed up. Why?
You're creating a new ItemDetails object with the call to
new ItemDetails(Name, Price, Units, pNumber);
but your constructor for ItemDetails is
ItemDetails(String productName, double productNumber, double unitsInStock, double unitPrice)
i.e., it takes the product number first and price last, not the other way around
Secondly, why does the product type always return null?
You're never actually setting your type, both your set and get methods do the same thing! That the setter is returning a value should've been a warning!
public String setUniqueType()
{
return UniqueType;
}
public String getUniqueType()
{
return UniqueType;
}
This is what it should be
public void setUniqueType(String type)
{
this.UniqueType = type;
}

Categories

Resources